aboutsummaryrefslogtreecommitdiff
path: root/include
diff options
context:
space:
mode:
authorEmma Miler <emma.pi@protonmail.com>2022-12-02 23:00:33 +0100
committerGitHub <noreply@github.com>2022-12-02 23:00:33 +0100
commit2d59006262d6e45f41ee325af78433475884dca4 (patch)
tree939c84779bf6a455102c74937f238a0ec05698eb /include
parentbe78dbacc5dcc95e7d9be503d61ceb5de640c661 (diff)
downloadNorthstarLauncher-2d59006262d6e45f41ee325af78433475884dca4.tar.gz
NorthstarLauncher-2d59006262d6e45f41ee325af78433475884dca4.zip
Move include directory (#337)v1.11.0-rc1
* Move include directory to shared folder This commit moves the `include` directory from the NorthstarDLL project folder to the solution folder. This allows both the DLL and Launcher project to target it properly. * Fix filters * Update memalloc.h * Fix filters * Update NorthstarLauncher.vcxproj * Remove stuff from other PR * Update NorthstarLauncher.vcxproj * Update NorthstarLauncher.vcxproj * Update NorthstarDLL.vcxproj
Diffstat (limited to 'include')
-rw-r--r--include/MinHook.h186
-rw-r--r--include/MinHook.x64.libbin0 -> 32401 bytes
-rw-r--r--include/crypto/__DECC_INCLUDE_EPILOGUE.H16
-rw-r--r--include/crypto/__DECC_INCLUDE_PROLOGUE.H20
-rw-r--r--include/crypto/aes_platform.h450
-rw-r--r--include/crypto/aria.h51
-rw-r--r--include/crypto/asn1.h149
-rw-r--r--include/crypto/asn1_dsa.h24
-rw-r--r--include/crypto/asn1err.h27
-rw-r--r--include/crypto/async.h19
-rw-r--r--include/crypto/asyncerr.h27
-rw-r--r--include/crypto/bioerr.h27
-rw-r--r--include/crypto/bn.h117
-rw-r--r--include/crypto/bn_conf.h29
-rw-r--r--include/crypto/bn_conf.h.in28
-rw-r--r--include/crypto/bn_dh.h43
-rw-r--r--include/crypto/bn_srp.h32
-rw-r--r--include/crypto/bnerr.h27
-rw-r--r--include/crypto/buffererr.h27
-rw-r--r--include/crypto/chacha.h43
-rw-r--r--include/crypto/cmll_platform.h51
-rw-r--r--include/crypto/cmperr.h30
-rw-r--r--include/crypto/cmserr.h30
-rw-r--r--include/crypto/comperr.h30
-rw-r--r--include/crypto/conferr.h27
-rw-r--r--include/crypto/crmferr.h30
-rw-r--r--include/crypto/cryptlib.h39
-rw-r--r--include/crypto/cryptoerr.h27
-rw-r--r--include/crypto/cterr.h30
-rw-r--r--include/crypto/ctype.h83
-rw-r--r--include/crypto/decoder.h42
-rw-r--r--include/crypto/decodererr.h27
-rw-r--r--include/crypto/des_platform.h35
-rw-r--r--include/crypto/dh.h61
-rw-r--r--include/crypto/dherr.h30
-rw-r--r--include/crypto/dsa.h48
-rw-r--r--include/crypto/dsaerr.h30
-rw-r--r--include/crypto/dso_conf.h18
-rw-r--r--include/crypto/dso_conf.h.in33
-rw-r--r--include/crypto/ec.h100
-rw-r--r--include/crypto/ecerr.h30
-rw-r--r--include/crypto/ecx.h150
-rw-r--r--include/crypto/encoder.h14
-rw-r--r--include/crypto/encodererr.h27
-rw-r--r--include/crypto/engine.h20
-rw-r--r--include/crypto/engineerr.h30
-rw-r--r--include/crypto/err.h20
-rw-r--r--include/crypto/ess.h76
-rw-r--r--include/crypto/esserr.h27
-rw-r--r--include/crypto/evp.h944
-rw-r--r--include/crypto/evperr.h27
-rw-r--r--include/crypto/httperr.h27
-rw-r--r--include/crypto/lhash.h16
-rw-r--r--include/crypto/md32_common.h256
-rw-r--r--include/crypto/modes.h223
-rw-r--r--include/crypto/objects.h12
-rw-r--r--include/crypto/objectserr.h27
-rw-r--r--include/crypto/ocsperr.h30
-rw-r--r--include/crypto/pem.h51
-rw-r--r--include/crypto/pemerr.h27
-rw-r--r--include/crypto/pkcs12err.h27
-rw-r--r--include/crypto/pkcs7.h19
-rw-r--r--include/crypto/pkcs7err.h27
-rw-r--r--include/crypto/poly1305.h46
-rw-r--r--include/crypto/ppc_arch.h28
-rw-r--r--include/crypto/punycode.h24
-rw-r--r--include/crypto/rand.h128
-rw-r--r--include/crypto/rand_pool.h109
-rw-r--r--include/crypto/randerr.h27
-rw-r--r--include/crypto/rsa.h129
-rw-r--r--include/crypto/rsaerr.h27
-rw-r--r--include/crypto/security_bits.h16
-rw-r--r--include/crypto/sha.h22
-rw-r--r--include/crypto/siphash.h50
-rw-r--r--include/crypto/siv.h33
-rw-r--r--include/crypto/sm2.h86
-rw-r--r--include/crypto/sm2err.h49
-rw-r--r--include/crypto/sm4.h38
-rw-r--r--include/crypto/sparc_arch.h122
-rw-r--r--include/crypto/sparse_array.h92
-rw-r--r--include/crypto/store.h21
-rw-r--r--include/crypto/storeerr.h27
-rw-r--r--include/crypto/tserr.h30
-rw-r--r--include/crypto/types.h29
-rw-r--r--include/crypto/uierr.h27
-rw-r--r--include/crypto/x509.h367
-rw-r--r--include/crypto/x509err.h27
-rw-r--r--include/crypto/x509v3err.h27
-rw-r--r--include/httplib.h7832
-rw-r--r--include/internal/__DECC_INCLUDE_EPILOGUE.H16
-rw-r--r--include/internal/__DECC_INCLUDE_PROLOGUE.H20
-rw-r--r--include/internal/asn1.h16
-rw-r--r--include/internal/bio.h91
-rw-r--r--include/internal/comp.h12
-rw-r--r--include/internal/conf.h31
-rw-r--r--include/internal/constant_time.h421
-rw-r--r--include/internal/core.h66
-rw-r--r--include/internal/cryptlib.h261
-rw-r--r--include/internal/dane.h104
-rw-r--r--include/internal/deprecated.h30
-rw-r--r--include/internal/der.h88
-rw-r--r--include/internal/dso.h164
-rw-r--r--include/internal/dsoerr.h48
-rw-r--r--include/internal/endian.h51
-rw-r--r--include/internal/err.h16
-rw-r--r--include/internal/ffc.h212
-rw-r--r--include/internal/ktls.h404
-rw-r--r--include/internal/namemap.h43
-rw-r--r--include/internal/nelem.h15
-rw-r--r--include/internal/numbers.h85
-rw-r--r--include/internal/o_dir.h53
-rw-r--r--include/internal/packet.h902
-rw-r--r--include/internal/param_build_set.h46
-rw-r--r--include/internal/passphrase.h122
-rw-r--r--include/internal/property.h93
-rw-r--r--include/internal/propertyerr.h43
-rw-r--r--include/internal/provider.h117
-rw-r--r--include/internal/refcount.h178
-rw-r--r--include/internal/sha3.h54
-rw-r--r--include/internal/sizes.h22
-rw-r--r--include/internal/sm3.h39
-rw-r--r--include/internal/sockets.h175
-rw-r--r--include/internal/sslconf.h21
-rw-r--r--include/internal/symhacks.h27
-rw-r--r--include/internal/thread_once.h151
-rw-r--r--include/internal/tlsgroups.h50
-rw-r--r--include/internal/tsan_assist.h144
-rw-r--r--include/internal/unicode.h31
-rw-r--r--include/libcrypto_static.libbin0 -> 35832383 bytes
-rw-r--r--include/libcurl/include/curl/curl.h3103
-rw-r--r--include/libcurl/include/curl/curlver.h77
-rw-r--r--include/libcurl/include/curl/easy.h123
-rw-r--r--include/libcurl/include/curl/mprintf.h50
-rw-r--r--include/libcurl/include/curl/multi.h457
-rw-r--r--include/libcurl/include/curl/options.h68
-rw-r--r--include/libcurl/include/curl/stdcheaders.h33
-rw-r--r--include/libcurl/include/curl/system.h504
-rw-r--r--include/libcurl/include/curl/typecheck-gcc.h707
-rw-r--r--include/libcurl/include/curl/urlapi.h145
-rw-r--r--include/libcurl/lib/libcurl_a.libbin0 -> 2140641 bytes
-rw-r--r--include/libssl_static.libbin0 -> 4851209 bytes
-rw-r--r--include/openssl/__DECC_INCLUDE_EPILOGUE.H22
-rw-r--r--include/openssl/__DECC_INCLUDE_PROLOGUE.H26
-rw-r--r--include/openssl/aes.h111
-rw-r--r--include/openssl/asn1.h1128
-rw-r--r--include/openssl/asn1.h.in961
-rw-r--r--include/openssl/asn1_mac.h10
-rw-r--r--include/openssl/asn1err.h140
-rw-r--r--include/openssl/asn1t.h946
-rw-r--r--include/openssl/asn1t.h.in923
-rw-r--r--include/openssl/async.h96
-rw-r--r--include/openssl/asyncerr.h29
-rw-r--r--include/openssl/bio.h884
-rw-r--r--include/openssl/bio.h.in861
-rw-r--r--include/openssl/bioerr.h65
-rw-r--r--include/openssl/blowfish.h78
-rw-r--r--include/openssl/bn.h583
-rw-r--r--include/openssl/bnerr.h46
-rw-r--r--include/openssl/buffer.h62
-rw-r--r--include/openssl/buffererr.h25
-rw-r--r--include/openssl/camellia.h117
-rw-r--r--include/openssl/cast.h71
-rw-r--r--include/openssl/cmac.h52
-rw-r--r--include/openssl/cmp.h592
-rw-r--r--include/openssl/cmp.h.in473
-rw-r--r--include/openssl/cmp_util.h56
-rw-r--r--include/openssl/cmperr.h112
-rw-r--r--include/openssl/cms.h493
-rw-r--r--include/openssl/cms.h.in395
-rw-r--r--include/openssl/cmserr.h122
-rw-r--r--include/openssl/comp.h59
-rw-r--r--include/openssl/comperr.h31
-rw-r--r--include/openssl/conf.h211
-rw-r--r--include/openssl/conf.h.in174
-rw-r--r--include/openssl/conf_api.h46
-rw-r--r--include/openssl/conferr.h51
-rw-r--r--include/openssl/configuration.h133
-rw-r--r--include/openssl/configuration.h.in69
-rw-r--r--include/openssl/conftypes.h44
-rw-r--r--include/openssl/core.h233
-rw-r--r--include/openssl/core_dispatch.h943
-rw-r--r--include/openssl/core_names.h556
-rw-r--r--include/openssl/core_object.h41
-rw-r--r--include/openssl/crmf.h227
-rw-r--r--include/openssl/crmf.h.in180
-rw-r--r--include/openssl/crmferr.h50
-rw-r--r--include/openssl/crypto.h556
-rw-r--r--include/openssl/crypto.h.in533
-rw-r--r--include/openssl/cryptoerr.h46
-rw-r--r--include/openssl/cryptoerr_legacy.h1466
-rw-r--r--include/openssl/ct.h573
-rw-r--r--include/openssl/ct.h.in525
-rw-r--r--include/openssl/cterr.h45
-rw-r--r--include/openssl/decoder.h133
-rw-r--r--include/openssl/decodererr.h28
-rw-r--r--include/openssl/des.h211
-rw-r--r--include/openssl/dh.h328
-rw-r--r--include/openssl/dherr.h57
-rw-r--r--include/openssl/dsa.h275
-rw-r--r--include/openssl/dsaerr.h43
-rw-r--r--include/openssl/dtls1.h57
-rw-r--r--include/openssl/e_os2.h305
-rw-r--r--include/openssl/ebcdic.h39
-rw-r--r--include/openssl/ec.h1566
-rw-r--r--include/openssl/ecdh.h10
-rw-r--r--include/openssl/ecdsa.h10
-rw-r--r--include/openssl/ecerr.h102
-rw-r--r--include/openssl/encoder.h124
-rw-r--r--include/openssl/encodererr.h28
-rw-r--r--include/openssl/engine.h832
-rw-r--r--include/openssl/engineerr.h63
-rw-r--r--include/openssl/err.h492
-rw-r--r--include/openssl/err.h.in481
-rw-r--r--include/openssl/ess.h128
-rw-r--r--include/openssl/ess.h.in81
-rw-r--r--include/openssl/esserr.h32
-rw-r--r--include/openssl/evp.h2170
-rw-r--r--include/openssl/evperr.h134
-rw-r--r--include/openssl/fips_names.h60
-rw-r--r--include/openssl/fipskey.h36
-rw-r--r--include/openssl/fipskey.h.in35
-rw-r--r--include/openssl/hmac.h62
-rw-r--r--include/openssl/http.h109
-rw-r--r--include/openssl/httperr.h55
-rw-r--r--include/openssl/idea.h82
-rw-r--r--include/openssl/kdf.h138
-rw-r--r--include/openssl/kdferr.h16
-rw-r--r--include/openssl/lhash.h288
-rw-r--r--include/openssl/lhash.h.in263
-rw-r--r--include/openssl/macros.h304
-rw-r--r--include/openssl/md2.h56
-rw-r--r--include/openssl/md4.h63
-rw-r--r--include/openssl/md5.h62
-rw-r--r--include/openssl/mdc2.h55
-rw-r--r--include/openssl/modes.h219
-rw-r--r--include/openssl/obj_mac.h5481
-rw-r--r--include/openssl/objects.h183
-rw-r--r--include/openssl/objectserr.h28
-rw-r--r--include/openssl/ocsp.h483
-rw-r--r--include/openssl/ocsp.h.in387
-rw-r--r--include/openssl/ocsperr.h53
-rw-r--r--include/openssl/opensslconf.h17
-rw-r--r--include/openssl/opensslv.h114
-rw-r--r--include/openssl/opensslv.h.in113
-rw-r--r--include/openssl/ossl_typ.h16
-rw-r--r--include/openssl/param_build.h63
-rw-r--r--include/openssl/params.h160
-rw-r--r--include/openssl/pem.h538
-rw-r--r--include/openssl/pem2.h19
-rw-r--r--include/openssl/pemerr.h58
-rw-r--r--include/openssl/pkcs12.h350
-rw-r--r--include/openssl/pkcs12.h.in327
-rw-r--r--include/openssl/pkcs12err.h45
-rw-r--r--include/openssl/pkcs7.h427
-rw-r--r--include/openssl/pkcs7.h.in356
-rw-r--r--include/openssl/pkcs7err.h63
-rw-r--r--include/openssl/prov_ssl.h34
-rw-r--r--include/openssl/proverr.h148
-rw-r--r--include/openssl/provider.h60
-rw-r--r--include/openssl/rand.h123
-rw-r--r--include/openssl/randerr.h68
-rw-r--r--include/openssl/rc2.h68
-rw-r--r--include/openssl/rc4.h47
-rw-r--r--include/openssl/rc5.h79
-rw-r--r--include/openssl/ripemd.h59
-rw-r--r--include/openssl/rsa.h604
-rw-r--r--include/openssl/rsaerr.h107
-rw-r--r--include/openssl/safestack.h297
-rw-r--r--include/openssl/safestack.h.in227
-rw-r--r--include/openssl/seed.h113
-rw-r--r--include/openssl/self_test.h93
-rw-r--r--include/openssl/sha.h138
-rw-r--r--include/openssl/srp.h285
-rw-r--r--include/openssl/srp.h.in214
-rw-r--r--include/openssl/srtp.h56
-rw-r--r--include/openssl/ssl.h2585
-rw-r--r--include/openssl/ssl.h.in2513
-rw-r--r--include/openssl/ssl2.h30
-rw-r--r--include/openssl/ssl3.h347
-rw-r--r--include/openssl/sslerr.h343
-rw-r--r--include/openssl/sslerr_legacy.h468
-rw-r--r--include/openssl/stack.h90
-rw-r--r--include/openssl/store.h369
-rw-r--r--include/openssl/storeerr.h49
-rw-r--r--include/openssl/symhacks.h39
-rw-r--r--include/openssl/tls1.h1223
-rw-r--r--include/openssl/trace.h312
-rw-r--r--include/openssl/ts.h503
-rw-r--r--include/openssl/tserr.h67
-rw-r--r--include/openssl/txt_db.h63
-rw-r--r--include/openssl/types.h236
-rw-r--r--include/openssl/ui.h407
-rw-r--r--include/openssl/ui.h.in384
-rw-r--r--include/openssl/uierr.h38
-rw-r--r--include/openssl/whrlpool.h62
-rw-r--r--include/openssl/x509.h1276
-rw-r--r--include/openssl/x509.h.in1082
-rw-r--r--include/openssl/x509_vfy.h894
-rw-r--r--include/openssl/x509_vfy.h.in797
-rw-r--r--include/openssl/x509err.h68
-rw-r--r--include/openssl/x509v3.h1450
-rw-r--r--include/openssl/x509v3.h.in1017
-rw-r--r--include/openssl/x509v3err.h93
-rw-r--r--include/rapidjson/allocators.h271
-rw-r--r--include/rapidjson/document.h2575
-rw-r--r--include/rapidjson/encodedstream.h299
-rw-r--r--include/rapidjson/encodings.h716
-rw-r--r--include/rapidjson/error/en.h74
-rw-r--r--include/rapidjson/error/error.h155
-rw-r--r--include/rapidjson/filereadstream.h99
-rw-r--r--include/rapidjson/filewritestream.h104
-rw-r--r--include/rapidjson/fwd.h151
-rw-r--r--include/rapidjson/internal/biginteger.h290
-rw-r--r--include/rapidjson/internal/diyfp.h258
-rw-r--r--include/rapidjson/internal/dtoa.h245
-rw-r--r--include/rapidjson/internal/ieee754.h78
-rw-r--r--include/rapidjson/internal/itoa.h304
-rw-r--r--include/rapidjson/internal/meta.h181
-rw-r--r--include/rapidjson/internal/pow10.h55
-rw-r--r--include/rapidjson/internal/regex.h701
-rw-r--r--include/rapidjson/internal/stack.h230
-rw-r--r--include/rapidjson/internal/strfunc.h55
-rw-r--r--include/rapidjson/internal/strtod.h269
-rw-r--r--include/rapidjson/internal/swap.h46
-rw-r--r--include/rapidjson/istreamwrapper.h115
-rw-r--r--include/rapidjson/memorybuffer.h70
-rw-r--r--include/rapidjson/memorystream.h71
-rw-r--r--include/rapidjson/msinttypes/inttypes.h316
-rw-r--r--include/rapidjson/msinttypes/stdint.h300
-rw-r--r--include/rapidjson/ostreamwrapper.h81
-rw-r--r--include/rapidjson/pointer.h1358
-rw-r--r--include/rapidjson/prettywriter.h255
-rw-r--r--include/rapidjson/rapidjson.h615
-rw-r--r--include/rapidjson/reader.h1879
-rw-r--r--include/rapidjson/schema.h2006
-rw-r--r--include/rapidjson/stream.h179
-rw-r--r--include/rapidjson/stringbuffer.h117
-rw-r--r--include/rapidjson/writer.h610
-rw-r--r--include/spdlog/async.h93
-rw-r--r--include/spdlog/async_logger-inl.h92
-rw-r--r--include/spdlog/async_logger.h68
-rw-r--r--include/spdlog/cfg/argv.h44
-rw-r--r--include/spdlog/cfg/env.h38
-rw-r--r--include/spdlog/cfg/helpers-inl.h120
-rw-r--r--include/spdlog/cfg/helpers.h29
-rw-r--r--include/spdlog/common-inl.h82
-rw-r--r--include/spdlog/common.h249
-rw-r--r--include/spdlog/details/backtracer-inl.h69
-rw-r--r--include/spdlog/details/backtracer.h45
-rw-r--r--include/spdlog/details/circular_q.h141
-rw-r--r--include/spdlog/details/console_globals.h32
-rw-r--r--include/spdlog/details/file_helper-inl.h147
-rw-r--r--include/spdlog/details/file_helper.h59
-rw-r--r--include/spdlog/details/fmt_helper.h116
-rw-r--r--include/spdlog/details/log_msg-inl.h37
-rw-r--r--include/spdlog/details/log_msg.h36
-rw-r--r--include/spdlog/details/log_msg_buffer-inl.h60
-rw-r--r--include/spdlog/details/log_msg_buffer.h33
-rw-r--r--include/spdlog/details/mpmc_blocking_q.h126
-rw-r--r--include/spdlog/details/null_mutex.h49
-rw-r--r--include/spdlog/details/os-inl.h589
-rw-r--r--include/spdlog/details/os.h118
-rw-r--r--include/spdlog/details/periodic_worker-inl.h49
-rw-r--r--include/spdlog/details/periodic_worker.h40
-rw-r--r--include/spdlog/details/registry-inl.h313
-rw-r--r--include/spdlog/details/registry.h115
-rw-r--r--include/spdlog/details/synchronous_factory.h24
-rw-r--r--include/spdlog/details/tcp_client-windows.h175
-rw-r--r--include/spdlog/details/tcp_client.h146
-rw-r--r--include/spdlog/details/thread_pool-inl.h129
-rw-r--r--include/spdlog/details/thread_pool.h121
-rw-r--r--include/spdlog/details/windows_include.h11
-rw-r--r--include/spdlog/fmt/bin_to_hex.h216
-rw-r--r--include/spdlog/fmt/bundled/LICENSE.rst27
-rw-r--r--include/spdlog/fmt/bundled/chrono.h1116
-rw-r--r--include/spdlog/fmt/bundled/color.h603
-rw-r--r--include/spdlog/fmt/bundled/compile.h701
-rw-r--r--include/spdlog/fmt/bundled/core.h2122
-rw-r--r--include/spdlog/fmt/bundled/format-inl.h2801
-rw-r--r--include/spdlog/fmt/bundled/format.h3960
-rw-r--r--include/spdlog/fmt/bundled/locale.h64
-rw-r--r--include/spdlog/fmt/bundled/os.h480
-rw-r--r--include/spdlog/fmt/bundled/ostream.h177
-rw-r--r--include/spdlog/fmt/bundled/posix.h2
-rw-r--r--include/spdlog/fmt/bundled/printf.h751
-rw-r--r--include/spdlog/fmt/bundled/ranges.h396
-rw-r--r--include/spdlog/fmt/chrono.h20
-rw-r--r--include/spdlog/fmt/fmt.h27
-rw-r--r--include/spdlog/fmt/ostr.h20
-rw-r--r--include/spdlog/formatter.h18
-rw-r--r--include/spdlog/fwd.h14
-rw-r--r--include/spdlog/logger-inl.h257
-rw-r--r--include/spdlog/logger.h366
-rw-r--r--include/spdlog/pattern_formatter-inl.h1395
-rw-r--r--include/spdlog/pattern_formatter.h126
-rw-r--r--include/spdlog/sinks/android_sink.h119
-rw-r--r--include/spdlog/sinks/ansicolor_sink-inl.h145
-rw-r--r--include/spdlog/sinks/ansicolor_sink.h118
-rw-r--r--include/spdlog/sinks/base_sink-inl.h63
-rw-r--r--include/spdlog/sinks/base_sink.h52
-rw-r--r--include/spdlog/sinks/basic_file_sink-inl.h43
-rw-r--r--include/spdlog/sinks/basic_file_sink.h58
-rw-r--r--include/spdlog/sinks/daily_file_sink.h238
-rw-r--r--include/spdlog/sinks/dist_sink.h97
-rw-r--r--include/spdlog/sinks/dup_filter_sink.h90
-rw-r--r--include/spdlog/sinks/hourly_file_sink.h194
-rw-r--r--include/spdlog/sinks/msvc_sink.h49
-rw-r--r--include/spdlog/sinks/null_sink.h44
-rw-r--r--include/spdlog/sinks/ostream_sink.h50
-rw-r--r--include/spdlog/sinks/ringbuffer_sink.h74
-rw-r--r--include/spdlog/sinks/rotating_file_sink-inl.h131
-rw-r--r--include/spdlog/sinks/rotating_file_sink.h78
-rw-r--r--include/spdlog/sinks/sink-inl.h25
-rw-r--r--include/spdlog/sinks/sink.h35
-rw-r--r--include/spdlog/sinks/stdout_color_sinks-inl.h38
-rw-r--r--include/spdlog/sinks/stdout_color_sinks.h45
-rw-r--r--include/spdlog/sinks/stdout_sinks-inl.h135
-rw-r--r--include/spdlog/sinks/stdout_sinks.h87
-rw-r--r--include/spdlog/sinks/syslog_sink.h109
-rw-r--r--include/spdlog/sinks/systemd_sink.h103
-rw-r--r--include/spdlog/sinks/tcp_sink.h81
-rw-r--r--include/spdlog/sinks/win_eventlog_sink.h276
-rw-r--r--include/spdlog/sinks/wincolor_sink-inl.h175
-rw-r--r--include/spdlog/sinks/wincolor_sink.h85
-rw-r--r--include/spdlog/spdlog-inl.h125
-rw-r--r--include/spdlog/spdlog.h295
-rw-r--r--include/spdlog/stopwatch.h61
-rw-r--r--include/spdlog/tweakme.h124
-rw-r--r--include/spdlog/version.h10
429 files changed, 116035 insertions, 0 deletions
diff --git a/include/MinHook.h b/include/MinHook.h
new file mode 100644
index 00000000..15c0a875
--- /dev/null
+++ b/include/MinHook.h
@@ -0,0 +1,186 @@
+/*
+ * MinHook - The Minimalistic API Hooking Library for x64/x86
+ * Copyright (C) 2009-2017 Tsuda Kageyu.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must 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.
+ */
+
+#pragma once
+
+#if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__)
+ #error MinHook supports only x86 and x64 systems.
+#endif
+
+#include <windows.h>
+
+// MinHook Error Codes.
+typedef enum MH_STATUS
+{
+ // Unknown error. Should not be returned.
+ MH_UNKNOWN = -1,
+
+ // Successful.
+ MH_OK = 0,
+
+ // MinHook is already initialized.
+ MH_ERROR_ALREADY_INITIALIZED,
+
+ // MinHook is not initialized yet, or already uninitialized.
+ MH_ERROR_NOT_INITIALIZED,
+
+ // The hook for the specified target function is already created.
+ MH_ERROR_ALREADY_CREATED,
+
+ // The hook for the specified target function is not created yet.
+ MH_ERROR_NOT_CREATED,
+
+ // The hook for the specified target function is already enabled.
+ MH_ERROR_ENABLED,
+
+ // The hook for the specified target function is not enabled yet, or already
+ // disabled.
+ MH_ERROR_DISABLED,
+
+ // The specified pointer is invalid. It points the address of non-allocated
+ // and/or non-executable region.
+ MH_ERROR_NOT_EXECUTABLE,
+
+ // The specified target function cannot be hooked.
+ MH_ERROR_UNSUPPORTED_FUNCTION,
+
+ // Failed to allocate memory.
+ MH_ERROR_MEMORY_ALLOC,
+
+ // Failed to change the memory protection.
+ MH_ERROR_MEMORY_PROTECT,
+
+ // The specified module is not loaded.
+ MH_ERROR_MODULE_NOT_FOUND,
+
+ // The specified function is not found.
+ MH_ERROR_FUNCTION_NOT_FOUND
+}
+MH_STATUS;
+
+// Can be passed as a parameter to MH_EnableHook, MH_DisableHook,
+// MH_QueueEnableHook or MH_QueueDisableHook.
+#define MH_ALL_HOOKS NULL
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ // Initialize the MinHook library. You must call this function EXACTLY ONCE
+ // at the beginning of your program.
+ MH_STATUS WINAPI MH_Initialize(VOID);
+
+ // Uninitialize the MinHook library. You must call this function EXACTLY
+ // ONCE at the end of your program.
+ MH_STATUS WINAPI MH_Uninitialize(VOID);
+
+ // Creates a Hook for the specified target function, in disabled state.
+ // Parameters:
+ // pTarget [in] A pointer to the target function, which will be
+ // overridden by the detour function.
+ // pDetour [in] A pointer to the detour function, which will override
+ // the target function.
+ // ppOriginal [out] A pointer to the trampoline function, which will be
+ // used to call the original target function.
+ // This parameter can be NULL.
+ MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal);
+
+ // Creates a Hook for the specified API function, in disabled state.
+ // Parameters:
+ // pszModule [in] A pointer to the loaded module name which contains the
+ // target function.
+ // pszTarget [in] A pointer to the target function name, which will be
+ // overridden by the detour function.
+ // pDetour [in] A pointer to the detour function, which will override
+ // the target function.
+ // ppOriginal [out] A pointer to the trampoline function, which will be
+ // used to call the original target function.
+ // This parameter can be NULL.
+ MH_STATUS WINAPI MH_CreateHookApi(
+ LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal);
+
+ // Creates a Hook for the specified API function, in disabled state.
+ // Parameters:
+ // pszModule [in] A pointer to the loaded module name which contains the
+ // target function.
+ // pszTarget [in] A pointer to the target function name, which will be
+ // overridden by the detour function.
+ // pDetour [in] A pointer to the detour function, which will override
+ // the target function.
+ // ppOriginal [out] A pointer to the trampoline function, which will be
+ // used to call the original target function.
+ // This parameter can be NULL.
+ // ppTarget [out] A pointer to the target function, which will be used
+ // with other functions.
+ // This parameter can be NULL.
+ MH_STATUS WINAPI MH_CreateHookApiEx(
+ LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget);
+
+ // Removes an already created hook.
+ // Parameters:
+ // pTarget [in] A pointer to the target function.
+ MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget);
+
+ // Enables an already created hook.
+ // Parameters:
+ // pTarget [in] A pointer to the target function.
+ // If this parameter is MH_ALL_HOOKS, all created hooks are
+ // enabled in one go.
+ MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget);
+
+ // Disables an already created hook.
+ // Parameters:
+ // pTarget [in] A pointer to the target function.
+ // If this parameter is MH_ALL_HOOKS, all created hooks are
+ // disabled in one go.
+ MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget);
+
+ // Queues to enable an already created hook.
+ // Parameters:
+ // pTarget [in] A pointer to the target function.
+ // If this parameter is MH_ALL_HOOKS, all created hooks are
+ // queued to be enabled.
+ MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget);
+
+ // Queues to disable an already created hook.
+ // Parameters:
+ // pTarget [in] A pointer to the target function.
+ // If this parameter is MH_ALL_HOOKS, all created hooks are
+ // queued to be disabled.
+ MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget);
+
+ // Applies all queued changes in one go.
+ MH_STATUS WINAPI MH_ApplyQueued(VOID);
+
+ // Translates the MH_STATUS to its name as a string.
+ const char * WINAPI MH_StatusToString(MH_STATUS status);
+
+#ifdef __cplusplus
+}
+#endif
+
diff --git a/include/MinHook.x64.lib b/include/MinHook.x64.lib
new file mode 100644
index 00000000..a346f386
--- /dev/null
+++ b/include/MinHook.x64.lib
Binary files differ
diff --git a/include/crypto/__DECC_INCLUDE_EPILOGUE.H b/include/crypto/__DECC_INCLUDE_EPILOGUE.H
new file mode 100644
index 00000000..e57c0eab
--- /dev/null
+++ b/include/crypto/__DECC_INCLUDE_EPILOGUE.H
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This file is only used by HP C on VMS, and is included automatically
+ * after each header file from this directory
+ */
+
+/* restore state. Must correspond to the save in __decc_include_prologue.h */
+#pragma names restore
diff --git a/include/crypto/__DECC_INCLUDE_PROLOGUE.H b/include/crypto/__DECC_INCLUDE_PROLOGUE.H
new file mode 100644
index 00000000..a0139575
--- /dev/null
+++ b/include/crypto/__DECC_INCLUDE_PROLOGUE.H
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This file is only used by HP C on VMS, and is included automatically
+ * after each header file from this directory
+ */
+
+/* save state */
+#pragma names save
+/* have the compiler shorten symbols larger than 31 chars to 23 chars
+ * followed by a 8 hex char CRC
+ */
+#pragma names as_is,shortened
diff --git a/include/crypto/aes_platform.h b/include/crypto/aes_platform.h
new file mode 100644
index 00000000..e95ad5aa
--- /dev/null
+++ b/include/crypto/aes_platform.h
@@ -0,0 +1,450 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_AES_PLATFORM_H
+# define OSSL_AES_PLATFORM_H
+# pragma once
+
+# include <openssl/aes.h>
+
+# ifdef VPAES_ASM
+int vpaes_set_encrypt_key(const unsigned char *userKey, int bits,
+ AES_KEY *key);
+int vpaes_set_decrypt_key(const unsigned char *userKey, int bits,
+ AES_KEY *key);
+void vpaes_encrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+void vpaes_decrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+void vpaes_cbc_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const AES_KEY *key, unsigned char *ivec, int enc);
+# endif /* VPAES_ASM */
+
+# ifdef BSAES_ASM
+void ossl_bsaes_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char ivec[16], int enc);
+void ossl_bsaes_ctr32_encrypt_blocks(const unsigned char *in,
+ unsigned char *out, size_t len,
+ const AES_KEY *key,
+ const unsigned char ivec[16]);
+void ossl_bsaes_xts_encrypt(const unsigned char *inp, unsigned char *out,
+ size_t len, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char iv[16]);
+void ossl_bsaes_xts_decrypt(const unsigned char *inp, unsigned char *out,
+ size_t len, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char iv[16]);
+# endif /* BSAES_ASM */
+
+# ifdef AES_CTR_ASM
+void AES_ctr32_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key,
+ const unsigned char ivec[AES_BLOCK_SIZE]);
+# endif /* AES_CTR_ASM */
+
+# ifdef AES_XTS_ASM
+void AES_xts_encrypt(const unsigned char *inp, unsigned char *out, size_t len,
+ const AES_KEY *key1, const AES_KEY *key2,
+ const unsigned char iv[16]);
+void AES_xts_decrypt(const unsigned char *inp, unsigned char *out, size_t len,
+ const AES_KEY *key1, const AES_KEY *key2,
+ const unsigned char iv[16]);
+# endif /* AES_XTS_ASM */
+
+# if defined(OPENSSL_CPUID_OBJ)
+# if (defined(__powerpc__) || defined(__ppc__) || defined(_ARCH_PPC))
+# include "crypto/ppc_arch.h"
+# ifdef VPAES_ASM
+# define VPAES_CAPABLE (OPENSSL_ppccap_P & PPC_ALTIVEC)
+# endif
+# define HWAES_CAPABLE (OPENSSL_ppccap_P & PPC_CRYPTO207)
+# define HWAES_set_encrypt_key aes_p8_set_encrypt_key
+# define HWAES_set_decrypt_key aes_p8_set_decrypt_key
+# define HWAES_encrypt aes_p8_encrypt
+# define HWAES_decrypt aes_p8_decrypt
+# define HWAES_cbc_encrypt aes_p8_cbc_encrypt
+# define HWAES_ctr32_encrypt_blocks aes_p8_ctr32_encrypt_blocks
+# define HWAES_xts_encrypt aes_p8_xts_encrypt
+# define HWAES_xts_decrypt aes_p8_xts_decrypt
+# endif /* PPC */
+
+# if (defined(__arm__) || defined(__arm) || defined(__aarch64__))
+# include "arm_arch.h"
+# if __ARM_MAX_ARCH__>=7
+# if defined(BSAES_ASM)
+# define BSAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON)
+# endif
+# if defined(VPAES_ASM)
+# define VPAES_CAPABLE (OPENSSL_armcap_P & ARMV7_NEON)
+# endif
+# define HWAES_CAPABLE (OPENSSL_armcap_P & ARMV8_AES)
+# define HWAES_set_encrypt_key aes_v8_set_encrypt_key
+# define HWAES_set_decrypt_key aes_v8_set_decrypt_key
+# define HWAES_encrypt aes_v8_encrypt
+# define HWAES_decrypt aes_v8_decrypt
+# define HWAES_cbc_encrypt aes_v8_cbc_encrypt
+# define HWAES_ecb_encrypt aes_v8_ecb_encrypt
+# if __ARM_MAX_ARCH__>=8 && defined(__aarch64__)
+# define HWAES_xts_encrypt aes_v8_xts_encrypt
+# define HWAES_xts_decrypt aes_v8_xts_decrypt
+# endif
+# define HWAES_ctr32_encrypt_blocks aes_v8_ctr32_encrypt_blocks
+# define AES_PMULL_CAPABLE ((OPENSSL_armcap_P & ARMV8_PMULL) && (OPENSSL_armcap_P & ARMV8_AES))
+# define AES_GCM_ENC_BYTES 512
+# define AES_GCM_DEC_BYTES 512
+# if __ARM_MAX_ARCH__>=8 && defined(__aarch64__)
+# define AES_gcm_encrypt armv8_aes_gcm_encrypt
+# define AES_gcm_decrypt armv8_aes_gcm_decrypt
+# define AES_GCM_ASM(gctx) ((gctx)->ctr==aes_v8_ctr32_encrypt_blocks && \
+ (gctx)->gcm.ghash==gcm_ghash_v8)
+size_t aes_gcm_enc_128_kernel(const uint8_t * plaintext, uint64_t plaintext_length, uint8_t * ciphertext,
+ uint64_t *Xi, unsigned char ivec[16], const void *key);
+size_t aes_gcm_enc_192_kernel(const uint8_t * plaintext, uint64_t plaintext_length, uint8_t * ciphertext,
+ uint64_t *Xi, unsigned char ivec[16], const void *key);
+size_t aes_gcm_enc_256_kernel(const uint8_t * plaintext, uint64_t plaintext_length, uint8_t * ciphertext,
+ uint64_t *Xi, unsigned char ivec[16], const void *key);
+size_t aes_gcm_dec_128_kernel(const uint8_t * ciphertext, uint64_t plaintext_length, uint8_t * plaintext,
+ uint64_t *Xi, unsigned char ivec[16], const void *key);
+size_t aes_gcm_dec_192_kernel(const uint8_t * ciphertext, uint64_t plaintext_length, uint8_t * plaintext,
+ uint64_t *Xi, unsigned char ivec[16], const void *key);
+size_t aes_gcm_dec_256_kernel(const uint8_t * ciphertext, uint64_t plaintext_length, uint8_t * plaintext,
+ uint64_t *Xi, unsigned char ivec[16], const void *key);
+size_t armv8_aes_gcm_encrypt(const unsigned char *in, unsigned char *out, size_t len, const void *key,
+ unsigned char ivec[16], u64 *Xi);
+size_t armv8_aes_gcm_decrypt(const unsigned char *in, unsigned char *out, size_t len, const void *key,
+ unsigned char ivec[16], u64 *Xi);
+void gcm_ghash_v8(u64 Xi[2],const u128 Htable[16],const u8 *inp, size_t len);
+# endif
+# endif
+# endif
+# endif /* OPENSSL_CPUID_OBJ */
+
+# if defined(AES_ASM) && ( \
+ defined(__x86_64) || defined(__x86_64__) || \
+ defined(_M_AMD64) || defined(_M_X64) )
+# define AES_CBC_HMAC_SHA_CAPABLE 1
+# define AESNI_CBC_HMAC_SHA_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(57-32)))
+# endif
+
+# if defined(AES_ASM) && !defined(I386_ONLY) && ( \
+ ((defined(__i386) || defined(__i386__) || \
+ defined(_M_IX86)) && defined(OPENSSL_IA32_SSE2))|| \
+ defined(__x86_64) || defined(__x86_64__) || \
+ defined(_M_AMD64) || defined(_M_X64) )
+
+/* AES-NI section */
+
+# define AESNI_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(57-32)))
+# ifdef VPAES_ASM
+# define VPAES_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
+# endif
+# ifdef BSAES_ASM
+# define BSAES_CAPABLE (OPENSSL_ia32cap_P[1]&(1<<(41-32)))
+# endif
+
+# define AES_GCM_ENC_BYTES 32
+# define AES_GCM_DEC_BYTES 16
+
+int aesni_set_encrypt_key(const unsigned char *userKey, int bits,
+ AES_KEY *key);
+int aesni_set_decrypt_key(const unsigned char *userKey, int bits,
+ AES_KEY *key);
+
+void aesni_encrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+void aesni_decrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+
+void aesni_ecb_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length, const AES_KEY *key, int enc);
+void aesni_cbc_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const AES_KEY *key, unsigned char *ivec, int enc);
+# ifndef OPENSSL_NO_OCB
+void aesni_ocb_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const void *key,
+ size_t start_block_num,
+ unsigned char offset_i[16],
+ const unsigned char L_[][16],
+ unsigned char checksum[16]);
+void aesni_ocb_decrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const void *key,
+ size_t start_block_num,
+ unsigned char offset_i[16],
+ const unsigned char L_[][16],
+ unsigned char checksum[16]);
+# endif /* OPENSSL_NO_OCB */
+
+void aesni_ctr32_encrypt_blocks(const unsigned char *in,
+ unsigned char *out,
+ size_t blocks,
+ const void *key, const unsigned char *ivec);
+
+void aesni_xts_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const AES_KEY *key1, const AES_KEY *key2,
+ const unsigned char iv[16]);
+
+void aesni_xts_decrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const AES_KEY *key1, const AES_KEY *key2,
+ const unsigned char iv[16]);
+
+void aesni_ccm64_encrypt_blocks(const unsigned char *in,
+ unsigned char *out,
+ size_t blocks,
+ const void *key,
+ const unsigned char ivec[16],
+ unsigned char cmac[16]);
+
+void aesni_ccm64_decrypt_blocks(const unsigned char *in,
+ unsigned char *out,
+ size_t blocks,
+ const void *key,
+ const unsigned char ivec[16],
+ unsigned char cmac[16]);
+
+# if defined(__x86_64) || defined(__x86_64__) || defined(_M_AMD64) || defined(_M_X64)
+size_t aesni_gcm_encrypt(const unsigned char *in, unsigned char *out, size_t len,
+ const void *key, unsigned char ivec[16], u64 *Xi);
+size_t aesni_gcm_decrypt(const unsigned char *in, unsigned char *out, size_t len,
+ const void *key, unsigned char ivec[16], u64 *Xi);
+void gcm_ghash_avx(u64 Xi[2], const u128 Htable[16], const u8 *in, size_t len);
+
+# define AES_gcm_encrypt aesni_gcm_encrypt
+# define AES_gcm_decrypt aesni_gcm_decrypt
+# define AES_GCM_ASM(ctx) (ctx->ctr == aesni_ctr32_encrypt_blocks && \
+ ctx->gcm.ghash == gcm_ghash_avx)
+# endif
+
+
+# elif defined(AES_ASM) && (defined(__sparc) || defined(__sparc__))
+
+/* Fujitsu SPARC64 X support */
+# include "crypto/sparc_arch.h"
+
+# define SPARC_AES_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_AES)
+# define HWAES_CAPABLE (OPENSSL_sparcv9cap_P[0] & SPARCV9_FJAESX)
+# define HWAES_set_encrypt_key aes_fx_set_encrypt_key
+# define HWAES_set_decrypt_key aes_fx_set_decrypt_key
+# define HWAES_encrypt aes_fx_encrypt
+# define HWAES_decrypt aes_fx_decrypt
+# define HWAES_cbc_encrypt aes_fx_cbc_encrypt
+# define HWAES_ctr32_encrypt_blocks aes_fx_ctr32_encrypt_blocks
+
+void aes_t4_set_encrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
+void aes_t4_set_decrypt_key(const unsigned char *key, int bits, AES_KEY *ks);
+void aes_t4_encrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+void aes_t4_decrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+/*
+ * Key-length specific subroutines were chosen for following reason.
+ * Each SPARC T4 core can execute up to 8 threads which share core's
+ * resources. Loading as much key material to registers allows to
+ * minimize references to shared memory interface, as well as amount
+ * of instructions in inner loops [much needed on T4]. But then having
+ * non-key-length specific routines would require conditional branches
+ * either in inner loops or on subroutines' entries. Former is hardly
+ * acceptable, while latter means code size increase to size occupied
+ * by multiple key-length specific subroutines, so why fight?
+ */
+void aes128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const AES_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void aes128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const AES_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void aes192_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const AES_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void aes192_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const AES_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void aes256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const AES_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void aes256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const AES_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void aes128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key,
+ unsigned char *ivec);
+void aes192_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key,
+ unsigned char *ivec);
+void aes256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key,
+ unsigned char *ivec);
+void aes128_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char *ivec);
+void aes128_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char *ivec);
+void aes256_t4_xts_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char *ivec);
+void aes256_t4_xts_decrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char *ivec);
+
+# elif defined(OPENSSL_CPUID_OBJ) && defined(__s390__)
+/* IBM S390X support */
+# include "s390x_arch.h"
+
+
+/* Convert key size to function code: [16,24,32] -> [18,19,20]. */
+# define S390X_AES_FC(keylen) (S390X_AES_128 + ((((keylen) << 3) - 128) >> 6))
+
+/* Most modes of operation need km for partial block processing. */
+# define S390X_aes_128_CAPABLE (OPENSSL_s390xcap_P.km[0] & \
+ S390X_CAPBIT(S390X_AES_128))
+# define S390X_aes_192_CAPABLE (OPENSSL_s390xcap_P.km[0] & \
+ S390X_CAPBIT(S390X_AES_192))
+# define S390X_aes_256_CAPABLE (OPENSSL_s390xcap_P.km[0] & \
+ S390X_CAPBIT(S390X_AES_256))
+
+# define S390X_aes_128_cbc_CAPABLE 1 /* checked by callee */
+# define S390X_aes_192_cbc_CAPABLE 1
+# define S390X_aes_256_cbc_CAPABLE 1
+
+# define S390X_aes_128_ecb_CAPABLE S390X_aes_128_CAPABLE
+# define S390X_aes_192_ecb_CAPABLE S390X_aes_192_CAPABLE
+# define S390X_aes_256_ecb_CAPABLE S390X_aes_256_CAPABLE
+
+# define S390X_aes_128_ofb_CAPABLE (S390X_aes_128_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmo[0] & \
+ S390X_CAPBIT(S390X_AES_128)))
+# define S390X_aes_192_ofb_CAPABLE (S390X_aes_192_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmo[0] & \
+ S390X_CAPBIT(S390X_AES_192)))
+# define S390X_aes_256_ofb_CAPABLE (S390X_aes_256_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmo[0] & \
+ S390X_CAPBIT(S390X_AES_256)))
+
+# define S390X_aes_128_cfb_CAPABLE (S390X_aes_128_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmf[0] & \
+ S390X_CAPBIT(S390X_AES_128)))
+# define S390X_aes_192_cfb_CAPABLE (S390X_aes_192_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmf[0] & \
+ S390X_CAPBIT(S390X_AES_192)))
+# define S390X_aes_256_cfb_CAPABLE (S390X_aes_256_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmf[0] & \
+ S390X_CAPBIT(S390X_AES_256)))
+# define S390X_aes_128_cfb8_CAPABLE (OPENSSL_s390xcap_P.kmf[0] & \
+ S390X_CAPBIT(S390X_AES_128))
+# define S390X_aes_192_cfb8_CAPABLE (OPENSSL_s390xcap_P.kmf[0] & \
+ S390X_CAPBIT(S390X_AES_192))
+# define S390X_aes_256_cfb8_CAPABLE (OPENSSL_s390xcap_P.kmf[0] & \
+ S390X_CAPBIT(S390X_AES_256))
+# define S390X_aes_128_cfb1_CAPABLE 0
+# define S390X_aes_192_cfb1_CAPABLE 0
+# define S390X_aes_256_cfb1_CAPABLE 0
+
+# define S390X_aes_128_ctr_CAPABLE 1 /* checked by callee */
+# define S390X_aes_192_ctr_CAPABLE 1
+# define S390X_aes_256_ctr_CAPABLE 1
+
+# define S390X_aes_128_xts_CAPABLE 1 /* checked by callee */
+# define S390X_aes_256_xts_CAPABLE 1
+
+# define S390X_aes_128_gcm_CAPABLE (S390X_aes_128_CAPABLE && \
+ (OPENSSL_s390xcap_P.kma[0] & \
+ S390X_CAPBIT(S390X_AES_128)))
+# define S390X_aes_192_gcm_CAPABLE (S390X_aes_192_CAPABLE && \
+ (OPENSSL_s390xcap_P.kma[0] & \
+ S390X_CAPBIT(S390X_AES_192)))
+# define S390X_aes_256_gcm_CAPABLE (S390X_aes_256_CAPABLE && \
+ (OPENSSL_s390xcap_P.kma[0] & \
+ S390X_CAPBIT(S390X_AES_256)))
+
+# define S390X_aes_128_ccm_CAPABLE (S390X_aes_128_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmac[0] & \
+ S390X_CAPBIT(S390X_AES_128)))
+# define S390X_aes_192_ccm_CAPABLE (S390X_aes_192_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmac[0] & \
+ S390X_CAPBIT(S390X_AES_192)))
+# define S390X_aes_256_ccm_CAPABLE (S390X_aes_256_CAPABLE && \
+ (OPENSSL_s390xcap_P.kmac[0] & \
+ S390X_CAPBIT(S390X_AES_256)))
+# define S390X_CCM_AAD_FLAG 0x40
+
+# ifndef OPENSSL_NO_OCB
+# define S390X_aes_128_ocb_CAPABLE 0
+# define S390X_aes_192_ocb_CAPABLE 0
+# define S390X_aes_256_ocb_CAPABLE 0
+# endif /* OPENSSL_NO_OCB */
+
+# ifndef OPENSSL_NO_SIV
+# define S390X_aes_128_siv_CAPABLE 0
+# define S390X_aes_192_siv_CAPABLE 0
+# define S390X_aes_256_siv_CAPABLE 0
+# endif /* OPENSSL_NO_SIV */
+
+/* Convert key size to function code: [16,24,32] -> [18,19,20]. */
+# define S390X_AES_FC(keylen) (S390X_AES_128 + ((((keylen) << 3) - 128) >> 6))
+# endif
+
+# if defined(HWAES_CAPABLE)
+int HWAES_set_encrypt_key(const unsigned char *userKey, const int bits,
+ AES_KEY *key);
+int HWAES_set_decrypt_key(const unsigned char *userKey, const int bits,
+ AES_KEY *key);
+void HWAES_encrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+void HWAES_decrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+void HWAES_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char *ivec, const int enc);
+void HWAES_ecb_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ const int enc);
+void HWAES_ctr32_encrypt_blocks(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ const unsigned char ivec[16]);
+void HWAES_xts_encrypt(const unsigned char *inp, unsigned char *out,
+ size_t len, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char iv[16]);
+void HWAES_xts_decrypt(const unsigned char *inp, unsigned char *out,
+ size_t len, const AES_KEY *key1,
+ const AES_KEY *key2, const unsigned char iv[16]);
+# ifndef OPENSSL_NO_OCB
+# ifdef HWAES_ocb_encrypt
+void HWAES_ocb_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const void *key,
+ size_t start_block_num,
+ unsigned char offset_i[16],
+ const unsigned char L_[][16],
+ unsigned char checksum[16]);
+# else
+# define HWAES_ocb_encrypt ((ocb128_f)NULL)
+# endif
+# ifdef HWAES_ocb_decrypt
+void HWAES_ocb_decrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const void *key,
+ size_t start_block_num,
+ unsigned char offset_i[16],
+ const unsigned char L_[][16],
+ unsigned char checksum[16]);
+# else
+# define HWAES_ocb_decrypt ((ocb128_f)NULL)
+# endif
+# endif /* OPENSSL_NO_OCB */
+
+# endif /* HWAES_CAPABLE */
+
+#endif /* OSSL_AES_PLATFORM_H */
diff --git a/include/crypto/aria.h b/include/crypto/aria.h
new file mode 100644
index 00000000..21a9932e
--- /dev/null
+++ b/include/crypto/aria.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+ /* Copyright (c) 2017 National Security Research Institute. All rights reserved. */
+
+#ifndef OSSL_CRYPTO_ARIA_H
+# define OSSL_CRYPTO_ARIA_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# ifdef OPENSSL_NO_ARIA
+# error ARIA is disabled.
+# endif
+
+# define ARIA_ENCRYPT 1
+# define ARIA_DECRYPT 0
+
+# define ARIA_BLOCK_SIZE 16 /* Size of each encryption/decryption block */
+# define ARIA_MAX_KEYS 17 /* Number of keys needed in the worst case */
+
+typedef union {
+ unsigned char c[ARIA_BLOCK_SIZE];
+ unsigned int u[ARIA_BLOCK_SIZE / sizeof(unsigned int)];
+} ARIA_u128;
+
+typedef unsigned char ARIA_c128[ARIA_BLOCK_SIZE];
+
+struct aria_key_st {
+ ARIA_u128 rd_key[ARIA_MAX_KEYS];
+ unsigned int rounds;
+};
+typedef struct aria_key_st ARIA_KEY;
+
+
+int ossl_aria_set_encrypt_key(const unsigned char *userKey, const int bits,
+ ARIA_KEY *key);
+int ossl_aria_set_decrypt_key(const unsigned char *userKey, const int bits,
+ ARIA_KEY *key);
+
+void ossl_aria_encrypt(const unsigned char *in, unsigned char *out,
+ const ARIA_KEY *key);
+
+#endif
diff --git a/include/crypto/asn1.h b/include/crypto/asn1.h
new file mode 100644
index 00000000..ec76ae6f
--- /dev/null
+++ b/include/crypto/asn1.h
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ASN1_H
+# define OSSL_CRYPTO_ASN1_H
+# pragma once
+
+# include <openssl/asn1.h>
+# include <openssl/core_dispatch.h> /* OSSL_FUNC_keymgmt_import() */
+
+/* Internal ASN1 structures and functions: not for application use */
+
+/* ASN1 public key method structure */
+
+#include <openssl/core.h>
+
+struct evp_pkey_asn1_method_st {
+ int pkey_id;
+ int pkey_base_id;
+ unsigned long pkey_flags;
+ char *pem_str;
+ char *info;
+ int (*pub_decode) (EVP_PKEY *pk, const X509_PUBKEY *pub);
+ int (*pub_encode) (X509_PUBKEY *pub, const EVP_PKEY *pk);
+ int (*pub_cmp) (const EVP_PKEY *a, const EVP_PKEY *b);
+ int (*pub_print) (BIO *out, const EVP_PKEY *pkey, int indent,
+ ASN1_PCTX *pctx);
+ int (*priv_decode) (EVP_PKEY *pk, const PKCS8_PRIV_KEY_INFO *p8inf);
+ int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8, const EVP_PKEY *pk);
+ int (*priv_print) (BIO *out, const EVP_PKEY *pkey, int indent,
+ ASN1_PCTX *pctx);
+ int (*pkey_size) (const EVP_PKEY *pk);
+ int (*pkey_bits) (const EVP_PKEY *pk);
+ int (*pkey_security_bits) (const EVP_PKEY *pk);
+ int (*param_decode) (EVP_PKEY *pkey,
+ const unsigned char **pder, int derlen);
+ int (*param_encode) (const EVP_PKEY *pkey, unsigned char **pder);
+ int (*param_missing) (const EVP_PKEY *pk);
+ int (*param_copy) (EVP_PKEY *to, const EVP_PKEY *from);
+ int (*param_cmp) (const EVP_PKEY *a, const EVP_PKEY *b);
+ int (*param_print) (BIO *out, const EVP_PKEY *pkey, int indent,
+ ASN1_PCTX *pctx);
+ int (*sig_print) (BIO *out,
+ const X509_ALGOR *sigalg, const ASN1_STRING *sig,
+ int indent, ASN1_PCTX *pctx);
+ void (*pkey_free) (EVP_PKEY *pkey);
+ int (*pkey_ctrl) (EVP_PKEY *pkey, int op, long arg1, void *arg2);
+ /* Legacy functions for old PEM */
+ int (*old_priv_decode) (EVP_PKEY *pkey,
+ const unsigned char **pder, int derlen);
+ int (*old_priv_encode) (const EVP_PKEY *pkey, unsigned char **pder);
+ /* Custom ASN1 signature verification */
+ int (*item_verify) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, const void *data,
+ const X509_ALGOR *a, const ASN1_BIT_STRING *sig,
+ EVP_PKEY *pkey);
+ int (*item_sign) (EVP_MD_CTX *ctx, const ASN1_ITEM *it, const void *data,
+ X509_ALGOR *alg1, X509_ALGOR *alg2,
+ ASN1_BIT_STRING *sig);
+ int (*siginf_set) (X509_SIG_INFO *siginf, const X509_ALGOR *alg,
+ const ASN1_STRING *sig);
+ /* Check */
+ int (*pkey_check) (const EVP_PKEY *pk);
+ int (*pkey_public_check) (const EVP_PKEY *pk);
+ int (*pkey_param_check) (const EVP_PKEY *pk);
+ /* Get/set raw private/public key data */
+ int (*set_priv_key) (EVP_PKEY *pk, const unsigned char *priv, size_t len);
+ int (*set_pub_key) (EVP_PKEY *pk, const unsigned char *pub, size_t len);
+ int (*get_priv_key) (const EVP_PKEY *pk, unsigned char *priv, size_t *len);
+ int (*get_pub_key) (const EVP_PKEY *pk, unsigned char *pub, size_t *len);
+
+ /* Exports and imports to / from providers */
+ size_t (*dirty_cnt) (const EVP_PKEY *pk);
+ int (*export_to) (const EVP_PKEY *pk, void *to_keydata,
+ OSSL_FUNC_keymgmt_import_fn *importer,
+ OSSL_LIB_CTX *libctx, const char *propq);
+ OSSL_CALLBACK *import_from;
+ int (*copy) (EVP_PKEY *to, EVP_PKEY *from);
+
+ int (*priv_decode_ex) (EVP_PKEY *pk,
+ const PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *libctx,
+ const char *propq);
+} /* EVP_PKEY_ASN1_METHOD */ ;
+
+DEFINE_STACK_OF_CONST(EVP_PKEY_ASN1_METHOD)
+
+extern const EVP_PKEY_ASN1_METHOD ossl_dh_asn1_meth;
+extern const EVP_PKEY_ASN1_METHOD ossl_dhx_asn1_meth;
+extern const EVP_PKEY_ASN1_METHOD ossl_dsa_asn1_meths[5];
+extern const EVP_PKEY_ASN1_METHOD ossl_eckey_asn1_meth;
+extern const EVP_PKEY_ASN1_METHOD ossl_ecx25519_asn1_meth;
+extern const EVP_PKEY_ASN1_METHOD ossl_ecx448_asn1_meth;
+extern const EVP_PKEY_ASN1_METHOD ossl_ed25519_asn1_meth;
+extern const EVP_PKEY_ASN1_METHOD ossl_ed448_asn1_meth;
+extern const EVP_PKEY_ASN1_METHOD ossl_sm2_asn1_meth;
+
+extern const EVP_PKEY_ASN1_METHOD ossl_rsa_asn1_meths[2];
+extern const EVP_PKEY_ASN1_METHOD ossl_rsa_pss_asn1_meth;
+
+/*
+ * These are used internally in the ASN1_OBJECT to keep track of whether the
+ * names and data need to be free()ed
+ */
+# define ASN1_OBJECT_FLAG_DYNAMIC 0x01/* internal use */
+# define ASN1_OBJECT_FLAG_CRITICAL 0x02/* critical x509v3 object id */
+# define ASN1_OBJECT_FLAG_DYNAMIC_STRINGS 0x04/* internal use */
+# define ASN1_OBJECT_FLAG_DYNAMIC_DATA 0x08/* internal use */
+struct asn1_object_st {
+ const char *sn, *ln;
+ int nid;
+ int length;
+ const unsigned char *data; /* data remains const after init */
+ int flags; /* Should we free this one */
+};
+
+/* ASN1 print context structure */
+
+struct asn1_pctx_st {
+ unsigned long flags;
+ unsigned long nm_flags;
+ unsigned long cert_flags;
+ unsigned long oid_flags;
+ unsigned long str_flags;
+} /* ASN1_PCTX */ ;
+
+/* ASN1 type functions */
+
+int ossl_asn1_type_set_octetstring_int(ASN1_TYPE *a, long num,
+ unsigned char *data, int len);
+int ossl_asn1_type_get_octetstring_int(const ASN1_TYPE *a, long *num,
+ unsigned char *data, int max_len);
+
+int ossl_x509_algor_new_from_md(X509_ALGOR **palg, const EVP_MD *md);
+const EVP_MD *ossl_x509_algor_get_md(X509_ALGOR *alg);
+X509_ALGOR *ossl_x509_algor_mgf1_decode(X509_ALGOR *alg);
+int ossl_x509_algor_md_to_mgf1(X509_ALGOR **palg, const EVP_MD *mgf1md);
+int ossl_asn1_time_print_ex(BIO *bp, const ASN1_TIME *tm, unsigned long flags);
+
+EVP_PKEY * ossl_d2i_PrivateKey_legacy(int keytype, EVP_PKEY **a,
+ const unsigned char **pp, long length,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+#endif /* ndef OSSL_CRYPTO_ASN1_H */
diff --git a/include/crypto/asn1_dsa.h b/include/crypto/asn1_dsa.h
new file mode 100644
index 00000000..3eadb9ec
--- /dev/null
+++ b/include/crypto/asn1_dsa.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ASN1_DSA_H
+# define OSSL_CRYPTO_ASN1_DSA_H
+# pragma once
+
+#include "internal/packet.h"
+
+int ossl_encode_der_length(WPACKET *pkt, size_t cont_len);
+int ossl_encode_der_integer(WPACKET *pkt, const BIGNUM *n);
+int ossl_encode_der_dsa_sig(WPACKET *pkt, const BIGNUM *r, const BIGNUM *s);
+int ossl_decode_der_length(PACKET *pkt, PACKET *subpkt);
+int ossl_decode_der_integer(PACKET *pkt, BIGNUM *n);
+size_t ossl_decode_der_dsa_sig(BIGNUM *r, BIGNUM *s, const unsigned char **ppin,
+ size_t len);
+
+#endif
diff --git a/include/crypto/asn1err.h b/include/crypto/asn1err.h
new file mode 100644
index 00000000..6441386b
--- /dev/null
+++ b/include/crypto/asn1err.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ASN1ERR_H
+# define OSSL_CRYPTO_ASN1ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_ASN1_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/async.h b/include/crypto/async.h
new file mode 100644
index 00000000..7bc0dbb6
--- /dev/null
+++ b/include/crypto/async.h
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ASYNC_H
+# define OSSL_CRYPTO_ASYNC_H
+# pragma once
+
+# include <openssl/async.h>
+
+int async_init(void);
+void async_deinit(void);
+
+#endif
diff --git a/include/crypto/asyncerr.h b/include/crypto/asyncerr.h
new file mode 100644
index 00000000..574e0af7
--- /dev/null
+++ b/include/crypto/asyncerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ASYNCERR_H
+# define OSSL_CRYPTO_ASYNCERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_ASYNC_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/bioerr.h b/include/crypto/bioerr.h
new file mode 100644
index 00000000..a0c06099
--- /dev/null
+++ b/include/crypto/bioerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_BIOERR_H
+# define OSSL_CRYPTO_BIOERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_BIO_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/bn.h b/include/crypto/bn.h
new file mode 100644
index 00000000..cf69bea8
--- /dev/null
+++ b/include/crypto/bn.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_BN_H
+# define OSSL_CRYPTO_BN_H
+# pragma once
+
+# include <openssl/bn.h>
+# include <limits.h>
+
+BIGNUM *bn_wexpand(BIGNUM *a, int words);
+BIGNUM *bn_expand2(BIGNUM *a, int words);
+
+void bn_correct_top(BIGNUM *a);
+
+/*
+ * Determine the modified width-(w+1) Non-Adjacent Form (wNAF) of 'scalar'.
+ * This is an array r[] of values that are either zero or odd with an
+ * absolute value less than 2^w satisfying scalar = \sum_j r[j]*2^j where at
+ * most one of any w+1 consecutive digits is non-zero with the exception that
+ * the most significant digit may be only w-1 zeros away from that next
+ * non-zero digit.
+ */
+signed char *bn_compute_wNAF(const BIGNUM *scalar, int w, size_t *ret_len);
+
+int bn_get_top(const BIGNUM *a);
+
+int bn_get_dmax(const BIGNUM *a);
+
+/* Set all words to zero */
+void bn_set_all_zero(BIGNUM *a);
+
+/*
+ * Copy the internal BIGNUM words into out which holds size elements (and size
+ * must be bigger than top)
+ */
+int bn_copy_words(BN_ULONG *out, const BIGNUM *in, int size);
+
+BN_ULONG *bn_get_words(const BIGNUM *a);
+
+/*
+ * Set the internal data words in a to point to words which contains size
+ * elements. The BN_FLG_STATIC_DATA flag is set
+ */
+void bn_set_static_words(BIGNUM *a, const BN_ULONG *words, int size);
+
+/*
+ * Copy words into the BIGNUM |a|, reallocating space as necessary.
+ * The negative flag of |a| is not modified.
+ * Returns 1 on success and 0 on failure.
+ */
+/*
+ * |num_words| is int because bn_expand2 takes an int. This is an internal
+ * function so we simply trust callers not to pass negative values.
+ */
+int bn_set_words(BIGNUM *a, const BN_ULONG *words, int num_words);
+
+/*
+ * Some BIGNUM functions assume most significant limb to be non-zero, which
+ * is customarily arranged by bn_correct_top. Output from below functions
+ * is not processed with bn_correct_top, and for this reason it may not be
+ * returned out of public API. It may only be passed internally into other
+ * functions known to support non-minimal or zero-padded BIGNUMs. Even
+ * though the goal is to facilitate constant-time-ness, not each subroutine
+ * is constant-time by itself. They all have pre-conditions, consult source
+ * code...
+ */
+int bn_mul_mont_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ BN_MONT_CTX *mont, BN_CTX *ctx);
+int bn_to_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
+ BN_CTX *ctx);
+int bn_from_mont_fixed_top(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
+ BN_CTX *ctx);
+int bn_mod_add_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const BIGNUM *m);
+int bn_mod_sub_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const BIGNUM *m);
+int bn_mul_fixed_top(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
+int bn_sqr_fixed_top(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx);
+int bn_lshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n);
+int bn_rshift_fixed_top(BIGNUM *r, const BIGNUM *a, int n);
+int bn_div_fixed_top(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
+ const BIGNUM *d, BN_CTX *ctx);
+
+#define BN_PRIMETEST_COMPOSITE 0
+#define BN_PRIMETEST_COMPOSITE_WITH_FACTOR 1
+#define BN_PRIMETEST_COMPOSITE_NOT_POWER_OF_PRIME 2
+#define BN_PRIMETEST_PROBABLY_PRIME 3
+
+int ossl_bn_miller_rabin_is_prime(const BIGNUM *w, int iterations, BN_CTX *ctx,
+ BN_GENCB *cb, int enhanced, int *status);
+
+const BIGNUM *ossl_bn_get0_small_factors(void);
+
+int ossl_bn_rsa_fips186_4_gen_prob_primes(BIGNUM *p, BIGNUM *Xpout,
+ BIGNUM *p1, BIGNUM *p2,
+ const BIGNUM *Xp, const BIGNUM *Xp1,
+ const BIGNUM *Xp2, int nlen,
+ const BIGNUM *e, BN_CTX *ctx,
+ BN_GENCB *cb);
+
+int ossl_bn_rsa_fips186_4_derive_prime(BIGNUM *Y, BIGNUM *X, const BIGNUM *Xin,
+ const BIGNUM *r1, const BIGNUM *r2,
+ int nlen, const BIGNUM *e, BN_CTX *ctx,
+ BN_GENCB *cb);
+
+OSSL_LIB_CTX *ossl_bn_get_libctx(BN_CTX *ctx);
+
+extern const BIGNUM ossl_bn_inv_sqrt_2;
+
+#endif
diff --git a/include/crypto/bn_conf.h b/include/crypto/bn_conf.h
new file mode 100644
index 00000000..a6f73d4a
--- /dev/null
+++ b/include/crypto/bn_conf.h
@@ -0,0 +1,29 @@
+/* WARNING: do not edit! */
+/* Generated by makefile from include\crypto\bn_conf.h.in */
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_BN_CONF_H
+# define OSSL_CRYPTO_BN_CONF_H
+# pragma once
+
+/*
+ * The contents of this file are not used in the UEFI build, as
+ * both 32-bit and 64-bit builds are supported from a single run
+ * of the Configure script.
+ */
+
+/* Should we define BN_DIV2W here? */
+
+/* Only one for the following should be defined */
+#undef SIXTY_FOUR_BIT_LONG
+#define SIXTY_FOUR_BIT
+#undef THIRTY_TWO_BIT
+
+#endif
diff --git a/include/crypto/bn_conf.h.in b/include/crypto/bn_conf.h.in
new file mode 100644
index 00000000..dbc901b1
--- /dev/null
+++ b/include/crypto/bn_conf.h.in
@@ -0,0 +1,28 @@
+{- join("\n",map { "/* $_ */" } @autowarntext) -}
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_BN_CONF_H
+# define OSSL_CRYPTO_BN_CONF_H
+# pragma once
+
+/*
+ * The contents of this file are not used in the UEFI build, as
+ * both 32-bit and 64-bit builds are supported from a single run
+ * of the Configure script.
+ */
+
+/* Should we define BN_DIV2W here? */
+
+/* Only one for the following should be defined */
+{- $config{b64l} ? "#define" : "#undef" -} SIXTY_FOUR_BIT_LONG
+{- $config{b64} ? "#define" : "#undef" -} SIXTY_FOUR_BIT
+{- $config{b32} ? "#define" : "#undef" -} THIRTY_TWO_BIT
+
+#endif
diff --git a/include/crypto/bn_dh.h b/include/crypto/bn_dh.h
new file mode 100644
index 00000000..6d12c20e
--- /dev/null
+++ b/include/crypto/bn_dh.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#define declare_dh_bn(x) \
+ extern const BIGNUM ossl_bignum_dh##x##_p; \
+ extern const BIGNUM ossl_bignum_dh##x##_q; \
+ extern const BIGNUM ossl_bignum_dh##x##_g; \
+
+declare_dh_bn(1024_160)
+declare_dh_bn(2048_224)
+declare_dh_bn(2048_256)
+
+extern const BIGNUM ossl_bignum_const_2;
+
+extern const BIGNUM ossl_bignum_ffdhe2048_p;
+extern const BIGNUM ossl_bignum_ffdhe3072_p;
+extern const BIGNUM ossl_bignum_ffdhe4096_p;
+extern const BIGNUM ossl_bignum_ffdhe6144_p;
+extern const BIGNUM ossl_bignum_ffdhe8192_p;
+extern const BIGNUM ossl_bignum_ffdhe2048_q;
+extern const BIGNUM ossl_bignum_ffdhe3072_q;
+extern const BIGNUM ossl_bignum_ffdhe4096_q;
+extern const BIGNUM ossl_bignum_ffdhe6144_q;
+extern const BIGNUM ossl_bignum_ffdhe8192_q;
+
+extern const BIGNUM ossl_bignum_modp_1536_p;
+extern const BIGNUM ossl_bignum_modp_2048_p;
+extern const BIGNUM ossl_bignum_modp_3072_p;
+extern const BIGNUM ossl_bignum_modp_4096_p;
+extern const BIGNUM ossl_bignum_modp_6144_p;
+extern const BIGNUM ossl_bignum_modp_8192_p;
+extern const BIGNUM ossl_bignum_modp_1536_q;
+extern const BIGNUM ossl_bignum_modp_2048_q;
+extern const BIGNUM ossl_bignum_modp_3072_q;
+extern const BIGNUM ossl_bignum_modp_4096_q;
+extern const BIGNUM ossl_bignum_modp_6144_q;
+extern const BIGNUM ossl_bignum_modp_8192_q;
diff --git a/include/crypto/bn_srp.h b/include/crypto/bn_srp.h
new file mode 100644
index 00000000..00b160aa
--- /dev/null
+++ b/include/crypto/bn_srp.h
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_NO_SRP
+
+extern const BIGNUM ossl_bn_group_1024;
+
+extern const BIGNUM ossl_bn_group_1536;
+
+extern const BIGNUM ossl_bn_group_2048;
+
+extern const BIGNUM ossl_bn_group_3072;
+
+extern const BIGNUM ossl_bn_group_4096;
+
+extern const BIGNUM ossl_bn_group_6144;
+
+extern const BIGNUM ossl_bn_group_8192;
+
+extern const BIGNUM ossl_bn_generator_19;
+
+extern const BIGNUM ossl_bn_generator_5;
+
+extern const BIGNUM ossl_bn_generator_2;
+
+#endif
diff --git a/include/crypto/bnerr.h b/include/crypto/bnerr.h
new file mode 100644
index 00000000..7282c915
--- /dev/null
+++ b/include/crypto/bnerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_BNERR_H
+# define OSSL_CRYPTO_BNERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_BN_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/buffererr.h b/include/crypto/buffererr.h
new file mode 100644
index 00000000..54976d95
--- /dev/null
+++ b/include/crypto/buffererr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_BUFFERERR_H
+# define OSSL_CRYPTO_BUFFERERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_BUF_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/chacha.h b/include/crypto/chacha.h
new file mode 100644
index 00000000..d29998ff
--- /dev/null
+++ b/include/crypto/chacha.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CHACHA_H
+#define OSSL_CRYPTO_CHACHA_H
+# pragma once
+
+#include <stddef.h>
+
+/*
+ * ChaCha20_ctr32 encrypts |len| bytes from |inp| with the given key and
+ * nonce and writes the result to |out|, which may be equal to |inp|.
+ * The |key| is not 32 bytes of verbatim key material though, but the
+ * said material collected into 8 32-bit elements array in host byte
+ * order. Same approach applies to nonce: the |counter| argument is
+ * pointer to concatenated nonce and counter values collected into 4
+ * 32-bit elements. This, passing crypto material collected into 32-bit
+ * elements as opposite to passing verbatim byte vectors, is chosen for
+ * efficiency in multi-call scenarios.
+ */
+void ChaCha20_ctr32(unsigned char *out, const unsigned char *inp,
+ size_t len, const unsigned int key[8],
+ const unsigned int counter[4]);
+/*
+ * You can notice that there is no key setup procedure. Because it's
+ * as trivial as collecting bytes into 32-bit elements, it's reckoned
+ * that below macro is sufficient.
+ */
+#define CHACHA_U8TOU32(p) ( \
+ ((unsigned int)(p)[0]) | ((unsigned int)(p)[1]<<8) | \
+ ((unsigned int)(p)[2]<<16) | ((unsigned int)(p)[3]<<24) )
+
+#define CHACHA_KEY_SIZE 32
+#define CHACHA_CTR_SIZE 16
+#define CHACHA_BLK_SIZE 64
+
+#endif
diff --git a/include/crypto/cmll_platform.h b/include/crypto/cmll_platform.h
new file mode 100644
index 00000000..8cadadf6
--- /dev/null
+++ b/include/crypto/cmll_platform.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CMLL_PLATFORM_H
+# define OSSL_CMLL_PLATFORM_H
+# pragma once
+
+# if defined(CMLL_ASM) && (defined(__sparc) || defined(__sparc__))
+
+/* Fujitsu SPARC64 X support */
+# include "crypto/sparc_arch.h"
+
+# ifndef OPENSSL_NO_CAMELLIA
+# define SPARC_CMLL_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_CAMELLIA)
+# include <openssl/camellia.h>
+
+void cmll_t4_set_key(const unsigned char *key, int bits, CAMELLIA_KEY *ks);
+void cmll_t4_encrypt(const unsigned char *in, unsigned char *out,
+ const CAMELLIA_KEY *key);
+void cmll_t4_decrypt(const unsigned char *in, unsigned char *out,
+ const CAMELLIA_KEY *key);
+
+void cmll128_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const CAMELLIA_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void cmll128_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const CAMELLIA_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void cmll256_t4_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const CAMELLIA_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void cmll256_t4_cbc_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const CAMELLIA_KEY *key,
+ unsigned char *ivec, int /*unused*/);
+void cmll128_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const CAMELLIA_KEY *key,
+ unsigned char *ivec);
+void cmll256_t4_ctr32_encrypt(const unsigned char *in, unsigned char *out,
+ size_t blocks, const CAMELLIA_KEY *key,
+ unsigned char *ivec);
+# endif /* OPENSSL_NO_CAMELLIA */
+
+# endif /* CMLL_ASM && sparc */
+
+#endif /* OSSL_CRYPTO_CIPHERMODE_PLATFORM_H */
diff --git a/include/crypto/cmperr.h b/include/crypto/cmperr.h
new file mode 100644
index 00000000..ac61dd48
--- /dev/null
+++ b/include/crypto/cmperr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CMPERR_H
+# define OSSL_CRYPTO_CMPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_CMP
+
+int ossl_err_load_CMP_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/cmserr.h b/include/crypto/cmserr.h
new file mode 100644
index 00000000..1de2f9c7
--- /dev/null
+++ b/include/crypto/cmserr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CMSERR_H
+# define OSSL_CRYPTO_CMSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_CMS
+
+int ossl_err_load_CMS_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/comperr.h b/include/crypto/comperr.h
new file mode 100644
index 00000000..0fd9c6de
--- /dev/null
+++ b/include/crypto/comperr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_COMPERR_H
+# define OSSL_CRYPTO_COMPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_COMP
+
+int ossl_err_load_COMP_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/conferr.h b/include/crypto/conferr.h
new file mode 100644
index 00000000..cb367e4f
--- /dev/null
+++ b/include/crypto/conferr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CONFERR_H
+# define OSSL_CRYPTO_CONFERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_CONF_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/crmferr.h b/include/crypto/crmferr.h
new file mode 100644
index 00000000..f1a27e04
--- /dev/null
+++ b/include/crypto/crmferr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CRMFERR_H
+# define OSSL_CRYPTO_CRMFERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_CRMF
+
+int ossl_err_load_CRMF_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/cryptlib.h b/include/crypto/cryptlib.h
new file mode 100644
index 00000000..39a956bf
--- /dev/null
+++ b/include/crypto/cryptlib.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CRYPTLIB_H
+# define OSSL_CRYPTO_CRYPTLIB_H
+# pragma once
+
+# include <openssl/core.h>
+# include "internal/cryptlib.h"
+
+/* This file is not scanned by mkdef.pl, whereas cryptlib.h is */
+
+int ossl_init_thread_start(const void *index, void *arg,
+ OSSL_thread_stop_handler_fn handfn);
+int ossl_init_thread_deregister(void *index);
+int ossl_init_thread(void);
+void ossl_cleanup_thread(void);
+void ossl_ctx_thread_stop(OSSL_LIB_CTX *ctx);
+
+/*
+ * OPENSSL_INIT flags. The primary list of these is in crypto.h. Flags below
+ * are those omitted from crypto.h because they are "reserved for internal
+ * use".
+ */
+# define OPENSSL_INIT_BASE_ONLY 0x00040000L
+
+void ossl_trace_cleanup(void);
+void ossl_malloc_setup_failures(void);
+
+int ossl_crypto_alloc_ex_data_intern(int class_index, void *obj,
+ CRYPTO_EX_DATA *ad, int idx);
+
+#endif /* OSSL_CRYPTO_CRYPTLIB_H */
diff --git a/include/crypto/cryptoerr.h b/include/crypto/cryptoerr.h
new file mode 100644
index 00000000..288b87ac
--- /dev/null
+++ b/include/crypto/cryptoerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CRYPTOERR_H
+# define OSSL_CRYPTO_CRYPTOERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_CRYPTO_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/cterr.h b/include/crypto/cterr.h
new file mode 100644
index 00000000..760bc796
--- /dev/null
+++ b/include/crypto/cterr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_CTERR_H
+# define OSSL_CRYPTO_CTERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_CT
+
+int ossl_err_load_CT_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/ctype.h b/include/crypto/ctype.h
new file mode 100644
index 00000000..a35c137e
--- /dev/null
+++ b/include/crypto/ctype.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This version of ctype.h provides a standardised and platform
+ * independent implementation that supports seven bit ASCII characters.
+ * The specific intent is to not pass extended ASCII characters (> 127)
+ * even if the host operating system would.
+ *
+ * There is EBCDIC support included for machines which use this. However,
+ * there are a number of concerns about how well EBCDIC is supported
+ * throughout the rest of the source code. Refer to issue #4154 for
+ * details.
+ */
+#ifndef OSSL_CRYPTO_CTYPE_H
+# define OSSL_CRYPTO_CTYPE_H
+# pragma once
+
+# define CTYPE_MASK_lower 0x1
+# define CTYPE_MASK_upper 0x2
+# define CTYPE_MASK_digit 0x4
+# define CTYPE_MASK_space 0x8
+# define CTYPE_MASK_xdigit 0x10
+# define CTYPE_MASK_blank 0x20
+# define CTYPE_MASK_cntrl 0x40
+# define CTYPE_MASK_graph 0x80
+# define CTYPE_MASK_print 0x100
+# define CTYPE_MASK_punct 0x200
+# define CTYPE_MASK_base64 0x400
+# define CTYPE_MASK_asn1print 0x800
+
+# define CTYPE_MASK_alpha (CTYPE_MASK_lower | CTYPE_MASK_upper)
+# define CTYPE_MASK_alnum (CTYPE_MASK_alpha | CTYPE_MASK_digit)
+
+/*
+ * The ascii mask assumes that any other classification implies that
+ * the character is ASCII and that there are no ASCII characters
+ * that aren't in any of the classifications.
+ *
+ * This assumption holds at the moment, but it might not in the future.
+ */
+# define CTYPE_MASK_ascii (~0)
+
+# ifdef CHARSET_EBCDIC
+int ossl_toascii(int c);
+int ossl_fromascii(int c);
+# else
+# define ossl_toascii(c) (c)
+# define ossl_fromascii(c) (c)
+# endif
+int ossl_ctype_check(int c, unsigned int mask);
+int ossl_tolower(int c);
+int ossl_toupper(int c);
+
+int ossl_ascii_isdigit(const char inchar);
+
+# define ossl_isalnum(c) (ossl_ctype_check((c), CTYPE_MASK_alnum))
+# define ossl_isalpha(c) (ossl_ctype_check((c), CTYPE_MASK_alpha))
+# ifdef CHARSET_EBCDIC
+# define ossl_isascii(c) (ossl_ctype_check((c), CTYPE_MASK_ascii))
+# else
+# define ossl_isascii(c) (((c) & ~127) == 0)
+# endif
+# define ossl_isblank(c) (ossl_ctype_check((c), CTYPE_MASK_blank))
+# define ossl_iscntrl(c) (ossl_ctype_check((c), CTYPE_MASK_cntrl))
+# define ossl_isdigit(c) (ossl_ctype_check((c), CTYPE_MASK_digit))
+# define ossl_isgraph(c) (ossl_ctype_check((c), CTYPE_MASK_graph))
+# define ossl_islower(c) (ossl_ctype_check((c), CTYPE_MASK_lower))
+# define ossl_isprint(c) (ossl_ctype_check((c), CTYPE_MASK_print))
+# define ossl_ispunct(c) (ossl_ctype_check((c), CTYPE_MASK_punct))
+# define ossl_isspace(c) (ossl_ctype_check((c), CTYPE_MASK_space))
+# define ossl_isupper(c) (ossl_ctype_check((c), CTYPE_MASK_upper))
+# define ossl_isxdigit(c) (ossl_ctype_check((c), CTYPE_MASK_xdigit))
+# define ossl_isbase64(c) (ossl_ctype_check((c), CTYPE_MASK_base64))
+# define ossl_isasn1print(c) (ossl_ctype_check((c), CTYPE_MASK_asn1print))
+
+#endif
diff --git a/include/crypto/decoder.h b/include/crypto/decoder.h
new file mode 100644
index 00000000..cc06ef29
--- /dev/null
+++ b/include/crypto/decoder.h
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DECODER_H
+# define OSSL_CRYPTO_DECODER_H
+# pragma once
+
+# include <openssl/decoder.h>
+
+OSSL_DECODER *ossl_decoder_fetch_by_number(OSSL_LIB_CTX *libctx,
+ int id,
+ const char *properties);
+
+/*
+ * These are specially made for the 'file:' provider-native loader, which
+ * uses this to install a DER to anything decoder, which doesn't do much
+ * except read a DER blob and pass it on as a provider object abstraction
+ * (provider-object(7)).
+ */
+void *ossl_decoder_from_algorithm(int id, const OSSL_ALGORITHM *algodef,
+ OSSL_PROVIDER *prov);
+
+OSSL_DECODER_INSTANCE *
+ossl_decoder_instance_new(OSSL_DECODER *decoder, void *decoderctx);
+void ossl_decoder_instance_free(OSSL_DECODER_INSTANCE *decoder_inst);
+int ossl_decoder_ctx_add_decoder_inst(OSSL_DECODER_CTX *ctx,
+ OSSL_DECODER_INSTANCE *di);
+
+int ossl_decoder_ctx_setup_for_pkey(OSSL_DECODER_CTX *ctx,
+ EVP_PKEY **pkey, const char *keytype,
+ OSSL_LIB_CTX *libctx,
+ const char *propquery);
+
+int ossl_decoder_get_number(const OSSL_DECODER *encoder);
+
+#endif
diff --git a/include/crypto/decodererr.h b/include/crypto/decodererr.h
new file mode 100644
index 00000000..d7badc43
--- /dev/null
+++ b/include/crypto/decodererr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DECODERERR_H
+# define OSSL_CRYPTO_DECODERERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_OSSL_DECODER_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/des_platform.h b/include/crypto/des_platform.h
new file mode 100644
index 00000000..07ea1ddd
--- /dev/null
+++ b/include/crypto/des_platform.h
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_DES_PLATFORM_H
+# define OSSL_DES_PLATFORM_H
+# pragma once
+
+# if defined(DES_ASM) && (defined(__sparc) || defined(__sparc__))
+
+/* Fujitsu SPARC64 X support */
+# include "crypto/sparc_arch.h"
+
+# ifndef OPENSSL_NO_DES
+# define SPARC_DES_CAPABLE (OPENSSL_sparcv9cap_P[1] & CFR_DES)
+# include <openssl/des.h>
+void des_t4_key_expand(const void *key, DES_key_schedule *ks);
+void des_t4_ede3_cbc_encrypt(const void *inp, void *out, size_t len,
+ const DES_key_schedule ks[3], unsigned char iv[8]);
+void des_t4_ede3_cbc_decrypt(const void *inp, void *out, size_t len,
+ const DES_key_schedule ks[3], unsigned char iv[8]);
+void des_t4_cbc_encrypt(const void *inp, void *out, size_t len,
+ const DES_key_schedule *ks, unsigned char iv[8]);
+void des_t4_cbc_decrypt(const void *inp, void *out, size_t len,
+ const DES_key_schedule *ks, unsigned char iv[8]);
+# endif /* OPENSSL_NO_DES */
+
+# endif /* DES_ASM && sparc */
+
+#endif /* OSSL_CRYPTO_CIPHERMODE_PLATFORM_H */
diff --git a/include/crypto/dh.h b/include/crypto/dh.h
new file mode 100644
index 00000000..f6be4ae0
--- /dev/null
+++ b/include/crypto/dh.h
@@ -0,0 +1,61 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DH_H
+# define OSSL_CRYPTO_DH_H
+# pragma once
+
+# include <openssl/core.h>
+# include <openssl/params.h>
+# include <openssl/dh.h>
+# include "internal/ffc.h"
+
+DH *ossl_dh_new_by_nid_ex(OSSL_LIB_CTX *libctx, int nid);
+DH *ossl_dh_new_ex(OSSL_LIB_CTX *libctx);
+void ossl_dh_set0_libctx(DH *d, OSSL_LIB_CTX *libctx);
+int ossl_dh_generate_ffc_parameters(DH *dh, int type, int pbits, int qbits,
+ BN_GENCB *cb);
+int ossl_dh_generate_public_key(BN_CTX *ctx, const DH *dh,
+ const BIGNUM *priv_key, BIGNUM *pub_key);
+int ossl_dh_get_named_group_uid_from_size(int pbits);
+const char *ossl_dh_gen_type_id2name(int id);
+int ossl_dh_gen_type_name2id(const char *name, int type);
+void ossl_dh_cache_named_group(DH *dh);
+int ossl_dh_is_named_safe_prime_group(const DH *dh);
+
+FFC_PARAMS *ossl_dh_get0_params(DH *dh);
+int ossl_dh_get0_nid(const DH *dh);
+int ossl_dh_params_fromdata(DH *dh, const OSSL_PARAM params[]);
+int ossl_dh_key_fromdata(DH *dh, const OSSL_PARAM params[]);
+int ossl_dh_params_todata(DH *dh, OSSL_PARAM_BLD *bld, OSSL_PARAM params[]);
+int ossl_dh_key_todata(DH *dh, OSSL_PARAM_BLD *bld, OSSL_PARAM params[]);
+DH *ossl_dh_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int ossl_dh_compute_key(unsigned char *key, const BIGNUM *pub_key, DH *dh);
+
+int ossl_dh_check_pub_key_partial(const DH *dh, const BIGNUM *pub_key, int *ret);
+int ossl_dh_check_priv_key(const DH *dh, const BIGNUM *priv_key, int *ret);
+int ossl_dh_check_pairwise(const DH *dh);
+
+const DH_METHOD *ossl_dh_get_method(const DH *dh);
+
+int ossl_dh_buf2key(DH *key, const unsigned char *buf, size_t len);
+size_t ossl_dh_key2buf(const DH *dh, unsigned char **pbuf, size_t size,
+ int alloc);
+
+int ossl_dh_kdf_X9_42_asn1(unsigned char *out, size_t outlen,
+ const unsigned char *Z, size_t Zlen,
+ const char *cek_alg,
+ const unsigned char *ukm, size_t ukmlen,
+ const EVP_MD *md,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int ossl_dh_is_foreign(const DH *dh);
+DH *ossl_dh_dup(const DH *dh, int selection);
+
+#endif /* OSSL_CRYPTO_DH_H */
diff --git a/include/crypto/dherr.h b/include/crypto/dherr.h
new file mode 100644
index 00000000..bb24d131
--- /dev/null
+++ b/include/crypto/dherr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DHERR_H
+# define OSSL_CRYPTO_DHERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DH
+
+int ossl_err_load_DH_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/dsa.h b/include/crypto/dsa.h
new file mode 100644
index 00000000..eedbd8c7
--- /dev/null
+++ b/include/crypto/dsa.h
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DSAERR_H
+# define OSSL_CRYPTO_DSAERR_H
+# pragma once
+
+# include <openssl/core.h>
+# include <openssl/dsa.h>
+# include "internal/ffc.h"
+
+#define DSA_PARAMGEN_TYPE_FIPS_186_4 0 /* Use FIPS186-4 standard */
+#define DSA_PARAMGEN_TYPE_FIPS_186_2 1 /* Use legacy FIPS186-2 standard */
+#define DSA_PARAMGEN_TYPE_FIPS_DEFAULT 2
+
+DSA *ossl_dsa_new(OSSL_LIB_CTX *libctx);
+void ossl_dsa_set0_libctx(DSA *d, OSSL_LIB_CTX *libctx);
+
+int ossl_dsa_generate_ffc_parameters(DSA *dsa, int type, int pbits, int qbits,
+ BN_GENCB *cb);
+
+int ossl_dsa_sign_int(int type, const unsigned char *dgst, int dlen,
+ unsigned char *sig, unsigned int *siglen, DSA *dsa);
+
+FFC_PARAMS *ossl_dsa_get0_params(DSA *dsa);
+int ossl_dsa_ffc_params_fromdata(DSA *dsa, const OSSL_PARAM params[]);
+int ossl_dsa_key_fromdata(DSA *dsa, const OSSL_PARAM params[]);
+DSA *ossl_dsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+int ossl_dsa_generate_public_key(BN_CTX *ctx, const DSA *dsa,
+ const BIGNUM *priv_key, BIGNUM *pub_key);
+int ossl_dsa_check_params(const DSA *dsa, int checktype, int *ret);
+int ossl_dsa_check_pub_key(const DSA *dsa, const BIGNUM *pub_key, int *ret);
+int ossl_dsa_check_pub_key_partial(const DSA *dsa, const BIGNUM *pub_key,
+ int *ret);
+int ossl_dsa_check_priv_key(const DSA *dsa, const BIGNUM *priv_key, int *ret);
+int ossl_dsa_check_pairwise(const DSA *dsa);
+int ossl_dsa_is_foreign(const DSA *dsa);
+DSA *ossl_dsa_dup(const DSA *dsa, int selection);
+
+#endif
diff --git a/include/crypto/dsaerr.h b/include/crypto/dsaerr.h
new file mode 100644
index 00000000..9898097d
--- /dev/null
+++ b/include/crypto/dsaerr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DSAERR_H
+# define OSSL_CRYPTO_DSAERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DSA
+
+int ossl_err_load_DSA_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/dso_conf.h b/include/crypto/dso_conf.h
new file mode 100644
index 00000000..99514321
--- /dev/null
+++ b/include/crypto/dso_conf.h
@@ -0,0 +1,18 @@
+/* WARNING: do not edit! */
+/* Generated by makefile from include\crypto\dso_conf.h.in */
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DSO_CONF_H
+# define OSSL_CRYPTO_DSO_CONF_H
+# pragma once
+
+# define DSO_WIN32
+# define DSO_EXTENSION ".dll"
+#endif
diff --git a/include/crypto/dso_conf.h.in b/include/crypto/dso_conf.h.in
new file mode 100644
index 00000000..12de11ad
--- /dev/null
+++ b/include/crypto/dso_conf.h.in
@@ -0,0 +1,33 @@
+{- join("\n",map { "/* $_ */" } @autowarntext) -}
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_DSO_CONF_H
+# define OSSL_CRYPTO_DSO_CONF_H
+# pragma once
+
+{- # The DSO code currently always implements all functions so that no
+ # applications will have to worry about that from a compilation point
+ # of view. However, the "method"s may return zero unless that platform
+ # has support compiled in for them. Currently each method is enabled
+ # by a define "DSO_<name>" ... we translate the "dso_scheme" config
+ # string entry into using the following logic;
+ my $scheme = $disabled{dso} ? undef : uc $target{dso_scheme};
+ if (!$scheme) {
+ $scheme = "NONE";
+ }
+ my @macros = ( "DSO_$scheme" );
+ if ($scheme eq 'DLFCN') {
+ @macros = ( "DSO_DLFCN", "HAVE_DLFCN_H" );
+ } elsif ($scheme eq "DLFCN_NO_H") {
+ @macros = ( "DSO_DLFCN" );
+ }
+ join("\n", map { "# define $_" } @macros); -}
+# define DSO_EXTENSION "{- platform->dsoext() -}"
+#endif
diff --git a/include/crypto/ec.h b/include/crypto/ec.h
new file mode 100644
index 00000000..62163b31
--- /dev/null
+++ b/include/crypto/ec.h
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/* Internal EC functions for other submodules: not for application use */
+
+#ifndef OSSL_CRYPTO_EC_H
+# define OSSL_CRYPTO_EC_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/evp.h>
+
+int ossl_ec_curve_name2nid(const char *name);
+const char *ossl_ec_curve_nid2nist_int(int nid);
+int ossl_ec_curve_nist2nid_int(const char *name);
+int evp_pkey_ctx_set_ec_param_enc_prov(EVP_PKEY_CTX *ctx, int param_enc);
+
+# ifndef OPENSSL_NO_EC
+# include <openssl/core.h>
+# include <openssl/ec.h>
+# include "crypto/types.h"
+
+/*-
+ * Computes the multiplicative inverse of x in the range
+ * [1,EC_GROUP::order), where EC_GROUP::order is the cardinality of the
+ * subgroup generated by the generator G:
+ *
+ * res := x^(-1) (mod EC_GROUP::order).
+ *
+ * This function expects the following two conditions to hold:
+ * - the EC_GROUP order is prime, and
+ * - x is included in the range [1, EC_GROUP::order).
+ *
+ * This function returns 1 on success, 0 on error.
+ *
+ * If the EC_GROUP order is even, this function explicitly returns 0 as
+ * an error.
+ * In case any of the two conditions stated above is not satisfied,
+ * the correctness of its output is not guaranteed, even if the return
+ * value could still be 1 (as primality testing and a conditional modular
+ * reduction round on the input can be omitted by the underlying
+ * implementations for better SCA properties on regular input values).
+ */
+__owur int ossl_ec_group_do_inverse_ord(const EC_GROUP *group, BIGNUM *res,
+ const BIGNUM *x, BN_CTX *ctx);
+
+/*-
+ * ECDH Key Derivation Function as defined in ANSI X9.63
+ */
+int ossl_ecdh_kdf_X9_63(unsigned char *out, size_t outlen,
+ const unsigned char *Z, size_t Zlen,
+ const unsigned char *sinfo, size_t sinfolen,
+ const EVP_MD *md, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+int ossl_ec_key_public_check(const EC_KEY *eckey, BN_CTX *ctx);
+int ossl_ec_key_public_check_quick(const EC_KEY *eckey, BN_CTX *ctx);
+int ossl_ec_key_private_check(const EC_KEY *eckey);
+int ossl_ec_key_pairwise_check(const EC_KEY *eckey, BN_CTX *ctx);
+OSSL_LIB_CTX *ossl_ec_key_get_libctx(const EC_KEY *eckey);
+const char *ossl_ec_key_get0_propq(const EC_KEY *eckey);
+void ossl_ec_key_set0_libctx(EC_KEY *key, OSSL_LIB_CTX *libctx);
+
+/* Backend support */
+int ossl_ec_group_todata(const EC_GROUP *group, OSSL_PARAM_BLD *tmpl,
+ OSSL_PARAM params[], OSSL_LIB_CTX *libctx,
+ const char *propq,
+ BN_CTX *bnctx, unsigned char **genbuf);
+int ossl_ec_group_fromdata(EC_KEY *ec, const OSSL_PARAM params[]);
+int ossl_ec_group_set_params(EC_GROUP *group, const OSSL_PARAM params[]);
+int ossl_ec_key_fromdata(EC_KEY *ecx, const OSSL_PARAM params[],
+ int include_private);
+int ossl_ec_key_otherparams_fromdata(EC_KEY *ec, const OSSL_PARAM params[]);
+int ossl_ec_key_is_foreign(const EC_KEY *ec);
+EC_KEY *ossl_ec_key_dup(const EC_KEY *key, int selection);
+int ossl_x509_algor_is_sm2(const X509_ALGOR *palg);
+EC_KEY *ossl_ec_key_param_from_x509_algor(const X509_ALGOR *palg,
+ OSSL_LIB_CTX *libctx,
+ const char *propq);
+EC_KEY *ossl_ec_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+int ossl_ec_set_ecdh_cofactor_mode(EC_KEY *ec, int mode);
+int ossl_ec_encoding_name2id(const char *name);
+int ossl_ec_encoding_param2id(const OSSL_PARAM *p, int *id);
+int ossl_ec_pt_format_name2id(const char *name);
+int ossl_ec_pt_format_param2id(const OSSL_PARAM *p, int *id);
+char *ossl_ec_pt_format_id2name(int id);
+
+char *ossl_ec_check_group_type_id2name(int flags);
+int ossl_ec_set_check_group_type_from_name(EC_KEY *ec, const char *name);
+
+# endif /* OPENSSL_NO_EC */
+#endif
diff --git a/include/crypto/ecerr.h b/include/crypto/ecerr.h
new file mode 100644
index 00000000..07b6c7aa
--- /dev/null
+++ b/include/crypto/ecerr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ECERR_H
+# define OSSL_CRYPTO_ECERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_EC
+
+int ossl_err_load_EC_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/ecx.h b/include/crypto/ecx.h
new file mode 100644
index 00000000..48b95fa5
--- /dev/null
+++ b/include/crypto/ecx.h
@@ -0,0 +1,150 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/* Internal EC functions for other submodules: not for application use */
+
+#ifndef OSSL_CRYPTO_ECX_H
+# define OSSL_CRYPTO_ECX_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_EC
+
+# include <openssl/core.h>
+# include <openssl/e_os2.h>
+# include <openssl/crypto.h>
+# include "internal/refcount.h"
+# include "crypto/types.h"
+
+# define X25519_KEYLEN 32
+# define X448_KEYLEN 56
+# define ED25519_KEYLEN 32
+# define ED448_KEYLEN 57
+
+# define MAX_KEYLEN ED448_KEYLEN
+
+# define X25519_BITS 253
+# define X25519_SECURITY_BITS 128
+
+# define X448_BITS 448
+# define X448_SECURITY_BITS 224
+
+# define ED25519_BITS 256
+/* RFC8032 Section 8.5 */
+# define ED25519_SECURITY_BITS 128
+# define ED25519_SIGSIZE 64
+
+# define ED448_BITS 456
+/* RFC8032 Section 8.5 */
+# define ED448_SECURITY_BITS 224
+# define ED448_SIGSIZE 114
+
+
+typedef enum {
+ ECX_KEY_TYPE_X25519,
+ ECX_KEY_TYPE_X448,
+ ECX_KEY_TYPE_ED25519,
+ ECX_KEY_TYPE_ED448
+} ECX_KEY_TYPE;
+
+#define KEYTYPE2NID(type) \
+ ((type) == ECX_KEY_TYPE_X25519 \
+ ? EVP_PKEY_X25519 \
+ : ((type) == ECX_KEY_TYPE_X448 \
+ ? EVP_PKEY_X448 \
+ : ((type) == ECX_KEY_TYPE_ED25519 \
+ ? EVP_PKEY_ED25519 \
+ : EVP_PKEY_ED448)))
+
+struct ecx_key_st {
+ OSSL_LIB_CTX *libctx;
+ char *propq;
+ unsigned int haspubkey:1;
+ unsigned char pubkey[MAX_KEYLEN];
+ unsigned char *privkey;
+ size_t keylen;
+ ECX_KEY_TYPE type;
+ CRYPTO_REF_COUNT references;
+ CRYPTO_RWLOCK *lock;
+};
+
+size_t ossl_ecx_key_length(ECX_KEY_TYPE type);
+ECX_KEY *ossl_ecx_key_new(OSSL_LIB_CTX *libctx, ECX_KEY_TYPE type,
+ int haspubkey, const char *propq);
+void ossl_ecx_key_set0_libctx(ECX_KEY *key, OSSL_LIB_CTX *libctx);
+unsigned char *ossl_ecx_key_allocate_privkey(ECX_KEY *key);
+void ossl_ecx_key_free(ECX_KEY *key);
+int ossl_ecx_key_up_ref(ECX_KEY *key);
+ECX_KEY *ossl_ecx_key_dup(const ECX_KEY *key, int selection);
+
+int ossl_x25519(uint8_t out_shared_key[32], const uint8_t private_key[32],
+ const uint8_t peer_public_value[32]);
+void ossl_x25519_public_from_private(uint8_t out_public_value[32],
+ const uint8_t private_key[32]);
+
+int
+ossl_ed25519_public_from_private(OSSL_LIB_CTX *ctx, uint8_t out_public_key[32],
+ const uint8_t private_key[32],
+ const char *propq);
+int
+ossl_ed25519_sign(uint8_t *out_sig, const uint8_t *message, size_t message_len,
+ const uint8_t public_key[32], const uint8_t private_key[32],
+ OSSL_LIB_CTX *libctx, const char *propq);
+int
+ossl_ed25519_verify(const uint8_t *message, size_t message_len,
+ const uint8_t signature[64], const uint8_t public_key[32],
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+int
+ossl_ed448_public_from_private(OSSL_LIB_CTX *ctx, uint8_t out_public_key[57],
+ const uint8_t private_key[57], const char *propq);
+int
+ossl_ed448_sign(OSSL_LIB_CTX *ctx, uint8_t *out_sig, const uint8_t *message,
+ size_t message_len, const uint8_t public_key[57],
+ const uint8_t private_key[57], const uint8_t *context,
+ size_t context_len, const char *propq);
+
+int
+ossl_ed448_verify(OSSL_LIB_CTX *ctx, const uint8_t *message, size_t message_len,
+ const uint8_t signature[114], const uint8_t public_key[57],
+ const uint8_t *context, size_t context_len, const char *propq);
+
+int
+ossl_x448(uint8_t out_shared_key[56], const uint8_t private_key[56],
+ const uint8_t peer_public_value[56]);
+void
+ossl_x448_public_from_private(uint8_t out_public_value[56],
+ const uint8_t private_key[56]);
+
+
+/* Backend support */
+typedef enum {
+ KEY_OP_PUBLIC,
+ KEY_OP_PRIVATE,
+ KEY_OP_KEYGEN
+} ecx_key_op_t;
+
+ECX_KEY *ossl_ecx_key_op(const X509_ALGOR *palg,
+ const unsigned char *p, int plen,
+ int pkey_id, ecx_key_op_t op,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+int ossl_ecx_public_from_private(ECX_KEY *key);
+int ossl_ecx_key_fromdata(ECX_KEY *ecx, const OSSL_PARAM params[],
+ int include_private);
+ECX_KEY *ossl_ecx_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+ECX_KEY *ossl_evp_pkey_get1_X25519(EVP_PKEY *pkey);
+ECX_KEY *ossl_evp_pkey_get1_X448(EVP_PKEY *pkey);
+ECX_KEY *ossl_evp_pkey_get1_ED25519(EVP_PKEY *pkey);
+ECX_KEY *ossl_evp_pkey_get1_ED448(EVP_PKEY *pkey);
+# endif /* OPENSSL_NO_EC */
+#endif
diff --git a/include/crypto/encoder.h b/include/crypto/encoder.h
new file mode 100644
index 00000000..09d445d2
--- /dev/null
+++ b/include/crypto/encoder.h
@@ -0,0 +1,14 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <openssl/types.h>
+
+OSSL_ENCODER *ossl_encoder_fetch_by_number(OSSL_LIB_CTX *libctx, int id,
+ const char *properties);
+int ossl_encoder_get_number(const OSSL_ENCODER *encoder);
diff --git a/include/crypto/encodererr.h b/include/crypto/encodererr.h
new file mode 100644
index 00000000..56c45823
--- /dev/null
+++ b/include/crypto/encodererr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ENCODERERR_H
+# define OSSL_CRYPTO_ENCODERERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_OSSL_ENCODER_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/engine.h b/include/crypto/engine.h
new file mode 100644
index 00000000..fac6ed09
--- /dev/null
+++ b/include/crypto/engine.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <openssl/engine.h>
+
+void engine_load_openssl_int(void);
+void engine_load_devcrypto_int(void);
+void engine_load_rdrand_int(void);
+void engine_load_dynamic_int(void);
+void engine_load_padlock_int(void);
+void engine_load_capi_int(void);
+void engine_load_dasync_int(void);
+void engine_load_afalg_int(void);
+void engine_cleanup_int(void);
diff --git a/include/crypto/engineerr.h b/include/crypto/engineerr.h
new file mode 100644
index 00000000..737c841d
--- /dev/null
+++ b/include/crypto/engineerr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ENGINEERR_H
+# define OSSL_CRYPTO_ENGINEERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_ENGINE
+
+int ossl_err_load_ENGINE_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/err.h b/include/crypto/err.h
new file mode 100644
index 00000000..15ec6fd0
--- /dev/null
+++ b/include/crypto/err.h
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ERR_H
+# define OSSL_CRYPTO_ERR_H
+# pragma once
+
+int ossl_err_load_ERR_strings(void);
+int ossl_err_load_crypto_strings(void);
+void err_cleanup(void);
+int err_shelve_state(void **);
+void err_unshelve_state(void *);
+
+#endif
diff --git a/include/crypto/ess.h b/include/crypto/ess.h
new file mode 100644
index 00000000..7acde5f8
--- /dev/null
+++ b/include/crypto/ess.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ESS_H
+# define OSSL_CRYPTO_ESS_H
+# pragma once
+
+/*-
+ * IssuerSerial ::= SEQUENCE {
+ * issuer GeneralNames,
+ * serialNumber CertificateSerialNumber
+ * }
+ */
+
+struct ESS_issuer_serial {
+ STACK_OF(GENERAL_NAME) *issuer;
+ ASN1_INTEGER *serial;
+};
+
+/*-
+ * ESSCertID ::= SEQUENCE {
+ * certHash Hash,
+ * issuerSerial IssuerSerial OPTIONAL
+ * }
+ */
+
+struct ESS_cert_id {
+ ASN1_OCTET_STRING *hash; /* Always SHA-1 digest. */
+ ESS_ISSUER_SERIAL *issuer_serial;
+};
+
+/*-
+ * SigningCertificate ::= SEQUENCE {
+ * certs SEQUENCE OF ESSCertID,
+ * policies SEQUENCE OF PolicyInformation OPTIONAL
+ * }
+ */
+
+struct ESS_signing_cert {
+ STACK_OF(ESS_CERT_ID) *cert_ids;
+ STACK_OF(POLICYINFO) *policy_info;
+};
+
+/*-
+ * ESSCertIDv2 ::= SEQUENCE {
+ * hashAlgorithm AlgorithmIdentifier DEFAULT id-sha256,
+ * certHash Hash,
+ * issuerSerial IssuerSerial OPTIONAL
+ * }
+ */
+
+struct ESS_cert_id_v2_st {
+ X509_ALGOR *hash_alg; /* Default: SHA-256 */
+ ASN1_OCTET_STRING *hash;
+ ESS_ISSUER_SERIAL *issuer_serial;
+};
+
+/*-
+ * SigningCertificateV2 ::= SEQUENCE {
+ * certs SEQUENCE OF ESSCertIDv2,
+ * policies SEQUENCE OF PolicyInformation OPTIONAL
+ * }
+ */
+
+struct ESS_signing_cert_v2_st {
+ STACK_OF(ESS_CERT_ID_V2) *cert_ids;
+ STACK_OF(POLICYINFO) *policy_info;
+};
+
+#endif /* OSSL_CRYPTO_ESS_H */
diff --git a/include/crypto/esserr.h b/include/crypto/esserr.h
new file mode 100644
index 00000000..8df2df11
--- /dev/null
+++ b/include/crypto/esserr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_ESSERR_H
+# define OSSL_CRYPTO_ESSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_ESS_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/evp.h b/include/crypto/evp.h
new file mode 100644
index 00000000..c5d3a930
--- /dev/null
+++ b/include/crypto/evp.h
@@ -0,0 +1,944 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_EVP_H
+# define OSSL_CRYPTO_EVP_H
+# pragma once
+
+# include <openssl/evp.h>
+# include <openssl/core_dispatch.h>
+# include "internal/refcount.h"
+# include "crypto/ecx.h"
+
+/*
+ * Don't free up md_ctx->pctx in EVP_MD_CTX_reset, use the reserved flag
+ * values in evp.h
+ */
+#define EVP_MD_CTX_FLAG_KEEP_PKEY_CTX 0x0400
+
+#define evp_pkey_ctx_is_legacy(ctx) \
+ ((ctx)->keymgmt == NULL)
+#define evp_pkey_ctx_is_provided(ctx) \
+ (!evp_pkey_ctx_is_legacy(ctx))
+
+struct evp_pkey_ctx_st {
+ /* Actual operation */
+ int operation;
+
+ /*
+ * Library context, property query, keytype and keymgmt associated with
+ * this context
+ */
+ OSSL_LIB_CTX *libctx;
+ char *propquery;
+ const char *keytype;
+ /* If |pkey| below is set, this field is always a reference to its keymgmt */
+ EVP_KEYMGMT *keymgmt;
+
+ union {
+ struct {
+ void *genctx;
+ } keymgmt;
+
+ struct {
+ EVP_KEYEXCH *exchange;
+ /*
+ * Opaque ctx returned from a providers exchange algorithm
+ * implementation OSSL_FUNC_keyexch_newctx()
+ */
+ void *algctx;
+ } kex;
+
+ struct {
+ EVP_SIGNATURE *signature;
+ /*
+ * Opaque ctx returned from a providers signature algorithm
+ * implementation OSSL_FUNC_signature_newctx()
+ */
+ void *algctx;
+ } sig;
+
+ struct {
+ EVP_ASYM_CIPHER *cipher;
+ /*
+ * Opaque ctx returned from a providers asymmetric cipher algorithm
+ * implementation OSSL_FUNC_asym_cipher_newctx()
+ */
+ void *algctx;
+ } ciph;
+ struct {
+ EVP_KEM *kem;
+ /*
+ * Opaque ctx returned from a providers KEM algorithm
+ * implementation OSSL_FUNC_kem_newctx()
+ */
+ void *algctx;
+ } encap;
+ } op;
+
+ /*
+ * Cached parameters. Inits of operations that depend on these should
+ * call evp_pkey_ctx_use_delayed_data() when the operation has been set
+ * up properly.
+ */
+ struct {
+ /* Distinguishing Identifier, ISO/IEC 15946-3, FIPS 196 */
+ char *dist_id_name; /* The name used with EVP_PKEY_CTX_ctrl_str() */
+ void *dist_id; /* The distinguishing ID itself */
+ size_t dist_id_len; /* The length of the distinguishing ID */
+
+ /* Indicators of what has been set. Keep them together! */
+ unsigned int dist_id_set : 1;
+ } cached_parameters;
+
+ /* Application specific data, usually used by the callback */
+ void *app_data;
+ /* Keygen callback */
+ EVP_PKEY_gen_cb *pkey_gencb;
+ /* implementation specific keygen data */
+ int *keygen_info;
+ int keygen_info_count;
+
+ /* Legacy fields below */
+
+ /* EVP_PKEY identity */
+ int legacy_keytype;
+ /* Method associated with this operation */
+ const EVP_PKEY_METHOD *pmeth;
+ /* Engine that implements this method or NULL if builtin */
+ ENGINE *engine;
+ /* Key: may be NULL */
+ EVP_PKEY *pkey;
+ /* Peer key for key agreement, may be NULL */
+ EVP_PKEY *peerkey;
+ /* Algorithm specific data */
+ void *data;
+ /* Indicator if digest_custom needs to be called */
+ unsigned int flag_call_digest_custom:1;
+ /*
+ * Used to support taking custody of memory in the case of a provider being
+ * used with the deprecated EVP_PKEY_CTX_set_rsa_keygen_pubexp() API. This
+ * member should NOT be used for any other purpose and should be removed
+ * when said deprecated API is excised completely.
+ */
+ BIGNUM *rsa_pubexp;
+} /* EVP_PKEY_CTX */ ;
+
+#define EVP_PKEY_FLAG_DYNAMIC 1
+
+struct evp_pkey_method_st {
+ int pkey_id;
+ int flags;
+ int (*init) (EVP_PKEY_CTX *ctx);
+ int (*copy) (EVP_PKEY_CTX *dst, const EVP_PKEY_CTX *src);
+ void (*cleanup) (EVP_PKEY_CTX *ctx);
+ int (*paramgen_init) (EVP_PKEY_CTX *ctx);
+ int (*paramgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
+ int (*keygen_init) (EVP_PKEY_CTX *ctx);
+ int (*keygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey);
+ int (*sign_init) (EVP_PKEY_CTX *ctx);
+ int (*sign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
+ const unsigned char *tbs, size_t tbslen);
+ int (*verify_init) (EVP_PKEY_CTX *ctx);
+ int (*verify) (EVP_PKEY_CTX *ctx,
+ const unsigned char *sig, size_t siglen,
+ const unsigned char *tbs, size_t tbslen);
+ int (*verify_recover_init) (EVP_PKEY_CTX *ctx);
+ int (*verify_recover) (EVP_PKEY_CTX *ctx,
+ unsigned char *rout, size_t *routlen,
+ const unsigned char *sig, size_t siglen);
+ int (*signctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx);
+ int (*signctx) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
+ EVP_MD_CTX *mctx);
+ int (*verifyctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx);
+ int (*verifyctx) (EVP_PKEY_CTX *ctx, const unsigned char *sig, int siglen,
+ EVP_MD_CTX *mctx);
+ int (*encrypt_init) (EVP_PKEY_CTX *ctx);
+ int (*encrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen);
+ int (*decrypt_init) (EVP_PKEY_CTX *ctx);
+ int (*decrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen);
+ int (*derive_init) (EVP_PKEY_CTX *ctx);
+ int (*derive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen);
+ int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1, void *p2);
+ int (*ctrl_str) (EVP_PKEY_CTX *ctx, const char *type, const char *value);
+ int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen,
+ const unsigned char *tbs, size_t tbslen);
+ int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig,
+ size_t siglen, const unsigned char *tbs,
+ size_t tbslen);
+ int (*check) (EVP_PKEY *pkey);
+ int (*public_check) (EVP_PKEY *pkey);
+ int (*param_check) (EVP_PKEY *pkey);
+
+ int (*digest_custom) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx);
+} /* EVP_PKEY_METHOD */ ;
+
+DEFINE_STACK_OF_CONST(EVP_PKEY_METHOD)
+
+void evp_pkey_set_cb_translate(BN_GENCB *cb, EVP_PKEY_CTX *ctx);
+
+const EVP_PKEY_METHOD *ossl_dh_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_dhx_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_dsa_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_ec_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_ecx25519_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_ecx448_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_ed25519_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_ed448_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_rsa_pkey_method(void);
+const EVP_PKEY_METHOD *ossl_rsa_pss_pkey_method(void);
+
+struct evp_mac_st {
+ OSSL_PROVIDER *prov;
+ int name_id;
+ char *type_name;
+ const char *description;
+
+ CRYPTO_REF_COUNT refcnt;
+ CRYPTO_RWLOCK *lock;
+
+ OSSL_FUNC_mac_newctx_fn *newctx;
+ OSSL_FUNC_mac_dupctx_fn *dupctx;
+ OSSL_FUNC_mac_freectx_fn *freectx;
+ OSSL_FUNC_mac_init_fn *init;
+ OSSL_FUNC_mac_update_fn *update;
+ OSSL_FUNC_mac_final_fn *final;
+ OSSL_FUNC_mac_gettable_params_fn *gettable_params;
+ OSSL_FUNC_mac_gettable_ctx_params_fn *gettable_ctx_params;
+ OSSL_FUNC_mac_settable_ctx_params_fn *settable_ctx_params;
+ OSSL_FUNC_mac_get_params_fn *get_params;
+ OSSL_FUNC_mac_get_ctx_params_fn *get_ctx_params;
+ OSSL_FUNC_mac_set_ctx_params_fn *set_ctx_params;
+};
+
+struct evp_kdf_st {
+ OSSL_PROVIDER *prov;
+ int name_id;
+ char *type_name;
+ const char *description;
+ CRYPTO_REF_COUNT refcnt;
+ CRYPTO_RWLOCK *lock;
+
+ OSSL_FUNC_kdf_newctx_fn *newctx;
+ OSSL_FUNC_kdf_dupctx_fn *dupctx;
+ OSSL_FUNC_kdf_freectx_fn *freectx;
+ OSSL_FUNC_kdf_reset_fn *reset;
+ OSSL_FUNC_kdf_derive_fn *derive;
+ OSSL_FUNC_kdf_gettable_params_fn *gettable_params;
+ OSSL_FUNC_kdf_gettable_ctx_params_fn *gettable_ctx_params;
+ OSSL_FUNC_kdf_settable_ctx_params_fn *settable_ctx_params;
+ OSSL_FUNC_kdf_get_params_fn *get_params;
+ OSSL_FUNC_kdf_get_ctx_params_fn *get_ctx_params;
+ OSSL_FUNC_kdf_set_ctx_params_fn *set_ctx_params;
+};
+
+#define EVP_ORIG_DYNAMIC 0
+#define EVP_ORIG_GLOBAL 1
+#define EVP_ORIG_METH 2
+
+struct evp_md_st {
+ /* nid */
+ int type;
+
+ /* Legacy structure members */
+ int pkey_type;
+ int md_size;
+ unsigned long flags;
+ int origin;
+ int (*init) (EVP_MD_CTX *ctx);
+ int (*update) (EVP_MD_CTX *ctx, const void *data, size_t count);
+ int (*final) (EVP_MD_CTX *ctx, unsigned char *md);
+ int (*copy) (EVP_MD_CTX *to, const EVP_MD_CTX *from);
+ int (*cleanup) (EVP_MD_CTX *ctx);
+ int block_size;
+ int ctx_size; /* how big does the ctx->md_data need to be */
+ /* control function */
+ int (*md_ctrl) (EVP_MD_CTX *ctx, int cmd, int p1, void *p2);
+
+ /* New structure members */
+ /* Above comment to be removed when legacy has gone */
+ int name_id;
+ char *type_name;
+ const char *description;
+ OSSL_PROVIDER *prov;
+ CRYPTO_REF_COUNT refcnt;
+ CRYPTO_RWLOCK *lock;
+ OSSL_FUNC_digest_newctx_fn *newctx;
+ OSSL_FUNC_digest_init_fn *dinit;
+ OSSL_FUNC_digest_update_fn *dupdate;
+ OSSL_FUNC_digest_final_fn *dfinal;
+ OSSL_FUNC_digest_digest_fn *digest;
+ OSSL_FUNC_digest_freectx_fn *freectx;
+ OSSL_FUNC_digest_dupctx_fn *dupctx;
+ OSSL_FUNC_digest_get_params_fn *get_params;
+ OSSL_FUNC_digest_set_ctx_params_fn *set_ctx_params;
+ OSSL_FUNC_digest_get_ctx_params_fn *get_ctx_params;
+ OSSL_FUNC_digest_gettable_params_fn *gettable_params;
+ OSSL_FUNC_digest_settable_ctx_params_fn *settable_ctx_params;
+ OSSL_FUNC_digest_gettable_ctx_params_fn *gettable_ctx_params;
+
+} /* EVP_MD */ ;
+
+struct evp_cipher_st {
+ int nid;
+
+ int block_size;
+ /* Default value for variable length ciphers */
+ int key_len;
+ int iv_len;
+
+ /* Legacy structure members */
+ /* Various flags */
+ unsigned long flags;
+ /* How the EVP_CIPHER was created. */
+ int origin;
+ /* init key */
+ int (*init) (EVP_CIPHER_CTX *ctx, const unsigned char *key,
+ const unsigned char *iv, int enc);
+ /* encrypt/decrypt data */
+ int (*do_cipher) (EVP_CIPHER_CTX *ctx, unsigned char *out,
+ const unsigned char *in, size_t inl);
+ /* cleanup ctx */
+ int (*cleanup) (EVP_CIPHER_CTX *);
+ /* how big ctx->cipher_data needs to be */
+ int ctx_size;
+ /* Populate a ASN1_TYPE with parameters */
+ int (*set_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *);
+ /* Get parameters from a ASN1_TYPE */
+ int (*get_asn1_parameters) (EVP_CIPHER_CTX *, ASN1_TYPE *);
+ /* Miscellaneous operations */
+ int (*ctrl) (EVP_CIPHER_CTX *, int type, int arg, void *ptr);
+ /* Application data */
+ void *app_data;
+
+ /* New structure members */
+ /* Above comment to be removed when legacy has gone */
+ int name_id;
+ char *type_name;
+ const char *description;
+ OSSL_PROVIDER *prov;
+ CRYPTO_REF_COUNT refcnt;
+ CRYPTO_RWLOCK *lock;
+ OSSL_FUNC_cipher_newctx_fn *newctx;
+ OSSL_FUNC_cipher_encrypt_init_fn *einit;
+ OSSL_FUNC_cipher_decrypt_init_fn *dinit;
+ OSSL_FUNC_cipher_update_fn *cupdate;
+ OSSL_FUNC_cipher_final_fn *cfinal;
+ OSSL_FUNC_cipher_cipher_fn *ccipher;
+ OSSL_FUNC_cipher_freectx_fn *freectx;
+ OSSL_FUNC_cipher_dupctx_fn *dupctx;
+ OSSL_FUNC_cipher_get_params_fn *get_params;
+ OSSL_FUNC_cipher_get_ctx_params_fn *get_ctx_params;
+ OSSL_FUNC_cipher_set_ctx_params_fn *set_ctx_params;
+ OSSL_FUNC_cipher_gettable_params_fn *gettable_params;
+ OSSL_FUNC_cipher_gettable_ctx_params_fn *gettable_ctx_params;
+ OSSL_FUNC_cipher_settable_ctx_params_fn *settable_ctx_params;
+} /* EVP_CIPHER */ ;
+
+/* Macros to code block cipher wrappers */
+
+/* Wrapper functions for each cipher mode */
+
+#define EVP_C_DATA(kstruct, ctx) \
+ ((kstruct *)EVP_CIPHER_CTX_get_cipher_data(ctx))
+
+#define BLOCK_CIPHER_ecb_loop() \
+ size_t i, bl; \
+ bl = EVP_CIPHER_CTX_get0_cipher(ctx)->block_size; \
+ if (inl < bl) return 1;\
+ inl -= bl; \
+ for (i=0; i <= inl; i+=bl)
+
+#define BLOCK_CIPHER_func_ecb(cname, cprefix, kstruct, ksched) \
+static int cname##_ecb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
+{\
+ BLOCK_CIPHER_ecb_loop() \
+ cprefix##_ecb_encrypt(in + i, out + i, &EVP_C_DATA(kstruct,ctx)->ksched, EVP_CIPHER_CTX_is_encrypting(ctx)); \
+ return 1;\
+}
+
+#define EVP_MAXCHUNK ((size_t)1<<(sizeof(long)*8-2))
+
+#define BLOCK_CIPHER_func_ofb(cname, cprefix, cbits, kstruct, ksched) \
+ static int cname##_ofb_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
+{\
+ while(inl>=EVP_MAXCHUNK) {\
+ int num = EVP_CIPHER_CTX_get_num(ctx);\
+ cprefix##_ofb##cbits##_encrypt(in, out, (long)EVP_MAXCHUNK, &EVP_C_DATA(kstruct,ctx)->ksched, ctx->iv, &num); \
+ EVP_CIPHER_CTX_set_num(ctx, num);\
+ inl-=EVP_MAXCHUNK;\
+ in +=EVP_MAXCHUNK;\
+ out+=EVP_MAXCHUNK;\
+ }\
+ if (inl) {\
+ int num = EVP_CIPHER_CTX_get_num(ctx);\
+ cprefix##_ofb##cbits##_encrypt(in, out, (long)inl, &EVP_C_DATA(kstruct,ctx)->ksched, ctx->iv, &num); \
+ EVP_CIPHER_CTX_set_num(ctx, num);\
+ }\
+ return 1;\
+}
+
+#define BLOCK_CIPHER_func_cbc(cname, cprefix, kstruct, ksched) \
+static int cname##_cbc_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
+{\
+ while(inl>=EVP_MAXCHUNK) \
+ {\
+ cprefix##_cbc_encrypt(in, out, (long)EVP_MAXCHUNK, &EVP_C_DATA(kstruct,ctx)->ksched, ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx));\
+ inl-=EVP_MAXCHUNK;\
+ in +=EVP_MAXCHUNK;\
+ out+=EVP_MAXCHUNK;\
+ }\
+ if (inl)\
+ cprefix##_cbc_encrypt(in, out, (long)inl, &EVP_C_DATA(kstruct,ctx)->ksched, ctx->iv, EVP_CIPHER_CTX_is_encrypting(ctx));\
+ return 1;\
+}
+
+#define BLOCK_CIPHER_func_cfb(cname, cprefix, cbits, kstruct, ksched) \
+static int cname##_cfb##cbits##_cipher(EVP_CIPHER_CTX *ctx, unsigned char *out, const unsigned char *in, size_t inl) \
+{\
+ size_t chunk = EVP_MAXCHUNK;\
+ if (cbits == 1) chunk >>= 3;\
+ if (inl < chunk) chunk = inl;\
+ while (inl && inl >= chunk)\
+ {\
+ int num = EVP_CIPHER_CTX_get_num(ctx);\
+ cprefix##_cfb##cbits##_encrypt(in, out, (long) \
+ ((cbits == 1) \
+ && !EVP_CIPHER_CTX_test_flags(ctx, EVP_CIPH_FLAG_LENGTH_BITS) \
+ ? chunk*8 : chunk), \
+ &EVP_C_DATA(kstruct, ctx)->ksched, ctx->iv,\
+ &num, EVP_CIPHER_CTX_is_encrypting(ctx));\
+ EVP_CIPHER_CTX_set_num(ctx, num);\
+ inl -= chunk;\
+ in += chunk;\
+ out += chunk;\
+ if (inl < chunk) chunk = inl;\
+ }\
+ return 1;\
+}
+
+#define BLOCK_CIPHER_all_funcs(cname, cprefix, cbits, kstruct, ksched) \
+ BLOCK_CIPHER_func_cbc(cname, cprefix, kstruct, ksched) \
+ BLOCK_CIPHER_func_cfb(cname, cprefix, cbits, kstruct, ksched) \
+ BLOCK_CIPHER_func_ecb(cname, cprefix, kstruct, ksched) \
+ BLOCK_CIPHER_func_ofb(cname, cprefix, cbits, kstruct, ksched)
+
+#define BLOCK_CIPHER_def1(cname, nmode, mode, MODE, kstruct, nid, block_size, \
+ key_len, iv_len, flags, init_key, cleanup, \
+ set_asn1, get_asn1, ctrl) \
+static const EVP_CIPHER cname##_##mode = { \
+ nid##_##nmode, block_size, key_len, iv_len, \
+ flags | EVP_CIPH_##MODE##_MODE, \
+ EVP_ORIG_GLOBAL, \
+ init_key, \
+ cname##_##mode##_cipher, \
+ cleanup, \
+ sizeof(kstruct), \
+ set_asn1, get_asn1,\
+ ctrl, \
+ NULL \
+}; \
+const EVP_CIPHER *EVP_##cname##_##mode(void) { return &cname##_##mode; }
+
+#define BLOCK_CIPHER_def_cbc(cname, kstruct, nid, block_size, key_len, \
+ iv_len, flags, init_key, cleanup, set_asn1, \
+ get_asn1, ctrl) \
+BLOCK_CIPHER_def1(cname, cbc, cbc, CBC, kstruct, nid, block_size, key_len, \
+ iv_len, flags, init_key, cleanup, set_asn1, get_asn1, ctrl)
+
+#define BLOCK_CIPHER_def_cfb(cname, kstruct, nid, key_len, \
+ iv_len, cbits, flags, init_key, cleanup, \
+ set_asn1, get_asn1, ctrl) \
+BLOCK_CIPHER_def1(cname, cfb##cbits, cfb##cbits, CFB, kstruct, nid, 1, \
+ key_len, iv_len, flags, init_key, cleanup, set_asn1, \
+ get_asn1, ctrl)
+
+#define BLOCK_CIPHER_def_ofb(cname, kstruct, nid, key_len, \
+ iv_len, cbits, flags, init_key, cleanup, \
+ set_asn1, get_asn1, ctrl) \
+BLOCK_CIPHER_def1(cname, ofb##cbits, ofb, OFB, kstruct, nid, 1, \
+ key_len, iv_len, flags, init_key, cleanup, set_asn1, \
+ get_asn1, ctrl)
+
+#define BLOCK_CIPHER_def_ecb(cname, kstruct, nid, block_size, key_len, \
+ flags, init_key, cleanup, set_asn1, \
+ get_asn1, ctrl) \
+BLOCK_CIPHER_def1(cname, ecb, ecb, ECB, kstruct, nid, block_size, key_len, \
+ 0, flags, init_key, cleanup, set_asn1, get_asn1, ctrl)
+
+#define BLOCK_CIPHER_defs(cname, kstruct, \
+ nid, block_size, key_len, iv_len, cbits, flags, \
+ init_key, cleanup, set_asn1, get_asn1, ctrl) \
+BLOCK_CIPHER_def_cbc(cname, kstruct, nid, block_size, key_len, iv_len, flags, \
+ init_key, cleanup, set_asn1, get_asn1, ctrl) \
+BLOCK_CIPHER_def_cfb(cname, kstruct, nid, key_len, iv_len, cbits, \
+ flags, init_key, cleanup, set_asn1, get_asn1, ctrl) \
+BLOCK_CIPHER_def_ofb(cname, kstruct, nid, key_len, iv_len, cbits, \
+ flags, init_key, cleanup, set_asn1, get_asn1, ctrl) \
+BLOCK_CIPHER_def_ecb(cname, kstruct, nid, block_size, key_len, flags, \
+ init_key, cleanup, set_asn1, get_asn1, ctrl)
+
+/*-
+#define BLOCK_CIPHER_defs(cname, kstruct, \
+ nid, block_size, key_len, iv_len, flags,\
+ init_key, cleanup, set_asn1, get_asn1, ctrl)\
+static const EVP_CIPHER cname##_cbc = {\
+ nid##_cbc, block_size, key_len, iv_len, \
+ flags | EVP_CIPH_CBC_MODE,\
+ EVP_ORIG_GLOBAL,\
+ init_key,\
+ cname##_cbc_cipher,\
+ cleanup,\
+ sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
+ sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
+ set_asn1, get_asn1,\
+ ctrl, \
+ NULL \
+};\
+const EVP_CIPHER *EVP_##cname##_cbc(void) { return &cname##_cbc; }\
+static const EVP_CIPHER cname##_cfb = {\
+ nid##_cfb64, 1, key_len, iv_len, \
+ flags | EVP_CIPH_CFB_MODE,\
+ EVP_ORIG_GLOBAL,\
+ init_key,\
+ cname##_cfb_cipher,\
+ cleanup,\
+ sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
+ sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
+ set_asn1, get_asn1,\
+ ctrl,\
+ NULL \
+};\
+const EVP_CIPHER *EVP_##cname##_cfb(void) { return &cname##_cfb; }\
+static const EVP_CIPHER cname##_ofb = {\
+ nid##_ofb64, 1, key_len, iv_len, \
+ flags | EVP_CIPH_OFB_MODE,\
+ EVP_ORIG_GLOBAL,\
+ init_key,\
+ cname##_ofb_cipher,\
+ cleanup,\
+ sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
+ sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
+ set_asn1, get_asn1,\
+ ctrl,\
+ NULL \
+};\
+const EVP_CIPHER *EVP_##cname##_ofb(void) { return &cname##_ofb; }\
+static const EVP_CIPHER cname##_ecb = {\
+ nid##_ecb, block_size, key_len, iv_len, \
+ flags | EVP_CIPH_ECB_MODE,\
+ EVP_ORIG_GLOBAL,\
+ init_key,\
+ cname##_ecb_cipher,\
+ cleanup,\
+ sizeof(EVP_CIPHER_CTX)-sizeof((((EVP_CIPHER_CTX *)NULL)->c))+\
+ sizeof((((EVP_CIPHER_CTX *)NULL)->c.kstruct)),\
+ set_asn1, get_asn1,\
+ ctrl,\
+ NULL \
+};\
+const EVP_CIPHER *EVP_##cname##_ecb(void) { return &cname##_ecb; }
+*/
+
+#define IMPLEMENT_BLOCK_CIPHER(cname, ksched, cprefix, kstruct, nid, \
+ block_size, key_len, iv_len, cbits, \
+ flags, init_key, \
+ cleanup, set_asn1, get_asn1, ctrl) \
+ BLOCK_CIPHER_all_funcs(cname, cprefix, cbits, kstruct, ksched) \
+ BLOCK_CIPHER_defs(cname, kstruct, nid, block_size, key_len, iv_len, \
+ cbits, flags, init_key, cleanup, set_asn1, \
+ get_asn1, ctrl)
+
+#define IMPLEMENT_CFBR(cipher,cprefix,kstruct,ksched,keysize,cbits,iv_len,fl) \
+ BLOCK_CIPHER_func_cfb(cipher##_##keysize,cprefix,cbits,kstruct,ksched) \
+ BLOCK_CIPHER_def_cfb(cipher##_##keysize,kstruct, \
+ NID_##cipher##_##keysize, keysize/8, iv_len, cbits, \
+ (fl)|EVP_CIPH_FLAG_DEFAULT_ASN1, \
+ cipher##_init_key, NULL, NULL, NULL, NULL)
+
+typedef struct {
+ unsigned char iv[EVP_MAX_IV_LENGTH];
+ unsigned int iv_len;
+ unsigned int tag_len;
+} evp_cipher_aead_asn1_params;
+
+int evp_cipher_param_to_asn1_ex(EVP_CIPHER_CTX *c, ASN1_TYPE *type,
+ evp_cipher_aead_asn1_params *params);
+
+int evp_cipher_asn1_to_param_ex(EVP_CIPHER_CTX *c, ASN1_TYPE *type,
+ evp_cipher_aead_asn1_params *params);
+
+/*
+ * To support transparent execution of operation in backends other
+ * than the "origin" key, we support transparent export/import to
+ * those providers, and maintain a cache of the imported keydata,
+ * so we don't need to redo the export/import every time we perform
+ * the same operation in that same provider.
+ * This requires that the "origin" backend (whether it's a legacy or a
+ * provider "origin") implements exports, and that the target provider
+ * has an EVP_KEYMGMT that implements import.
+ */
+typedef struct {
+ EVP_KEYMGMT *keymgmt;
+ void *keydata;
+} OP_CACHE_ELEM;
+
+DEFINE_STACK_OF(OP_CACHE_ELEM)
+
+/*
+ * An EVP_PKEY can have the following states:
+ *
+ * untyped & empty:
+ *
+ * type == EVP_PKEY_NONE && keymgmt == NULL
+ *
+ * typed & empty:
+ *
+ * (type != EVP_PKEY_NONE && pkey.ptr == NULL) ## legacy (libcrypto only)
+ * || (keymgmt != NULL && keydata == NULL) ## provider side
+ *
+ * fully assigned:
+ *
+ * (type != EVP_PKEY_NONE && pkey.ptr != NULL) ## legacy (libcrypto only)
+ * || (keymgmt != NULL && keydata != NULL) ## provider side
+ *
+ * The easiest way to detect a legacy key is:
+ *
+ * keymgmt == NULL && type != EVP_PKEY_NONE
+ *
+ * The easiest way to detect a provider side key is:
+ *
+ * keymgmt != NULL
+ */
+#define evp_pkey_is_blank(pk) \
+ ((pk)->type == EVP_PKEY_NONE && (pk)->keymgmt == NULL)
+#define evp_pkey_is_typed(pk) \
+ ((pk)->type != EVP_PKEY_NONE || (pk)->keymgmt != NULL)
+#ifndef FIPS_MODULE
+# define evp_pkey_is_assigned(pk) \
+ ((pk)->pkey.ptr != NULL || (pk)->keydata != NULL)
+#else
+# define evp_pkey_is_assigned(pk) \
+ ((pk)->keydata != NULL)
+#endif
+#define evp_pkey_is_legacy(pk) \
+ ((pk)->type != EVP_PKEY_NONE && (pk)->keymgmt == NULL)
+#define evp_pkey_is_provided(pk) \
+ ((pk)->keymgmt != NULL)
+
+union legacy_pkey_st {
+ void *ptr;
+ struct rsa_st *rsa; /* RSA */
+# ifndef OPENSSL_NO_DSA
+ struct dsa_st *dsa; /* DSA */
+# endif
+# ifndef OPENSSL_NO_DH
+ struct dh_st *dh; /* DH */
+# endif
+# ifndef OPENSSL_NO_EC
+ struct ec_key_st *ec; /* ECC */
+ ECX_KEY *ecx; /* X25519, X448, Ed25519, Ed448 */
+# endif
+};
+
+struct evp_pkey_st {
+ /* == Legacy attributes == */
+ int type;
+ int save_type;
+
+# ifndef FIPS_MODULE
+ /*
+ * Legacy key "origin" is composed of a pointer to an EVP_PKEY_ASN1_METHOD,
+ * a pointer to a low level key and possibly a pointer to an engine.
+ */
+ const EVP_PKEY_ASN1_METHOD *ameth;
+ ENGINE *engine;
+ ENGINE *pmeth_engine; /* If not NULL public key ENGINE to use */
+
+ /* Union to store the reference to an origin legacy key */
+ union legacy_pkey_st pkey;
+
+ /* Union to store the reference to a non-origin legacy key */
+ union legacy_pkey_st legacy_cache_pkey;
+# endif
+
+ /* == Common attributes == */
+ CRYPTO_REF_COUNT references;
+ CRYPTO_RWLOCK *lock;
+#ifndef FIPS_MODULE
+ STACK_OF(X509_ATTRIBUTE) *attributes; /* [ 0 ] */
+ int save_parameters;
+ unsigned int foreign:1; /* the low-level key is using an engine or an app-method */
+ CRYPTO_EX_DATA ex_data;
+#endif
+
+ /* == Provider attributes == */
+
+ /*
+ * Provider keydata "origin" is composed of a pointer to an EVP_KEYMGMT
+ * and a pointer to the provider side key data. This is never used at
+ * the same time as the legacy key data above.
+ */
+ EVP_KEYMGMT *keymgmt;
+ void *keydata;
+ /*
+ * If any libcrypto code does anything that may modify the keydata
+ * contents, this dirty counter must be incremented.
+ */
+ size_t dirty_cnt;
+
+ /*
+ * To support transparent execution of operation in backends other
+ * than the "origin" key, we support transparent export/import to
+ * those providers, and maintain a cache of the imported keydata,
+ * so we don't need to redo the export/import every time we perform
+ * the same operation in that same provider.
+ */
+ STACK_OF(OP_CACHE_ELEM) *operation_cache;
+
+ /*
+ * We keep a copy of that "origin"'s dirty count, so we know if the
+ * operation cache needs flushing.
+ */
+ size_t dirty_cnt_copy;
+
+ /* Cache of key object information */
+ struct {
+ int bits;
+ int security_bits;
+ int size;
+ } cache;
+} /* EVP_PKEY */ ;
+
+#define EVP_PKEY_CTX_IS_SIGNATURE_OP(ctx) \
+ ((ctx)->operation == EVP_PKEY_OP_SIGN \
+ || (ctx)->operation == EVP_PKEY_OP_SIGNCTX \
+ || (ctx)->operation == EVP_PKEY_OP_VERIFY \
+ || (ctx)->operation == EVP_PKEY_OP_VERIFYCTX \
+ || (ctx)->operation == EVP_PKEY_OP_VERIFYRECOVER)
+
+#define EVP_PKEY_CTX_IS_DERIVE_OP(ctx) \
+ ((ctx)->operation == EVP_PKEY_OP_DERIVE)
+
+#define EVP_PKEY_CTX_IS_ASYM_CIPHER_OP(ctx) \
+ ((ctx)->operation == EVP_PKEY_OP_ENCRYPT \
+ || (ctx)->operation == EVP_PKEY_OP_DECRYPT)
+
+#define EVP_PKEY_CTX_IS_GEN_OP(ctx) \
+ ((ctx)->operation == EVP_PKEY_OP_PARAMGEN \
+ || (ctx)->operation == EVP_PKEY_OP_KEYGEN)
+
+#define EVP_PKEY_CTX_IS_FROMDATA_OP(ctx) \
+ ((ctx)->operation == EVP_PKEY_OP_FROMDATA)
+
+#define EVP_PKEY_CTX_IS_KEM_OP(ctx) \
+ ((ctx)->operation == EVP_PKEY_OP_ENCAPSULATE \
+ || (ctx)->operation == EVP_PKEY_OP_DECAPSULATE)
+
+void openssl_add_all_ciphers_int(void);
+void openssl_add_all_digests_int(void);
+void evp_cleanup_int(void);
+void evp_app_cleanup_int(void);
+void *evp_pkey_export_to_provider(EVP_PKEY *pk, OSSL_LIB_CTX *libctx,
+ EVP_KEYMGMT **keymgmt,
+ const char *propquery);
+#ifndef FIPS_MODULE
+int evp_pkey_copy_downgraded(EVP_PKEY **dest, const EVP_PKEY *src);
+void *evp_pkey_get_legacy(EVP_PKEY *pk);
+void evp_pkey_free_legacy(EVP_PKEY *x);
+EVP_PKEY *evp_pkcs82pkey_legacy(const PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *libctx, const char *propq);
+#endif
+
+/*
+ * KEYMGMT utility functions
+ */
+
+/*
+ * Key import structure and helper function, to be used as an export callback
+ */
+struct evp_keymgmt_util_try_import_data_st {
+ EVP_KEYMGMT *keymgmt;
+ void *keydata;
+
+ int selection;
+};
+int evp_keymgmt_util_try_import(const OSSL_PARAM params[], void *arg);
+int evp_keymgmt_util_assign_pkey(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt,
+ void *keydata);
+EVP_PKEY *evp_keymgmt_util_make_pkey(EVP_KEYMGMT *keymgmt, void *keydata);
+
+int evp_keymgmt_util_export(const EVP_PKEY *pk, int selection,
+ OSSL_CALLBACK *export_cb, void *export_cbarg);
+void *evp_keymgmt_util_export_to_provider(EVP_PKEY *pk, EVP_KEYMGMT *keymgmt);
+OP_CACHE_ELEM *evp_keymgmt_util_find_operation_cache(EVP_PKEY *pk,
+ EVP_KEYMGMT *keymgmt);
+int evp_keymgmt_util_clear_operation_cache(EVP_PKEY *pk, int locking);
+int evp_keymgmt_util_cache_keydata(EVP_PKEY *pk,
+ EVP_KEYMGMT *keymgmt, void *keydata);
+void evp_keymgmt_util_cache_keyinfo(EVP_PKEY *pk);
+void *evp_keymgmt_util_fromdata(EVP_PKEY *target, EVP_KEYMGMT *keymgmt,
+ int selection, const OSSL_PARAM params[]);
+int evp_keymgmt_util_has(EVP_PKEY *pk, int selection);
+int evp_keymgmt_util_match(EVP_PKEY *pk1, EVP_PKEY *pk2, int selection);
+int evp_keymgmt_util_copy(EVP_PKEY *to, EVP_PKEY *from, int selection);
+void *evp_keymgmt_util_gen(EVP_PKEY *target, EVP_KEYMGMT *keymgmt,
+ void *genctx, OSSL_CALLBACK *cb, void *cbarg);
+int evp_keymgmt_util_get_deflt_digest_name(EVP_KEYMGMT *keymgmt,
+ void *keydata,
+ char *mdname, size_t mdname_sz);
+const char *evp_keymgmt_util_query_operation_name(EVP_KEYMGMT *keymgmt,
+ int op_id);
+
+/*
+ * KEYMGMT provider interface functions
+ */
+void *evp_keymgmt_newdata(const EVP_KEYMGMT *keymgmt);
+void evp_keymgmt_freedata(const EVP_KEYMGMT *keymgmt, void *keyddata);
+int evp_keymgmt_get_params(const EVP_KEYMGMT *keymgmt,
+ void *keydata, OSSL_PARAM params[]);
+int evp_keymgmt_set_params(const EVP_KEYMGMT *keymgmt,
+ void *keydata, const OSSL_PARAM params[]);
+void *evp_keymgmt_gen_init(const EVP_KEYMGMT *keymgmt, int selection,
+ const OSSL_PARAM params[]);
+int evp_keymgmt_gen_set_template(const EVP_KEYMGMT *keymgmt, void *genctx,
+ void *template);
+int evp_keymgmt_gen_set_params(const EVP_KEYMGMT *keymgmt, void *genctx,
+ const OSSL_PARAM params[]);
+void *evp_keymgmt_gen(const EVP_KEYMGMT *keymgmt, void *genctx,
+ OSSL_CALLBACK *cb, void *cbarg);
+void evp_keymgmt_gen_cleanup(const EVP_KEYMGMT *keymgmt, void *genctx);
+
+int evp_keymgmt_has_load(const EVP_KEYMGMT *keymgmt);
+void *evp_keymgmt_load(const EVP_KEYMGMT *keymgmt,
+ const void *objref, size_t objref_sz);
+
+int evp_keymgmt_has(const EVP_KEYMGMT *keymgmt, void *keyddata, int selection);
+int evp_keymgmt_validate(const EVP_KEYMGMT *keymgmt, void *keydata,
+ int selection, int checktype);
+int evp_keymgmt_match(const EVP_KEYMGMT *keymgmt,
+ const void *keydata1, const void *keydata2,
+ int selection);
+
+int evp_keymgmt_import(const EVP_KEYMGMT *keymgmt, void *keydata,
+ int selection, const OSSL_PARAM params[]);
+const OSSL_PARAM *evp_keymgmt_import_types(const EVP_KEYMGMT *keymgmt,
+ int selection);
+int evp_keymgmt_export(const EVP_KEYMGMT *keymgmt, void *keydata,
+ int selection, OSSL_CALLBACK *param_cb, void *cbarg);
+const OSSL_PARAM *evp_keymgmt_export_types(const EVP_KEYMGMT *keymgmt,
+ int selection);
+void *evp_keymgmt_dup(const EVP_KEYMGMT *keymgmt,
+ const void *keydata_from, int selection);
+
+/* Pulling defines out of C source files */
+
+# define EVP_RC4_KEY_SIZE 16
+# ifndef TLS1_1_VERSION
+# define TLS1_1_VERSION 0x0302
+# endif
+
+void evp_encode_ctx_set_flags(EVP_ENCODE_CTX *ctx, unsigned int flags);
+
+/* EVP_ENCODE_CTX flags */
+/* Don't generate new lines when encoding */
+#define EVP_ENCODE_CTX_NO_NEWLINES 1
+/* Use the SRP base64 alphabet instead of the standard one */
+#define EVP_ENCODE_CTX_USE_SRP_ALPHABET 2
+
+const EVP_CIPHER *evp_get_cipherbyname_ex(OSSL_LIB_CTX *libctx,
+ const char *name);
+const EVP_MD *evp_get_digestbyname_ex(OSSL_LIB_CTX *libctx,
+ const char *name);
+
+int ossl_pkcs5_pbkdf2_hmac_ex(const char *pass, int passlen,
+ const unsigned char *salt, int saltlen, int iter,
+ const EVP_MD *digest, int keylen,
+ unsigned char *out,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+# ifndef FIPS_MODULE
+/*
+ * Internal helpers for stricter EVP_PKEY_CTX_{set,get}_params().
+ *
+ * Return 1 on success, 0 or negative for errors.
+ *
+ * In particular they return -2 if any of the params is not supported.
+ *
+ * They are not available in FIPS_MODULE as they depend on
+ * - EVP_PKEY_CTX_{get,set}_params()
+ * - EVP_PKEY_CTX_{gettable,settable}_params()
+ *
+ */
+int evp_pkey_ctx_set_params_strict(EVP_PKEY_CTX *ctx, OSSL_PARAM *params);
+int evp_pkey_ctx_get_params_strict(EVP_PKEY_CTX *ctx, OSSL_PARAM *params);
+
+EVP_MD_CTX *evp_md_ctx_new_ex(EVP_PKEY *pkey, const ASN1_OCTET_STRING *id,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int evp_pkey_name2type(const char *name);
+const char *evp_pkey_type2name(int type);
+
+int evp_pkey_ctx_set1_id_prov(EVP_PKEY_CTX *ctx, const void *id, int len);
+int evp_pkey_ctx_get1_id_prov(EVP_PKEY_CTX *ctx, void *id);
+int evp_pkey_ctx_get1_id_len_prov(EVP_PKEY_CTX *ctx, size_t *id_len);
+
+int evp_pkey_ctx_use_cached_data(EVP_PKEY_CTX *ctx);
+# endif /* !defined(FIPS_MODULE) */
+
+int evp_method_store_flush(OSSL_LIB_CTX *libctx);
+int evp_default_properties_enable_fips_int(OSSL_LIB_CTX *libctx, int enable,
+ int loadconfig);
+int evp_set_default_properties_int(OSSL_LIB_CTX *libctx, const char *propq,
+ int loadconfig, int mirrored);
+char *evp_get_global_properties_str(OSSL_LIB_CTX *libctx, int loadconfig);
+
+void evp_md_ctx_clear_digest(EVP_MD_CTX *ctx, int force);
+
+/* Three possible states: */
+# define EVP_PKEY_STATE_UNKNOWN 0
+# define EVP_PKEY_STATE_LEGACY 1
+# define EVP_PKEY_STATE_PROVIDER 2
+int evp_pkey_ctx_state(const EVP_PKEY_CTX *ctx);
+
+/* These two must ONLY be called for provider side operations */
+int evp_pkey_ctx_ctrl_to_param(EVP_PKEY_CTX *ctx,
+ int keytype, int optype,
+ int cmd, int p1, void *p2);
+int evp_pkey_ctx_ctrl_str_to_param(EVP_PKEY_CTX *ctx,
+ const char *name, const char *value);
+
+/* These two must ONLY be called for legacy operations */
+int evp_pkey_ctx_set_params_to_ctrl(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params);
+int evp_pkey_ctx_get_params_to_ctrl(EVP_PKEY_CTX *ctx, OSSL_PARAM *params);
+
+/* This must ONLY be called for legacy EVP_PKEYs */
+int evp_pkey_get_params_to_ctrl(const EVP_PKEY *pkey, OSSL_PARAM *params);
+
+/* Same as the public get0 functions but are not const */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+DH *evp_pkey_get0_DH_int(const EVP_PKEY *pkey);
+EC_KEY *evp_pkey_get0_EC_KEY_int(const EVP_PKEY *pkey);
+RSA *evp_pkey_get0_RSA_int(const EVP_PKEY *pkey);
+# endif
+
+/* Get internal identification number routines */
+int evp_asym_cipher_get_number(const EVP_ASYM_CIPHER *cipher);
+int evp_cipher_get_number(const EVP_CIPHER *cipher);
+int evp_kdf_get_number(const EVP_KDF *kdf);
+int evp_kem_get_number(const EVP_KEM *wrap);
+int evp_keyexch_get_number(const EVP_KEYEXCH *keyexch);
+int evp_keymgmt_get_number(const EVP_KEYMGMT *keymgmt);
+int evp_mac_get_number(const EVP_MAC *mac);
+int evp_md_get_number(const EVP_MD *md);
+int evp_rand_get_number(const EVP_RAND *rand);
+int evp_signature_get_number(const EVP_SIGNATURE *signature);
+
+#endif /* OSSL_CRYPTO_EVP_H */
diff --git a/include/crypto/evperr.h b/include/crypto/evperr.h
new file mode 100644
index 00000000..d90ba83f
--- /dev/null
+++ b/include/crypto/evperr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_EVPERR_H
+# define OSSL_CRYPTO_EVPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_EVP_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/httperr.h b/include/crypto/httperr.h
new file mode 100644
index 00000000..969df17b
--- /dev/null
+++ b/include/crypto/httperr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_HTTPERR_H
+# define OSSL_CRYPTO_HTTPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_HTTP_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/lhash.h b/include/crypto/lhash.h
new file mode 100644
index 00000000..0f64869f
--- /dev/null
+++ b/include/crypto/lhash.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_LHASH_H
+# define OSSL_CRYPTO_LHASH_H
+# pragma once
+
+unsigned long ossl_lh_strcasehash(const char *);
+
+#endif /* OSSL_CRYPTO_LHASH_H */
diff --git a/include/crypto/md32_common.h b/include/crypto/md32_common.h
new file mode 100644
index 00000000..3b16f1b7
--- /dev/null
+++ b/include/crypto/md32_common.h
@@ -0,0 +1,256 @@
+/*
+ * Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*-
+ * This is a generic 32 bit "collector" for message digest algorithms.
+ * Whenever needed it collects input character stream into chunks of
+ * 32 bit values and invokes a block function that performs actual hash
+ * calculations.
+ *
+ * Porting guide.
+ *
+ * Obligatory macros:
+ *
+ * DATA_ORDER_IS_BIG_ENDIAN or DATA_ORDER_IS_LITTLE_ENDIAN
+ * this macro defines byte order of input stream.
+ * HASH_CBLOCK
+ * size of a unit chunk HASH_BLOCK operates on.
+ * HASH_LONG
+ * has to be at least 32 bit wide.
+ * HASH_CTX
+ * context structure that at least contains following
+ * members:
+ * typedef struct {
+ * ...
+ * HASH_LONG Nl,Nh;
+ * either {
+ * HASH_LONG data[HASH_LBLOCK];
+ * unsigned char data[HASH_CBLOCK];
+ * };
+ * unsigned int num;
+ * ...
+ * } HASH_CTX;
+ * data[] vector is expected to be zeroed upon first call to
+ * HASH_UPDATE.
+ * HASH_UPDATE
+ * name of "Update" function, implemented here.
+ * HASH_TRANSFORM
+ * name of "Transform" function, implemented here.
+ * HASH_FINAL
+ * name of "Final" function, implemented here.
+ * HASH_BLOCK_DATA_ORDER
+ * name of "block" function capable of treating *unaligned* input
+ * message in original (data) byte order, implemented externally.
+ * HASH_MAKE_STRING
+ * macro converting context variables to an ASCII hash string.
+ *
+ * MD5 example:
+ *
+ * #define DATA_ORDER_IS_LITTLE_ENDIAN
+ *
+ * #define HASH_LONG MD5_LONG
+ * #define HASH_CTX MD5_CTX
+ * #define HASH_CBLOCK MD5_CBLOCK
+ * #define HASH_UPDATE MD5_Update
+ * #define HASH_TRANSFORM MD5_Transform
+ * #define HASH_FINAL MD5_Final
+ * #define HASH_BLOCK_DATA_ORDER md5_block_data_order
+ */
+
+#include <openssl/crypto.h>
+
+#if !defined(DATA_ORDER_IS_BIG_ENDIAN) && !defined(DATA_ORDER_IS_LITTLE_ENDIAN)
+# error "DATA_ORDER must be defined!"
+#endif
+
+#ifndef HASH_CBLOCK
+# error "HASH_CBLOCK must be defined!"
+#endif
+#ifndef HASH_LONG
+# error "HASH_LONG must be defined!"
+#endif
+#ifndef HASH_CTX
+# error "HASH_CTX must be defined!"
+#endif
+
+#ifndef HASH_UPDATE
+# error "HASH_UPDATE must be defined!"
+#endif
+#ifndef HASH_TRANSFORM
+# error "HASH_TRANSFORM must be defined!"
+#endif
+#ifndef HASH_FINAL
+# error "HASH_FINAL must be defined!"
+#endif
+
+#ifndef HASH_BLOCK_DATA_ORDER
+# error "HASH_BLOCK_DATA_ORDER must be defined!"
+#endif
+
+#define ROTATE(a,n) (((a)<<(n))|(((a)&0xffffffff)>>(32-(n))))
+
+#if defined(DATA_ORDER_IS_BIG_ENDIAN)
+
+# define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++)))<<24), \
+ l|=(((unsigned long)(*((c)++)))<<16), \
+ l|=(((unsigned long)(*((c)++)))<< 8), \
+ l|=(((unsigned long)(*((c)++))) ) )
+# define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l)>>24)&0xff), \
+ *((c)++)=(unsigned char)(((l)>>16)&0xff), \
+ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
+ *((c)++)=(unsigned char)(((l) )&0xff), \
+ l)
+
+#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
+
+# define HOST_c2l(c,l) (l =(((unsigned long)(*((c)++))) ), \
+ l|=(((unsigned long)(*((c)++)))<< 8), \
+ l|=(((unsigned long)(*((c)++)))<<16), \
+ l|=(((unsigned long)(*((c)++)))<<24) )
+# define HOST_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \
+ *((c)++)=(unsigned char)(((l)>> 8)&0xff), \
+ *((c)++)=(unsigned char)(((l)>>16)&0xff), \
+ *((c)++)=(unsigned char)(((l)>>24)&0xff), \
+ l)
+
+#endif
+
+/*
+ * Time for some action :-)
+ */
+
+int HASH_UPDATE(HASH_CTX *c, const void *data_, size_t len)
+{
+ const unsigned char *data = data_;
+ unsigned char *p;
+ HASH_LONG l;
+ size_t n;
+
+ if (len == 0)
+ return 1;
+
+ l = (c->Nl + (((HASH_LONG) len) << 3)) & 0xffffffffUL;
+ if (l < c->Nl) /* overflow */
+ c->Nh++;
+ c->Nh += (HASH_LONG) (len >> 29); /* might cause compiler warning on
+ * 16-bit */
+ c->Nl = l;
+
+ n = c->num;
+ if (n != 0) {
+ p = (unsigned char *)c->data;
+
+ if (len >= HASH_CBLOCK || len + n >= HASH_CBLOCK) {
+ memcpy(p + n, data, HASH_CBLOCK - n);
+ HASH_BLOCK_DATA_ORDER(c, p, 1);
+ n = HASH_CBLOCK - n;
+ data += n;
+ len -= n;
+ c->num = 0;
+ /*
+ * We use memset rather than OPENSSL_cleanse() here deliberately.
+ * Using OPENSSL_cleanse() here could be a performance issue. It
+ * will get properly cleansed on finalisation so this isn't a
+ * security problem.
+ */
+ memset(p, 0, HASH_CBLOCK); /* keep it zeroed */
+ } else {
+ memcpy(p + n, data, len);
+ c->num += (unsigned int)len;
+ return 1;
+ }
+ }
+
+ n = len / HASH_CBLOCK;
+ if (n > 0) {
+ HASH_BLOCK_DATA_ORDER(c, data, n);
+ n *= HASH_CBLOCK;
+ data += n;
+ len -= n;
+ }
+
+ if (len != 0) {
+ p = (unsigned char *)c->data;
+ c->num = (unsigned int)len;
+ memcpy(p, data, len);
+ }
+ return 1;
+}
+
+void HASH_TRANSFORM(HASH_CTX *c, const unsigned char *data)
+{
+ HASH_BLOCK_DATA_ORDER(c, data, 1);
+}
+
+int HASH_FINAL(unsigned char *md, HASH_CTX *c)
+{
+ unsigned char *p = (unsigned char *)c->data;
+ size_t n = c->num;
+
+ p[n] = 0x80; /* there is always room for one */
+ n++;
+
+ if (n > (HASH_CBLOCK - 8)) {
+ memset(p + n, 0, HASH_CBLOCK - n);
+ n = 0;
+ HASH_BLOCK_DATA_ORDER(c, p, 1);
+ }
+ memset(p + n, 0, HASH_CBLOCK - 8 - n);
+
+ p += HASH_CBLOCK - 8;
+#if defined(DATA_ORDER_IS_BIG_ENDIAN)
+ (void)HOST_l2c(c->Nh, p);
+ (void)HOST_l2c(c->Nl, p);
+#elif defined(DATA_ORDER_IS_LITTLE_ENDIAN)
+ (void)HOST_l2c(c->Nl, p);
+ (void)HOST_l2c(c->Nh, p);
+#endif
+ p -= HASH_CBLOCK;
+ HASH_BLOCK_DATA_ORDER(c, p, 1);
+ c->num = 0;
+ OPENSSL_cleanse(p, HASH_CBLOCK);
+
+#ifndef HASH_MAKE_STRING
+# error "HASH_MAKE_STRING must be defined!"
+#else
+ HASH_MAKE_STRING(c, md);
+#endif
+
+ return 1;
+}
+
+#ifndef MD32_REG_T
+# if defined(__alpha) || defined(__sparcv9) || defined(__mips)
+# define MD32_REG_T long
+/*
+ * This comment was originally written for MD5, which is why it
+ * discusses A-D. But it basically applies to all 32-bit digests,
+ * which is why it was moved to common header file.
+ *
+ * In case you wonder why A-D are declared as long and not
+ * as MD5_LONG. Doing so results in slight performance
+ * boost on LP64 architectures. The catch is we don't
+ * really care if 32 MSBs of a 64-bit register get polluted
+ * with eventual overflows as we *save* only 32 LSBs in
+ * *either* case. Now declaring 'em long excuses the compiler
+ * from keeping 32 MSBs zeroed resulting in 13% performance
+ * improvement under SPARC Solaris7/64 and 5% under AlphaLinux.
+ * Well, to be honest it should say that this *prevents*
+ * performance degradation.
+ */
+# else
+/*
+ * Above is not absolute and there are LP64 compilers that
+ * generate better code if MD32_REG_T is defined int. The above
+ * pre-processor condition reflects the circumstances under which
+ * the conclusion was made and is subject to further extension.
+ */
+# define MD32_REG_T int
+# endif
+#endif
diff --git a/include/crypto/modes.h b/include/crypto/modes.h
new file mode 100644
index 00000000..19f9d859
--- /dev/null
+++ b/include/crypto/modes.h
@@ -0,0 +1,223 @@
+/*
+ * Copyright 2010-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/* This header can move into provider when legacy support is removed */
+#include <openssl/modes.h>
+
+#if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__)
+typedef __int64 i64;
+typedef unsigned __int64 u64;
+# define U64(C) C##UI64
+#elif defined(__arch64__)
+typedef long i64;
+typedef unsigned long u64;
+# define U64(C) C##UL
+#else
+typedef long long i64;
+typedef unsigned long long u64;
+# define U64(C) C##ULL
+#endif
+
+typedef unsigned int u32;
+typedef unsigned char u8;
+
+#define STRICT_ALIGNMENT 1
+#ifndef PEDANTIC
+# if defined(__i386) || defined(__i386__) || \
+ defined(__x86_64) || defined(__x86_64__) || \
+ defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64) || \
+ defined(__aarch64__) || \
+ defined(__s390__) || defined(__s390x__)
+# undef STRICT_ALIGNMENT
+# endif
+#endif
+
+#if !defined(PEDANTIC) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_NO_INLINE_ASM)
+# if defined(__GNUC__) && __GNUC__>=2
+# if defined(__x86_64) || defined(__x86_64__)
+# define BSWAP8(x) ({ u64 ret_=(x); \
+ asm ("bswapq %0" \
+ : "+r"(ret_)); ret_; })
+# define BSWAP4(x) ({ u32 ret_=(x); \
+ asm ("bswapl %0" \
+ : "+r"(ret_)); ret_; })
+# elif (defined(__i386) || defined(__i386__)) && !defined(I386_ONLY)
+# define BSWAP8(x) ({ u32 lo_=(u64)(x)>>32,hi_=(x); \
+ asm ("bswapl %0; bswapl %1" \
+ : "+r"(hi_),"+r"(lo_)); \
+ (u64)hi_<<32|lo_; })
+# define BSWAP4(x) ({ u32 ret_=(x); \
+ asm ("bswapl %0" \
+ : "+r"(ret_)); ret_; })
+# elif defined(__aarch64__)
+# if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \
+ __BYTE_ORDER__==__ORDER_LITTLE_ENDIAN__
+# define BSWAP8(x) ({ u64 ret_; \
+ asm ("rev %0,%1" \
+ : "=r"(ret_) : "r"(x)); ret_; })
+# define BSWAP4(x) ({ u32 ret_; \
+ asm ("rev %w0,%w1" \
+ : "=r"(ret_) : "r"(x)); ret_; })
+# endif
+# elif (defined(__arm__) || defined(__arm)) && !defined(STRICT_ALIGNMENT)
+# define BSWAP8(x) ({ u32 lo_=(u64)(x)>>32,hi_=(x); \
+ asm ("rev %0,%0; rev %1,%1" \
+ : "+r"(hi_),"+r"(lo_)); \
+ (u64)hi_<<32|lo_; })
+# define BSWAP4(x) ({ u32 ret_; \
+ asm ("rev %0,%1" \
+ : "=r"(ret_) : "r"((u32)(x))); \
+ ret_; })
+# endif
+# elif defined(_MSC_VER)
+# if _MSC_VER>=1300
+# include <stdlib.h>
+# pragma intrinsic(_byteswap_uint64,_byteswap_ulong)
+# define BSWAP8(x) _byteswap_uint64((u64)(x))
+# define BSWAP4(x) _byteswap_ulong((u32)(x))
+# elif defined(_M_IX86)
+__inline u32 _bswap4(u32 val)
+{
+_asm mov eax, val _asm bswap eax}
+# define BSWAP4(x) _bswap4(x)
+# endif
+# endif
+#endif
+#if defined(BSWAP4) && !defined(STRICT_ALIGNMENT)
+# define GETU32(p) BSWAP4(*(const u32 *)(p))
+# define PUTU32(p,v) *(u32 *)(p) = BSWAP4(v)
+#else
+# define GETU32(p) ((u32)(p)[0]<<24|(u32)(p)[1]<<16|(u32)(p)[2]<<8|(u32)(p)[3])
+# define PUTU32(p,v) ((p)[0]=(u8)((v)>>24),(p)[1]=(u8)((v)>>16),(p)[2]=(u8)((v)>>8),(p)[3]=(u8)(v))
+#endif
+/*- GCM definitions */ typedef struct {
+ u64 hi, lo;
+} u128;
+
+#ifdef TABLE_BITS
+# undef TABLE_BITS
+#endif
+/*
+ * Even though permitted values for TABLE_BITS are 8, 4 and 1, it should
+ * never be set to 8 [or 1]. For further information see gcm128.c.
+ */
+#define TABLE_BITS 4
+
+struct gcm128_context {
+ /* Following 6 names follow names in GCM specification */
+ union {
+ u64 u[2];
+ u32 d[4];
+ u8 c[16];
+ size_t t[16 / sizeof(size_t)];
+ } Yi, EKi, EK0, len, Xi, H;
+ /*
+ * Relative position of Xi, H and pre-computed Htable is used in some
+ * assembler modules, i.e. don't change the order!
+ */
+#if TABLE_BITS==8
+ u128 Htable[256];
+#else
+ u128 Htable[16];
+ void (*gmult) (u64 Xi[2], const u128 Htable[16]);
+ void (*ghash) (u64 Xi[2], const u128 Htable[16], const u8 *inp,
+ size_t len);
+#endif
+ unsigned int mres, ares;
+ block128_f block;
+ void *key;
+#if !defined(OPENSSL_SMALL_FOOTPRINT)
+ unsigned char Xn[48];
+#endif
+};
+
+/*
+ * The maximum permitted number of cipher blocks per data unit in XTS mode.
+ * Reference IEEE Std 1619-2018.
+ */
+#define XTS_MAX_BLOCKS_PER_DATA_UNIT (1<<20)
+
+struct xts128_context {
+ void *key1, *key2;
+ block128_f block1, block2;
+};
+
+struct ccm128_context {
+ union {
+ u64 u[2];
+ u8 c[16];
+ } nonce, cmac;
+ u64 blocks;
+ block128_f block;
+ void *key;
+};
+
+#ifndef OPENSSL_NO_OCB
+
+typedef union {
+ u64 a[2];
+ unsigned char c[16];
+} OCB_BLOCK;
+# define ocb_block16_xor(in1,in2,out) \
+ ( (out)->a[0]=(in1)->a[0]^(in2)->a[0], \
+ (out)->a[1]=(in1)->a[1]^(in2)->a[1] )
+# if STRICT_ALIGNMENT
+# define ocb_block16_xor_misaligned(in1,in2,out) \
+ ocb_block_xor((in1)->c,(in2)->c,16,(out)->c)
+# else
+# define ocb_block16_xor_misaligned ocb_block16_xor
+# endif
+
+struct ocb128_context {
+ /* Need both encrypt and decrypt key schedules for decryption */
+ block128_f encrypt;
+ block128_f decrypt;
+ void *keyenc;
+ void *keydec;
+ ocb128_f stream; /* direction dependent */
+ /* Key dependent variables. Can be reused if key remains the same */
+ size_t l_index;
+ size_t max_l_index;
+ OCB_BLOCK l_star;
+ OCB_BLOCK l_dollar;
+ OCB_BLOCK *l;
+ /* Must be reset for each session */
+ struct {
+ u64 blocks_hashed;
+ u64 blocks_processed;
+ OCB_BLOCK offset_aad;
+ OCB_BLOCK sum;
+ OCB_BLOCK offset;
+ OCB_BLOCK checksum;
+ } sess;
+};
+#endif /* OPENSSL_NO_OCB */
+
+#ifndef OPENSSL_NO_SIV
+
+#define SIV_LEN 16
+
+typedef union siv_block_u {
+ uint64_t word[SIV_LEN/sizeof(uint64_t)];
+ unsigned char byte[SIV_LEN];
+} SIV_BLOCK;
+
+struct siv128_context {
+ /* d stores intermediate results of S2V; it corresponds to D from the
+ pseudocode in section 2.4 of RFC 5297. */
+ SIV_BLOCK d;
+ SIV_BLOCK tag;
+ EVP_CIPHER_CTX *cipher_ctx;
+ EVP_MAC *mac;
+ EVP_MAC_CTX *mac_ctx_init;
+ int final_ret;
+ int crypto_ok;
+};
+
+#endif /* OPENSSL_NO_SIV */
diff --git a/include/crypto/objects.h b/include/crypto/objects.h
new file mode 100644
index 00000000..f22e9287
--- /dev/null
+++ b/include/crypto/objects.h
@@ -0,0 +1,12 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <openssl/objects.h>
+
+void ossl_obj_cleanup_int(void);
diff --git a/include/crypto/objectserr.h b/include/crypto/objectserr.h
new file mode 100644
index 00000000..ec994824
--- /dev/null
+++ b/include/crypto/objectserr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_OBJECTSERR_H
+# define OSSL_CRYPTO_OBJECTSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_OBJ_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/ocsperr.h b/include/crypto/ocsperr.h
new file mode 100644
index 00000000..f9529b2a
--- /dev/null
+++ b/include/crypto/ocsperr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_OCSPERR_H
+# define OSSL_CRYPTO_OCSPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_OCSP
+
+int ossl_err_load_OCSP_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/pem.h b/include/crypto/pem.h
new file mode 100644
index 00000000..840dc18f
--- /dev/null
+++ b/include/crypto/pem.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the OpenSSL license (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_PEM_H
+# define OSSL_INTERNAL_PEM_H
+# pragma once
+
+# include <openssl/pem.h>
+# include "crypto/types.h"
+
+/* Found in crypto/pem/pvkfmt.c */
+
+/* Maximum length of a blob after header */
+# define BLOB_MAX_LENGTH 102400
+
+int ossl_do_blob_header(const unsigned char **in, unsigned int length,
+ unsigned int *pmagic, unsigned int *pbitlen,
+ int *pisdss, int *pispub);
+unsigned int ossl_blob_length(unsigned bitlen, int isdss, int ispub);
+int ossl_do_PVK_header(const unsigned char **in, unsigned int length,
+ int skip_magic,
+ unsigned int *psaltlen, unsigned int *pkeylen);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+DSA *ossl_b2i_DSA_after_header(const unsigned char **in, unsigned int bitlen,
+ int ispub);
+# endif
+RSA *ossl_b2i_RSA_after_header(const unsigned char **in, unsigned int bitlen,
+ int ispub);
+# endif
+EVP_PKEY *ossl_b2i(const unsigned char **in, unsigned int length, int *ispub);
+EVP_PKEY *ossl_b2i_bio(BIO *in, int *ispub);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+DSA *b2i_DSA_PVK_bio(BIO *in, pem_password_cb *cb, void *u);
+DSA *b2i_DSA_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
+ OSSL_LIB_CTX *libctx, const char *propq);
+# endif
+RSA *b2i_RSA_PVK_bio(BIO *in, pem_password_cb *cb, void *u);
+RSA *b2i_RSA_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
+ OSSL_LIB_CTX *libctx, const char *propq);
+# endif
+
+#endif
diff --git a/include/crypto/pemerr.h b/include/crypto/pemerr.h
new file mode 100644
index 00000000..b255ff5c
--- /dev/null
+++ b/include/crypto/pemerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_PEMERR_H
+# define OSSL_CRYPTO_PEMERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_PEM_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/pkcs12err.h b/include/crypto/pkcs12err.h
new file mode 100644
index 00000000..662f412e
--- /dev/null
+++ b/include/crypto/pkcs12err.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_PKCS12ERR_H
+# define OSSL_CRYPTO_PKCS12ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_PKCS12_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/pkcs7.h b/include/crypto/pkcs7.h
new file mode 100644
index 00000000..9caa9af4
--- /dev/null
+++ b/include/crypto/pkcs7.h
@@ -0,0 +1,19 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_PKCS7_H
+# define OSSL_CRYPTO_PKCS7_H
+# pragma once
+
+void ossl_pkcs7_resolve_libctx(PKCS7 *p7);
+
+void ossl_pkcs7_set0_libctx(PKCS7 *p7, OSSL_LIB_CTX *ctx);
+int ossl_pkcs7_set1_propq(PKCS7 *p7, const char *propq);
+
+#endif
diff --git a/include/crypto/pkcs7err.h b/include/crypto/pkcs7err.h
new file mode 100644
index 00000000..c195190b
--- /dev/null
+++ b/include/crypto/pkcs7err.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_PKCS7ERR_H
+# define OSSL_CRYPTO_PKCS7ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_PKCS7_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/poly1305.h b/include/crypto/poly1305.h
new file mode 100644
index 00000000..ba54f3bd
--- /dev/null
+++ b/include/crypto/poly1305.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_POLY1305_H
+# define OSSL_CRYPTO_POLY1305_H
+# pragma once
+
+#include <stddef.h>
+
+#define POLY1305_BLOCK_SIZE 16
+#define POLY1305_DIGEST_SIZE 16
+#define POLY1305_KEY_SIZE 32
+
+typedef struct poly1305_context POLY1305;
+
+typedef void (*poly1305_blocks_f) (void *ctx, const unsigned char *inp,
+ size_t len, unsigned int padbit);
+typedef void (*poly1305_emit_f) (void *ctx, unsigned char mac[16],
+ const unsigned int nonce[4]);
+
+struct poly1305_context {
+ double opaque[24]; /* large enough to hold internal state, declared
+ * 'double' to ensure at least 64-bit invariant
+ * alignment across all platforms and
+ * configurations */
+ unsigned int nonce[4];
+ unsigned char data[POLY1305_BLOCK_SIZE];
+ size_t num;
+ struct {
+ poly1305_blocks_f blocks;
+ poly1305_emit_f emit;
+ } func;
+};
+
+size_t Poly1305_ctx_size(void);
+void Poly1305_Init(POLY1305 *ctx, const unsigned char key[32]);
+void Poly1305_Update(POLY1305 *ctx, const unsigned char *inp, size_t len);
+void Poly1305_Final(POLY1305 *ctx, unsigned char mac[16]);
+
+#endif /* OSSL_CRYPTO_POLY1305_H */
diff --git a/include/crypto/ppc_arch.h b/include/crypto/ppc_arch.h
new file mode 100644
index 00000000..3b3ce4bf
--- /dev/null
+++ b/include/crypto/ppc_arch.h
@@ -0,0 +1,28 @@
+/*
+ * Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_PPC_ARCH_H
+# define OSSL_CRYPTO_PPC_ARCH_H
+
+extern unsigned int OPENSSL_ppccap_P;
+
+/*
+ * Flags' usage can appear ambiguous, because they are set rather
+ * to reflect OpenSSL performance preferences than actual processor
+ * capabilities.
+ */
+# define PPC_FPU64 (1<<0)
+# define PPC_ALTIVEC (1<<1)
+# define PPC_CRYPTO207 (1<<2)
+# define PPC_FPU (1<<3)
+# define PPC_MADD300 (1<<4)
+# define PPC_MFTB (1<<5)
+# define PPC_MFSPR268 (1<<6)
+
+#endif
diff --git a/include/crypto/punycode.h b/include/crypto/punycode.h
new file mode 100644
index 00000000..133826d8
--- /dev/null
+++ b/include/crypto/punycode.h
@@ -0,0 +1,24 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_PUNYCODE_H
+# define OSSL_CRYPTO_PUNYCODE_H
+# pragma once
+
+int ossl_punycode_decode (
+ const char *pEncoded,
+ const size_t enc_len,
+ unsigned int *pDecoded,
+ unsigned int *pout_length
+);
+
+int ossl_a2ulabel(const char *in, char *out, size_t *outlen);
+
+int ossl_a2ucompare(const char *a, const char *u);
+#endif
diff --git a/include/crypto/rand.h b/include/crypto/rand.h
new file mode 100644
index 00000000..fa3b5b2b
--- /dev/null
+++ b/include/crypto/rand.h
@@ -0,0 +1,128 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * Licensed under the Apache License 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * https://www.openssl.org/source/license.html
+ * or in the file LICENSE in the source distribution.
+ */
+
+#ifndef OSSL_CRYPTO_RAND_H
+# define OSSL_CRYPTO_RAND_H
+# pragma once
+
+# include <openssl/rand.h>
+# include "crypto/rand_pool.h"
+
+# if defined(__APPLE__) && !defined(OPENSSL_NO_APPLE_CRYPTO_RANDOM)
+# include <Availability.h>
+# if (defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200) || \
+ (defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 80000)
+# define OPENSSL_APPLE_CRYPTO_RANDOM 1
+# include <CommonCrypto/CommonCryptoError.h>
+# include <CommonCrypto/CommonRandom.h>
+# endif
+# endif
+
+/*
+ * Defines related to seed sources
+ */
+#ifndef DEVRANDOM
+/*
+ * set this to a comma-separated list of 'random' device files to try out. By
+ * default, we will try to read at least one of these files
+ */
+# define DEVRANDOM "/dev/urandom", "/dev/random", "/dev/hwrng", "/dev/srandom"
+# if defined(__linux) && !defined(__ANDROID__)
+# ifndef DEVRANDOM_WAIT
+# define DEVRANDOM_WAIT "/dev/random"
+# endif
+/*
+ * Linux kernels 4.8 and later changes how their random device works and there
+ * is no reliable way to tell that /dev/urandom has been seeded -- getentropy(2)
+ * should be used instead.
+ */
+# ifndef DEVRANDOM_SAFE_KERNEL
+# define DEVRANDOM_SAFE_KERNEL 4, 8
+# endif
+/*
+ * Some operating systems do not permit select(2) on their random devices,
+ * defining this to zero will force the use of read(2) to extract one byte
+ * from /dev/random.
+ */
+# ifndef DEVRANDM_WAIT_USE_SELECT
+# define DEVRANDM_WAIT_USE_SELECT 1
+# endif
+/*
+ * Define the shared memory identifier used to indicate if the operating
+ * system has properly seeded the DEVRANDOM source.
+ */
+# ifndef OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID
+# define OPENSSL_RAND_SEED_DEVRANDOM_SHM_ID 114
+# endif
+
+# endif
+#endif
+
+#if !defined(OPENSSL_NO_EGD) && !defined(DEVRANDOM_EGD)
+/*
+ * set this to a comma-separated list of 'egd' sockets to try out. These
+ * sockets will be tried in the order listed in case accessing the device
+ * files listed in DEVRANDOM did not return enough randomness.
+ */
+# define DEVRANDOM_EGD "/var/run/egd-pool", "/dev/egd-pool", "/etc/egd-pool", "/etc/entropy"
+#endif
+
+void ossl_rand_cleanup_int(void);
+
+/*
+ * Initialise the random pool reseeding sources.
+ *
+ * Returns 1 on success and 0 on failure.
+ */
+int ossl_rand_pool_init(void);
+
+/*
+ * Finalise the random pool reseeding sources.
+ */
+void ossl_rand_pool_cleanup(void);
+
+/*
+ * Control the random pool use of open file descriptors.
+ */
+void ossl_rand_pool_keep_random_devices_open(int keep);
+
+/*
+ * Configuration
+ */
+void ossl_random_add_conf_module(void);
+
+/*
+ * Get and cleanup random seed material.
+ */
+size_t ossl_rand_get_entropy(ossl_unused OSSL_CORE_HANDLE *handle,
+ unsigned char **pout, int entropy,
+ size_t min_len, size_t max_len);
+void ossl_rand_cleanup_entropy(ossl_unused OSSL_CORE_HANDLE *handle,
+ unsigned char *buf, size_t len);
+size_t ossl_rand_get_nonce(ossl_unused OSSL_CORE_HANDLE *handle,
+ unsigned char **pout, size_t min_len, size_t max_len,
+ const void *salt, size_t salt_len);
+void ossl_rand_cleanup_nonce(ossl_unused OSSL_CORE_HANDLE *handle,
+ unsigned char *buf, size_t len);
+
+/*
+ * Get seeding material from the operating system sources.
+ */
+size_t ossl_pool_acquire_entropy(RAND_POOL *pool);
+int ossl_pool_add_nonce_data(RAND_POOL *pool);
+
+#endif
diff --git a/include/crypto/rand_pool.h b/include/crypto/rand_pool.h
new file mode 100644
index 00000000..f4d1d954
--- /dev/null
+++ b/include/crypto/rand_pool.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_PROVIDER_RAND_POOL_H
+# define OSSL_PROVIDER_RAND_POOL_H
+# pragma once
+
+# include <stdio.h>
+# include <openssl/rand.h>
+
+/*
+ * Maximum allocation size for RANDOM_POOL buffers
+ *
+ * The max_len value for the buffer provided to the rand_drbg_get_entropy()
+ * callback is currently 2^31 bytes (2 gigabytes), if a derivation function
+ * is used. Since this is much too large to be allocated, the ossl_rand_pool_new()
+ * function chooses more modest values as default pool length, bounded
+ * by RAND_POOL_MIN_LENGTH and RAND_POOL_MAX_LENGTH
+ *
+ * The choice of the RAND_POOL_FACTOR is large enough such that the
+ * RAND_POOL can store a random input which has a lousy entropy rate of
+ * 8/256 (= 0.03125) bits per byte. This input will be sent through the
+ * derivation function which 'compresses' the low quality input into a
+ * high quality output.
+ *
+ * The factor 1.5 below is the pessimistic estimate for the extra amount
+ * of entropy required when no get_nonce() callback is defined.
+ */
+# define RAND_POOL_FACTOR 256
+# define RAND_POOL_MAX_LENGTH (RAND_POOL_FACTOR * \
+ 3 * (RAND_DRBG_STRENGTH / 16))
+/*
+ * = (RAND_POOL_FACTOR * \
+ * 1.5 * (RAND_DRBG_STRENGTH / 8))
+ */
+
+/*
+ * Initial allocation minimum.
+ *
+ * There is a distinction between the secure and normal allocation minimums.
+ * Ideally, the secure allocation size should be a power of two. The normal
+ * allocation size doesn't have any such restriction.
+ *
+ * The secure value is based on 128 bits of secure material, which is 16 bytes.
+ * Typically, the DRBGs will set a minimum larger than this so optimal
+ * allocation ought to take place (for full quality seed material).
+ *
+ * The normal value has been chosen by noticing that the rand_drbg_get_nonce
+ * function is usually the largest of the built in allocation (twenty four
+ * bytes and then appending another sixteen bytes). This means the buffer ends
+ * with 40 bytes. The value of forty eight is comfortably above this which
+ * allows some slack in the platform specific values used.
+ */
+# define RAND_POOL_MIN_ALLOCATION(secure) ((secure) ? 16 : 48)
+
+/*
+ * The 'random pool' acts as a dumb container for collecting random
+ * input from various entropy sources. It is the callers duty to 1) initialize
+ * the random pool, 2) pass it to the polling callbacks, 3) seed the RNG, and
+ * 4) cleanup the random pool again.
+ *
+ * The random pool contains no locking mechanism because its scope and
+ * lifetime is intended to be restricted to a single stack frame.
+ */
+typedef struct rand_pool_st {
+ unsigned char *buffer; /* points to the beginning of the random pool */
+ size_t len; /* current number of random bytes contained in the pool */
+
+ int attached; /* true pool was attached to existing buffer */
+ int secure; /* 1: allocated on the secure heap, 0: otherwise */
+
+ size_t min_len; /* minimum number of random bytes requested */
+ size_t max_len; /* maximum number of random bytes (allocated buffer size) */
+ size_t alloc_len; /* current number of bytes allocated */
+ size_t entropy; /* current entropy count in bits */
+ size_t entropy_requested; /* requested entropy count in bits */
+} RAND_POOL;
+
+RAND_POOL *ossl_rand_pool_new(int entropy_requested, int secure,
+ size_t min_len, size_t max_len);
+RAND_POOL *ossl_rand_pool_attach(const unsigned char *buffer, size_t len,
+ size_t entropy);
+void ossl_rand_pool_free(RAND_POOL *pool);
+
+const unsigned char *ossl_rand_pool_buffer(RAND_POOL *pool);
+unsigned char *ossl_rand_pool_detach(RAND_POOL *pool);
+void ossl_rand_pool_reattach(RAND_POOL *pool, unsigned char *buffer);
+
+size_t ossl_rand_pool_entropy(RAND_POOL *pool);
+size_t ossl_rand_pool_length(RAND_POOL *pool);
+
+size_t ossl_rand_pool_entropy_available(RAND_POOL *pool);
+size_t ossl_rand_pool_entropy_needed(RAND_POOL *pool);
+/* |entropy_factor| expresses how many bits of data contain 1 bit of entropy */
+size_t ossl_rand_pool_bytes_needed(RAND_POOL *pool, unsigned int entropy_factor);
+size_t ossl_rand_pool_bytes_remaining(RAND_POOL *pool);
+
+int ossl_rand_pool_add(RAND_POOL *pool,
+ const unsigned char *buffer, size_t len, size_t entropy);
+unsigned char *ossl_rand_pool_add_begin(RAND_POOL *pool, size_t len);
+int ossl_rand_pool_add_end(RAND_POOL *pool, size_t len, size_t entropy);
+
+#endif /* OSSL_PROVIDER_RAND_POOL_H */
diff --git a/include/crypto/randerr.h b/include/crypto/randerr.h
new file mode 100644
index 00000000..832a8b7d
--- /dev/null
+++ b/include/crypto/randerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_RANDERR_H
+# define OSSL_CRYPTO_RANDERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_RAND_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/rsa.h b/include/crypto/rsa.h
new file mode 100644
index 00000000..100e7ceb
--- /dev/null
+++ b/include/crypto/rsa.h
@@ -0,0 +1,129 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_RSA_H
+# define OSSL_INTERNAL_RSA_H
+# pragma once
+
+# include <openssl/core.h>
+# include <openssl/rsa.h>
+# include "crypto/types.h"
+
+#define RSA_MIN_MODULUS_BITS 512
+
+typedef struct rsa_pss_params_30_st {
+ int hash_algorithm_nid;
+ struct {
+ int algorithm_nid; /* Currently always NID_mgf1 */
+ int hash_algorithm_nid;
+ } mask_gen;
+ int salt_len;
+ int trailer_field;
+} RSA_PSS_PARAMS_30;
+
+RSA_PSS_PARAMS_30 *ossl_rsa_get0_pss_params_30(RSA *r);
+int ossl_rsa_pss_params_30_set_defaults(RSA_PSS_PARAMS_30 *rsa_pss_params);
+int ossl_rsa_pss_params_30_copy(RSA_PSS_PARAMS_30 *to,
+ const RSA_PSS_PARAMS_30 *from);
+int ossl_rsa_pss_params_30_is_unrestricted(const RSA_PSS_PARAMS_30 *rsa_pss_params);
+int ossl_rsa_pss_params_30_set_hashalg(RSA_PSS_PARAMS_30 *rsa_pss_params,
+ int hashalg_nid);
+int ossl_rsa_pss_params_30_set_maskgenalg(RSA_PSS_PARAMS_30 *rsa_pss_params,
+ int maskgenalg_nid);
+int ossl_rsa_pss_params_30_set_maskgenhashalg(RSA_PSS_PARAMS_30 *rsa_pss_params,
+ int maskgenhashalg_nid);
+int ossl_rsa_pss_params_30_set_saltlen(RSA_PSS_PARAMS_30 *rsa_pss_params,
+ int saltlen);
+int ossl_rsa_pss_params_30_set_trailerfield(RSA_PSS_PARAMS_30 *rsa_pss_params,
+ int trailerfield);
+int ossl_rsa_pss_params_30_hashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params);
+int ossl_rsa_pss_params_30_maskgenalg(const RSA_PSS_PARAMS_30 *rsa_pss_params);
+int ossl_rsa_pss_params_30_maskgenhashalg(const RSA_PSS_PARAMS_30 *rsa_pss_params);
+int ossl_rsa_pss_params_30_saltlen(const RSA_PSS_PARAMS_30 *rsa_pss_params);
+int ossl_rsa_pss_params_30_trailerfield(const RSA_PSS_PARAMS_30 *rsa_pss_params);
+
+const char *ossl_rsa_mgf_nid2name(int mgf);
+int ossl_rsa_oaeppss_md2nid(const EVP_MD *md);
+const char *ossl_rsa_oaeppss_nid2name(int md);
+
+RSA *ossl_rsa_new_with_ctx(OSSL_LIB_CTX *libctx);
+OSSL_LIB_CTX *ossl_rsa_get0_libctx(RSA *r);
+void ossl_rsa_set0_libctx(RSA *r, OSSL_LIB_CTX *libctx);
+
+int ossl_rsa_set0_all_params(RSA *r, const STACK_OF(BIGNUM) *primes,
+ const STACK_OF(BIGNUM) *exps,
+ const STACK_OF(BIGNUM) *coeffs);
+int ossl_rsa_get0_all_params(RSA *r, STACK_OF(BIGNUM_const) *primes,
+ STACK_OF(BIGNUM_const) *exps,
+ STACK_OF(BIGNUM_const) *coeffs);
+int ossl_rsa_is_foreign(const RSA *rsa);
+RSA *ossl_rsa_dup(const RSA *rsa, int selection);
+
+int ossl_rsa_todata(RSA *rsa, OSSL_PARAM_BLD *bld, OSSL_PARAM params[]);
+int ossl_rsa_fromdata(RSA *rsa, const OSSL_PARAM params[]);
+int ossl_rsa_pss_params_30_todata(const RSA_PSS_PARAMS_30 *pss,
+ OSSL_PARAM_BLD *bld, OSSL_PARAM params[]);
+int ossl_rsa_pss_params_30_fromdata(RSA_PSS_PARAMS_30 *pss_params,
+ int *defaults_set,
+ const OSSL_PARAM params[],
+ OSSL_LIB_CTX *libctx);
+int ossl_rsa_set0_pss_params(RSA *r, RSA_PSS_PARAMS *pss);
+int ossl_rsa_pss_get_param_unverified(const RSA_PSS_PARAMS *pss,
+ const EVP_MD **pmd, const EVP_MD **pmgf1md,
+ int *psaltlen, int *ptrailerField);
+RSA_PSS_PARAMS *ossl_rsa_pss_decode(const X509_ALGOR *alg);
+int ossl_rsa_param_decode(RSA *rsa, const X509_ALGOR *alg);
+RSA *ossl_rsa_key_from_pkcs8(const PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+int ossl_rsa_padding_check_PKCS1_type_2_TLS(OSSL_LIB_CTX *ctx, unsigned char *to,
+ size_t tlen,
+ const unsigned char *from,
+ size_t flen, int client_version,
+ int alt_version);
+int ossl_rsa_padding_add_PKCS1_OAEP_mgf1_ex(OSSL_LIB_CTX *libctx,
+ unsigned char *to, int tlen,
+ const unsigned char *from, int flen,
+ const unsigned char *param,
+ int plen, const EVP_MD *md,
+ const EVP_MD *mgf1md);
+
+int ossl_rsa_validate_public(const RSA *key);
+int ossl_rsa_validate_private(const RSA *key);
+int ossl_rsa_validate_pairwise(const RSA *key);
+
+int ossl_rsa_verify(int dtype, const unsigned char *m,
+ unsigned int m_len, unsigned char *rm,
+ size_t *prm_len, const unsigned char *sigbuf,
+ size_t siglen, RSA *rsa);
+
+const unsigned char *ossl_rsa_digestinfo_encoding(int md_nid, size_t *len);
+
+extern const char *ossl_rsa_mp_factor_names[];
+extern const char *ossl_rsa_mp_exp_names[];
+extern const char *ossl_rsa_mp_coeff_names[];
+
+ASN1_STRING *ossl_rsa_ctx_to_pss_string(EVP_PKEY_CTX *pkctx);
+int ossl_rsa_pss_to_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pkctx,
+ const X509_ALGOR *sigalg, EVP_PKEY *pkey);
+
+# if defined(FIPS_MODULE) && !defined(OPENSSL_NO_ACVP_TESTS)
+int ossl_rsa_acvp_test_gen_params_new(OSSL_PARAM **dst, const OSSL_PARAM src[]);
+void ossl_rsa_acvp_test_gen_params_free(OSSL_PARAM *dst);
+
+int ossl_rsa_acvp_test_set_params(RSA *r, const OSSL_PARAM params[]);
+int ossl_rsa_acvp_test_get_params(RSA *r, OSSL_PARAM params[]);
+typedef struct rsa_acvp_test_st RSA_ACVP_TEST;
+void ossl_rsa_acvp_test_free(RSA_ACVP_TEST *t);
+# else
+# define RSA_ACVP_TEST void
+# endif
+
+RSA *evp_pkey_get1_RSA_PSS(EVP_PKEY *pkey);
+#endif
diff --git a/include/crypto/rsaerr.h b/include/crypto/rsaerr.h
new file mode 100644
index 00000000..9b23500b
--- /dev/null
+++ b/include/crypto/rsaerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_RSAERR_H
+# define OSSL_CRYPTO_RSAERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_RSA_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/security_bits.h b/include/crypto/security_bits.h
new file mode 100644
index 00000000..58f49681
--- /dev/null
+++ b/include/crypto/security_bits.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_SECURITY_BITS_H
+# define OSSL_SECURITY_BITS_H
+# pragma once
+
+uint16_t ossl_ifc_ffc_compute_security_bits(int n);
+
+#endif
diff --git a/include/crypto/sha.h b/include/crypto/sha.h
new file mode 100644
index 00000000..64305d17
--- /dev/null
+++ b/include/crypto/sha.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_SHA_H
+# define OSSL_CRYPTO_SHA_H
+# pragma once
+
+# include <openssl/sha.h>
+
+int sha512_224_init(SHA512_CTX *);
+int sha512_256_init(SHA512_CTX *);
+int ossl_sha1_ctrl(SHA_CTX *ctx, int cmd, int mslen, void *ms);
+unsigned char *ossl_sha1(const unsigned char *d, size_t n, unsigned char *md);
+
+#endif
diff --git a/include/crypto/siphash.h b/include/crypto/siphash.h
new file mode 100644
index 00000000..0d0767fc
--- /dev/null
+++ b/include/crypto/siphash.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_SIPHASH_H
+# define OSSL_CRYPTO_SIPHASH_H
+# pragma once
+
+# include <stddef.h>
+
+# define SIPHASH_BLOCK_SIZE 8
+# define SIPHASH_KEY_SIZE 16
+# define SIPHASH_MIN_DIGEST_SIZE 8
+# define SIPHASH_MAX_DIGEST_SIZE 16
+
+typedef struct siphash_st SIPHASH;
+
+size_t SipHash_ctx_size(void);
+size_t SipHash_hash_size(SIPHASH *ctx);
+int SipHash_set_hash_size(SIPHASH *ctx, size_t hash_size);
+int SipHash_Init(SIPHASH *ctx, const unsigned char *k,
+ int crounds, int drounds);
+void SipHash_Update(SIPHASH *ctx, const unsigned char *in, size_t inlen);
+int SipHash_Final(SIPHASH *ctx, unsigned char *out, size_t outlen);
+
+/* Based on https://131002.net/siphash C reference implementation */
+
+struct siphash_st {
+ uint64_t total_inlen;
+ uint64_t v0;
+ uint64_t v1;
+ uint64_t v2;
+ uint64_t v3;
+ unsigned int len;
+ unsigned int hash_size;
+ unsigned int crounds;
+ unsigned int drounds;
+ unsigned char leavings[SIPHASH_BLOCK_SIZE];
+};
+
+/* default: SipHash-2-4 */
+# define SIPHASH_C_ROUNDS 2
+# define SIPHASH_D_ROUNDS 4
+
+#endif
diff --git a/include/crypto/siv.h b/include/crypto/siv.h
new file mode 100644
index 00000000..8dc58bd3
--- /dev/null
+++ b/include/crypto/siv.h
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_NO_SIV
+
+typedef struct siv128_context SIV128_CONTEXT;
+
+SIV128_CONTEXT *ossl_siv128_new(const unsigned char *key, int klen,
+ EVP_CIPHER *cbc, EVP_CIPHER *ctr,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int ossl_siv128_init(SIV128_CONTEXT *ctx, const unsigned char *key, int klen,
+ const EVP_CIPHER *cbc, const EVP_CIPHER *ctr,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int ossl_siv128_copy_ctx(SIV128_CONTEXT *dest, SIV128_CONTEXT *src);
+int ossl_siv128_aad(SIV128_CONTEXT *ctx, const unsigned char *aad, size_t len);
+int ossl_siv128_encrypt(SIV128_CONTEXT *ctx,
+ const unsigned char *in, unsigned char *out, size_t len);
+int ossl_siv128_decrypt(SIV128_CONTEXT *ctx,
+ const unsigned char *in, unsigned char *out, size_t len);
+int ossl_siv128_finish(SIV128_CONTEXT *ctx);
+int ossl_siv128_set_tag(SIV128_CONTEXT *ctx, const unsigned char *tag,
+ size_t len);
+int ossl_siv128_get_tag(SIV128_CONTEXT *ctx, unsigned char *tag, size_t len);
+int ossl_siv128_cleanup(SIV128_CONTEXT *ctx);
+int ossl_siv128_speed(SIV128_CONTEXT *ctx, int arg);
+
+#endif /* OPENSSL_NO_SIV */
diff --git a/include/crypto/sm2.h b/include/crypto/sm2.h
new file mode 100644
index 00000000..9ab6c0b7
--- /dev/null
+++ b/include/crypto/sm2.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017 Ribose Inc. All Rights Reserved.
+ * Ported from Ribose contributions from Botan.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_SM2_H
+# define OSSL_CRYPTO_SM2_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# if !defined(OPENSSL_NO_SM2) && !defined(FIPS_MODULE)
+
+# include <openssl/ec.h>
+# include "crypto/types.h"
+
+int ossl_sm2_key_private_check(const EC_KEY *eckey);
+
+/* The default user id as specified in GM/T 0009-2012 */
+# define SM2_DEFAULT_USERID "1234567812345678"
+
+int ossl_sm2_compute_z_digest(uint8_t *out,
+ const EVP_MD *digest,
+ const uint8_t *id,
+ const size_t id_len,
+ const EC_KEY *key);
+
+/*
+ * SM2 signature operation. Computes Z and then signs H(Z || msg) using SM2
+ */
+ECDSA_SIG *ossl_sm2_do_sign(const EC_KEY *key,
+ const EVP_MD *digest,
+ const uint8_t *id,
+ const size_t id_len,
+ const uint8_t *msg, size_t msg_len);
+
+int ossl_sm2_do_verify(const EC_KEY *key,
+ const EVP_MD *digest,
+ const ECDSA_SIG *signature,
+ const uint8_t *id,
+ const size_t id_len,
+ const uint8_t *msg, size_t msg_len);
+
+/*
+ * SM2 signature generation.
+ */
+int ossl_sm2_internal_sign(const unsigned char *dgst, int dgstlen,
+ unsigned char *sig, unsigned int *siglen,
+ EC_KEY *eckey);
+
+/*
+ * SM2 signature verification.
+ */
+int ossl_sm2_internal_verify(const unsigned char *dgst, int dgstlen,
+ const unsigned char *sig, int siglen,
+ EC_KEY *eckey);
+
+/*
+ * SM2 encryption
+ */
+int ossl_sm2_ciphertext_size(const EC_KEY *key, const EVP_MD *digest,
+ size_t msg_len, size_t *ct_size);
+
+int ossl_sm2_plaintext_size(const unsigned char *ct, size_t ct_size,
+ size_t *pt_size);
+
+int ossl_sm2_encrypt(const EC_KEY *key,
+ const EVP_MD *digest,
+ const uint8_t *msg, size_t msg_len,
+ uint8_t *ciphertext_buf, size_t *ciphertext_len);
+
+int ossl_sm2_decrypt(const EC_KEY *key,
+ const EVP_MD *digest,
+ const uint8_t *ciphertext, size_t ciphertext_len,
+ uint8_t *ptext_buf, size_t *ptext_len);
+
+const unsigned char *ossl_sm2_algorithmidentifier_encoding(int md_nid,
+ size_t *len);
+# endif /* OPENSSL_NO_SM2 */
+#endif
diff --git a/include/crypto/sm2err.h b/include/crypto/sm2err.h
new file mode 100644
index 00000000..706f4d69
--- /dev/null
+++ b/include/crypto/sm2err.h
@@ -0,0 +1,49 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_SM2ERR_H
+# define OSSL_CRYPTO_SM2ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_SM2
+
+int ossl_err_load_SM2_strings(void);
+
+/*
+ * SM2 reason codes.
+ */
+# define SM2_R_ASN1_ERROR 100
+# define SM2_R_BAD_SIGNATURE 101
+# define SM2_R_BUFFER_TOO_SMALL 107
+# define SM2_R_DIST_ID_TOO_LARGE 110
+# define SM2_R_ID_NOT_SET 112
+# define SM2_R_ID_TOO_LARGE 111
+# define SM2_R_INVALID_CURVE 108
+# define SM2_R_INVALID_DIGEST 102
+# define SM2_R_INVALID_DIGEST_TYPE 103
+# define SM2_R_INVALID_ENCODING 104
+# define SM2_R_INVALID_FIELD 105
+# define SM2_R_INVALID_PRIVATE_KEY 113
+# define SM2_R_NO_PARAMETERS_SET 109
+# define SM2_R_USER_ID_TOO_LARGE 106
+
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/sm4.h b/include/crypto/sm4.h
new file mode 100644
index 00000000..e21ec81c
--- /dev/null
+++ b/include/crypto/sm4.h
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017 Ribose Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_SM4_H
+# define OSSL_CRYPTO_SM4_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/e_os2.h>
+
+# ifdef OPENSSL_NO_SM4
+# error SM4 is disabled.
+# endif
+
+# define SM4_ENCRYPT 1
+# define SM4_DECRYPT 0
+
+# define SM4_BLOCK_SIZE 16
+# define SM4_KEY_SCHEDULE 32
+
+typedef struct SM4_KEY_st {
+ uint32_t rk[SM4_KEY_SCHEDULE];
+} SM4_KEY;
+
+int ossl_sm4_set_key(const uint8_t *key, SM4_KEY *ks);
+
+void ossl_sm4_encrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks);
+
+void ossl_sm4_decrypt(const uint8_t *in, uint8_t *out, const SM4_KEY *ks);
+
+#endif
diff --git a/include/crypto/sparc_arch.h b/include/crypto/sparc_arch.h
new file mode 100644
index 00000000..447e715b
--- /dev/null
+++ b/include/crypto/sparc_arch.h
@@ -0,0 +1,122 @@
+/*
+ * Copyright 2012-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_SPARC_ARCH_H
+# define OSSL_CRYPTO_SPARC_ARCH_H
+
+# define SPARCV9_TICK_PRIVILEGED (1<<0)
+# define SPARCV9_PREFER_FPU (1<<1)
+# define SPARCV9_VIS1 (1<<2)
+# define SPARCV9_VIS2 (1<<3)/* reserved */
+# define SPARCV9_FMADD (1<<4)
+# define SPARCV9_BLK (1<<5)/* VIS1 block copy */
+# define SPARCV9_VIS3 (1<<6)
+# define SPARCV9_RANDOM (1<<7)
+# define SPARCV9_64BIT_STACK (1<<8)
+# define SPARCV9_FJAESX (1<<9)/* Fujitsu SPARC64 X AES */
+# define SPARCV9_FJDESX (1<<10)/* Fujitsu SPARC64 X DES, reserved */
+# define SPARCV9_FJHPCACE (1<<11)/* Fujitsu HPC-ACE, reserved */
+# define SPARCV9_IMA (1<<13)/* reserved */
+# define SPARCV9_VIS4 (1<<14)/* reserved */
+
+/*
+ * OPENSSL_sparcv9cap_P[1] is copy of Compatibility Feature Register,
+ * %asr26, SPARC-T4 and later. There is no SPARCV9_CFR bit in
+ * OPENSSL_sparcv9cap_P[0], as %cfr copy is sufficient...
+ */
+# define CFR_AES 0x00000001/* Supports AES opcodes */
+# define CFR_DES 0x00000002/* Supports DES opcodes */
+# define CFR_KASUMI 0x00000004/* Supports KASUMI opcodes */
+# define CFR_CAMELLIA 0x00000008/* Supports CAMELLIA opcodes */
+# define CFR_MD5 0x00000010/* Supports MD5 opcodes */
+# define CFR_SHA1 0x00000020/* Supports SHA1 opcodes */
+# define CFR_SHA256 0x00000040/* Supports SHA256 opcodes */
+# define CFR_SHA512 0x00000080/* Supports SHA512 opcodes */
+# define CFR_MPMUL 0x00000100/* Supports MPMUL opcodes */
+# define CFR_MONTMUL 0x00000200/* Supports MONTMUL opcodes */
+# define CFR_MONTSQR 0x00000400/* Supports MONTSQR opcodes */
+# define CFR_CRC32C 0x00000800/* Supports CRC32C opcodes */
+# define CFR_XMPMUL 0x00001000/* Supports XMPMUL opcodes */
+# define CFR_XMONTMUL 0x00002000/* Supports XMONTMUL opcodes */
+# define CFR_XMONTSQR 0x00004000/* Supports XMONTSQR opcodes */
+
+# if defined(OPENSSL_PIC) && !defined(__PIC__)
+# define __PIC__
+# endif
+
+# if defined(__SUNPRO_C) && defined(__sparcv9) && !defined(__arch64__)
+# define __arch64__
+# endif
+
+# define SPARC_PIC_THUNK(reg) \
+ .align 32; \
+.Lpic_thunk: \
+ jmp %o7 + 8; \
+ add %o7, reg, reg;
+
+# define SPARC_PIC_THUNK_CALL(reg) \
+ sethi %hi(_GLOBAL_OFFSET_TABLE_-4), reg; \
+ call .Lpic_thunk; \
+ or reg, %lo(_GLOBAL_OFFSET_TABLE_+4), reg;
+
+# if 1
+# define SPARC_SETUP_GOT_REG(reg) SPARC_PIC_THUNK_CALL(reg)
+# else
+# define SPARC_SETUP_GOT_REG(reg) \
+ sethi %hi(_GLOBAL_OFFSET_TABLE_-4), reg; \
+ call .+8; \
+ or reg,%lo(_GLOBAL_OFFSET_TABLE_+4), reg; \
+ add %o7, reg, reg
+# endif
+
+# if defined(__arch64__)
+
+# define SPARC_LOAD_ADDRESS(SYM, reg) \
+ setx SYM, %o7, reg;
+# define LDPTR ldx
+# define SIZE_T_CC %xcc
+# define STACK_FRAME 192
+# define STACK_BIAS 2047
+# define STACK_7thARG (STACK_BIAS+176)
+
+# else
+
+# define SPARC_LOAD_ADDRESS(SYM, reg) \
+ set SYM, reg;
+# define LDPTR ld
+# define SIZE_T_CC %icc
+# define STACK_FRAME 112
+# define STACK_BIAS 0
+# define STACK_7thARG 92
+# define SPARC_LOAD_ADDRESS_LEAF(SYM,reg,tmp) SPARC_LOAD_ADDRESS(SYM,reg)
+
+# endif
+
+# ifdef __PIC__
+# undef SPARC_LOAD_ADDRESS
+# undef SPARC_LOAD_ADDRESS_LEAF
+# define SPARC_LOAD_ADDRESS(SYM, reg) \
+ SPARC_SETUP_GOT_REG(reg); \
+ sethi %hi(SYM), %o7; \
+ or %o7, %lo(SYM), %o7; \
+ LDPTR [reg + %o7], reg;
+# endif
+
+# ifndef SPARC_LOAD_ADDRESS_LEAF
+# define SPARC_LOAD_ADDRESS_LEAF(SYM, reg, tmp) \
+ mov %o7, tmp; \
+ SPARC_LOAD_ADDRESS(SYM, reg) \
+ mov tmp, %o7;
+# endif
+
+# ifndef __ASSEMBLER__
+extern unsigned int OPENSSL_sparcv9cap_P[2];
+# endif
+
+#endif /* OSSL_CRYPTO_SPARC_ARCH_H */
diff --git a/include/crypto/sparse_array.h b/include/crypto/sparse_array.h
new file mode 100644
index 00000000..7ef74283
--- /dev/null
+++ b/include/crypto/sparse_array.h
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_SPARSE_ARRAY_H
+# define OSSL_CRYPTO_SPARSE_ARRAY_H
+# pragma once
+
+# include <openssl/e_os2.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define SPARSE_ARRAY_OF(type) struct sparse_array_st_ ## type
+
+# define DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, ctype) \
+ SPARSE_ARRAY_OF(type); \
+ static ossl_unused ossl_inline SPARSE_ARRAY_OF(type) * \
+ ossl_sa_##type##_new(void) \
+ { \
+ return (SPARSE_ARRAY_OF(type) *)ossl_sa_new(); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_sa_##type##_free(SPARSE_ARRAY_OF(type) *sa) \
+ { \
+ ossl_sa_free((OPENSSL_SA *)sa); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_sa_##type##_free_leaves(SPARSE_ARRAY_OF(type) *sa) \
+ { \
+ ossl_sa_free_leaves((OPENSSL_SA *)sa); \
+ } \
+ static ossl_unused ossl_inline size_t \
+ ossl_sa_##type##_num(const SPARSE_ARRAY_OF(type) *sa) \
+ { \
+ return ossl_sa_num((OPENSSL_SA *)sa); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_sa_##type##_doall(const SPARSE_ARRAY_OF(type) *sa, \
+ void (*leaf)(ossl_uintmax_t, type *)) \
+ { \
+ ossl_sa_doall((OPENSSL_SA *)sa, \
+ (void (*)(ossl_uintmax_t, void *))leaf); \
+ } \
+ static ossl_unused ossl_inline void \
+ ossl_sa_##type##_doall_arg(const SPARSE_ARRAY_OF(type) *sa, \
+ void (*leaf)(ossl_uintmax_t, type *, void *), \
+ void *arg) \
+ { \
+ ossl_sa_doall_arg((OPENSSL_SA *)sa, \
+ (void (*)(ossl_uintmax_t, void *, void *))leaf, arg); \
+ } \
+ static ossl_unused ossl_inline ctype \
+ *ossl_sa_##type##_get(const SPARSE_ARRAY_OF(type) *sa, ossl_uintmax_t n) \
+ { \
+ return (type *)ossl_sa_get((OPENSSL_SA *)sa, n); \
+ } \
+ static ossl_unused ossl_inline int \
+ ossl_sa_##type##_set(SPARSE_ARRAY_OF(type) *sa, \
+ ossl_uintmax_t n, ctype *val) \
+ { \
+ return ossl_sa_set((OPENSSL_SA *)sa, n, (void *)val); \
+ } \
+ SPARSE_ARRAY_OF(type)
+
+# define DEFINE_SPARSE_ARRAY_OF(type) \
+ DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, type)
+# define DEFINE_SPARSE_ARRAY_OF_CONST(type) \
+ DEFINE_SPARSE_ARRAY_OF_INTERNAL(type, const type)
+
+typedef struct sparse_array_st OPENSSL_SA;
+OPENSSL_SA *ossl_sa_new(void);
+void ossl_sa_free(OPENSSL_SA *sa);
+void ossl_sa_free_leaves(OPENSSL_SA *sa);
+size_t ossl_sa_num(const OPENSSL_SA *sa);
+void ossl_sa_doall(const OPENSSL_SA *sa, void (*leaf)(ossl_uintmax_t, void *));
+void ossl_sa_doall_arg(const OPENSSL_SA *sa,
+ void (*leaf)(ossl_uintmax_t, void *, void *), void *);
+void *ossl_sa_get(const OPENSSL_SA *sa, ossl_uintmax_t n);
+int ossl_sa_set(OPENSSL_SA *sa, ossl_uintmax_t n, void *val);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/store.h b/include/crypto/store.h
new file mode 100644
index 00000000..13d2646b
--- /dev/null
+++ b/include/crypto/store.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_STORE_H
+# define OSSL_CRYPTO_STORE_H
+# pragma once
+
+# include <openssl/bio.h>
+# include <openssl/store.h>
+# include <openssl/ui.h>
+
+void ossl_store_cleanup_int(void);
+int ossl_store_loader_get_number(const OSSL_STORE_LOADER *loader);
+
+#endif
diff --git a/include/crypto/storeerr.h b/include/crypto/storeerr.h
new file mode 100644
index 00000000..c46d845f
--- /dev/null
+++ b/include/crypto/storeerr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_STOREERR_H
+# define OSSL_CRYPTO_STOREERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_OSSL_STORE_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/tserr.h b/include/crypto/tserr.h
new file mode 100644
index 00000000..2f34ba31
--- /dev/null
+++ b/include/crypto/tserr.h
@@ -0,0 +1,30 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_TSERR_H
+# define OSSL_CRYPTO_TSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_TS
+
+int ossl_err_load_TS_strings(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/types.h b/include/crypto/types.h
new file mode 100644
index 00000000..0d814040
--- /dev/null
+++ b/include/crypto/types.h
@@ -0,0 +1,29 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/* When removal is simulated, we still need the type internally */
+
+#ifndef OSSL_CRYPTO_TYPES_H
+# define OSSL_CRYPTO_TYPES_H
+# pragma once
+
+# ifdef OPENSSL_NO_DEPRECATED_3_0
+typedef struct rsa_st RSA;
+typedef struct rsa_meth_st RSA_METHOD;
+# ifndef OPENSSL_NO_EC
+typedef struct ec_key_st EC_KEY;
+typedef struct ec_key_method_st EC_KEY_METHOD;
+# endif
+# endif
+
+# ifndef OPENSSL_NO_EC
+typedef struct ecx_key_st ECX_KEY;
+# endif
+
+#endif
diff --git a/include/crypto/uierr.h b/include/crypto/uierr.h
new file mode 100644
index 00000000..789077a8
--- /dev/null
+++ b/include/crypto/uierr.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_UIERR_H
+# define OSSL_CRYPTO_UIERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_UI_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/x509.h b/include/crypto/x509.h
new file mode 100644
index 00000000..1f00178e
--- /dev/null
+++ b/include/crypto/x509.h
@@ -0,0 +1,367 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_X509_H
+# define OSSL_CRYPTO_X509_H
+# pragma once
+
+# include "internal/refcount.h"
+# include <openssl/asn1.h>
+# include <openssl/x509.h>
+# include <openssl/conf.h>
+# include "crypto/types.h"
+
+/* Internal X509 structures and functions: not for application use */
+
+/* Note: unless otherwise stated a field pointer is mandatory and should
+ * never be set to NULL: the ASN.1 code and accessors rely on mandatory
+ * fields never being NULL.
+ */
+
+/*
+ * name entry structure, equivalent to AttributeTypeAndValue defined
+ * in RFC5280 et al.
+ */
+struct X509_name_entry_st {
+ ASN1_OBJECT *object; /* AttributeType */
+ ASN1_STRING *value; /* AttributeValue */
+ int set; /* index of RDNSequence for this entry */
+ int size; /* temp variable */
+};
+
+/* Name from RFC 5280. */
+struct X509_name_st {
+ STACK_OF(X509_NAME_ENTRY) *entries; /* DN components */
+ int modified; /* true if 'bytes' needs to be built */
+ BUF_MEM *bytes; /* cached encoding: cannot be NULL */
+ /* canonical encoding used for rapid Name comparison */
+ unsigned char *canon_enc;
+ int canon_enclen;
+} /* X509_NAME */ ;
+
+/* Signature info structure */
+
+struct x509_sig_info_st {
+ /* NID of message digest */
+ int mdnid;
+ /* NID of public key algorithm */
+ int pknid;
+ /* Security bits */
+ int secbits;
+ /* Various flags */
+ uint32_t flags;
+};
+
+/* PKCS#10 certificate request */
+
+struct X509_req_info_st {
+ ASN1_ENCODING enc; /* cached encoding of signed part */
+ ASN1_INTEGER *version; /* version, defaults to v1(0) so can be NULL */
+ X509_NAME *subject; /* certificate request DN */
+ X509_PUBKEY *pubkey; /* public key of request */
+ /*
+ * Zero or more attributes.
+ * NB: although attributes is a mandatory field some broken
+ * encodings omit it so this may be NULL in that case.
+ */
+ STACK_OF(X509_ATTRIBUTE) *attributes;
+};
+
+struct X509_req_st {
+ X509_REQ_INFO req_info; /* signed certificate request data */
+ X509_ALGOR sig_alg; /* signature algorithm */
+ ASN1_BIT_STRING *signature; /* signature */
+ CRYPTO_REF_COUNT references;
+ CRYPTO_RWLOCK *lock;
+
+ /* Set on live certificates for authentication purposes */
+ ASN1_OCTET_STRING *distinguishing_id;
+ OSSL_LIB_CTX *libctx;
+ char *propq;
+};
+
+struct X509_crl_info_st {
+ ASN1_INTEGER *version; /* version: defaults to v1(0) so may be NULL */
+ X509_ALGOR sig_alg; /* signature algorithm */
+ X509_NAME *issuer; /* CRL issuer name */
+ ASN1_TIME *lastUpdate; /* lastUpdate field */
+ ASN1_TIME *nextUpdate; /* nextUpdate field: optional */
+ STACK_OF(X509_REVOKED) *revoked; /* revoked entries: optional */
+ STACK_OF(X509_EXTENSION) *extensions; /* extensions: optional */
+ ASN1_ENCODING enc; /* encoding of signed portion of CRL */
+};
+
+struct X509_crl_st {
+ X509_CRL_INFO crl; /* signed CRL data */
+ X509_ALGOR sig_alg; /* CRL signature algorithm */
+ ASN1_BIT_STRING signature; /* CRL signature */
+ CRYPTO_REF_COUNT references;
+ int flags;
+ /*
+ * Cached copies of decoded extension values, since extensions
+ * are optional any of these can be NULL.
+ */
+ AUTHORITY_KEYID *akid;
+ ISSUING_DIST_POINT *idp;
+ /* Convenient breakdown of IDP */
+ int idp_flags;
+ int idp_reasons;
+ /* CRL and base CRL numbers for delta processing */
+ ASN1_INTEGER *crl_number;
+ ASN1_INTEGER *base_crl_number;
+ STACK_OF(GENERAL_NAMES) *issuers;
+ /* hash of CRL */
+ unsigned char sha1_hash[SHA_DIGEST_LENGTH];
+ /* alternative method to handle this CRL */
+ const X509_CRL_METHOD *meth;
+ void *meth_data;
+ CRYPTO_RWLOCK *lock;
+
+ OSSL_LIB_CTX *libctx;
+ char *propq;
+};
+
+struct x509_revoked_st {
+ ASN1_INTEGER serialNumber; /* revoked entry serial number */
+ ASN1_TIME *revocationDate; /* revocation date */
+ STACK_OF(X509_EXTENSION) *extensions; /* CRL entry extensions: optional */
+ /* decoded value of CRLissuer extension: set if indirect CRL */
+ STACK_OF(GENERAL_NAME) *issuer;
+ /* revocation reason: set to CRL_REASON_NONE if reason extension absent */
+ int reason;
+ /*
+ * CRL entries are reordered for faster lookup of serial numbers. This
+ * field contains the original load sequence for this entry.
+ */
+ int sequence;
+};
+
+/*
+ * This stuff is certificate "auxiliary info": it contains details which are
+ * useful in certificate stores and databases. When used this is tagged onto
+ * the end of the certificate itself. OpenSSL specific structure not defined
+ * in any RFC.
+ */
+
+struct x509_cert_aux_st {
+ STACK_OF(ASN1_OBJECT) *trust; /* trusted uses */
+ STACK_OF(ASN1_OBJECT) *reject; /* rejected uses */
+ ASN1_UTF8STRING *alias; /* "friendly name" */
+ ASN1_OCTET_STRING *keyid; /* key id of private key */
+ STACK_OF(X509_ALGOR) *other; /* other unspecified info */
+};
+
+struct x509_cinf_st {
+ ASN1_INTEGER *version; /* [ 0 ] default of v1 */
+ ASN1_INTEGER serialNumber;
+ X509_ALGOR signature;
+ X509_NAME *issuer;
+ X509_VAL validity;
+ X509_NAME *subject;
+ X509_PUBKEY *key;
+ ASN1_BIT_STRING *issuerUID; /* [ 1 ] optional in v2 */
+ ASN1_BIT_STRING *subjectUID; /* [ 2 ] optional in v2 */
+ STACK_OF(X509_EXTENSION) *extensions; /* [ 3 ] optional in v3 */
+ ASN1_ENCODING enc;
+};
+
+struct x509_st {
+ X509_CINF cert_info;
+ X509_ALGOR sig_alg;
+ ASN1_BIT_STRING signature;
+ X509_SIG_INFO siginf;
+ CRYPTO_REF_COUNT references;
+ CRYPTO_EX_DATA ex_data;
+ /* These contain copies of various extension values */
+ long ex_pathlen;
+ long ex_pcpathlen;
+ uint32_t ex_flags;
+ uint32_t ex_kusage;
+ uint32_t ex_xkusage;
+ uint32_t ex_nscert;
+ ASN1_OCTET_STRING *skid;
+ AUTHORITY_KEYID *akid;
+ X509_POLICY_CACHE *policy_cache;
+ STACK_OF(DIST_POINT) *crldp;
+ STACK_OF(GENERAL_NAME) *altname;
+ NAME_CONSTRAINTS *nc;
+# ifndef OPENSSL_NO_RFC3779
+ STACK_OF(IPAddressFamily) *rfc3779_addr;
+ struct ASIdentifiers_st *rfc3779_asid;
+# endif
+ unsigned char sha1_hash[SHA_DIGEST_LENGTH];
+ X509_CERT_AUX *aux;
+ CRYPTO_RWLOCK *lock;
+ volatile int ex_cached;
+
+ /* Set on live certificates for authentication purposes */
+ ASN1_OCTET_STRING *distinguishing_id;
+
+ OSSL_LIB_CTX *libctx;
+ char *propq;
+} /* X509 */ ;
+
+/*
+ * This is a used when verifying cert chains. Since the gathering of the
+ * cert chain can take some time (and have to be 'retried', this needs to be
+ * kept and passed around.
+ */
+struct x509_store_ctx_st { /* X509_STORE_CTX */
+ X509_STORE *store;
+ /* The following are set by the caller */
+ /* The cert to check */
+ X509 *cert;
+ /* chain of X509s - untrusted - passed in */
+ STACK_OF(X509) *untrusted;
+ /* set of CRLs passed in */
+ STACK_OF(X509_CRL) *crls;
+ X509_VERIFY_PARAM *param;
+ /* Other info for use with get_issuer() */
+ void *other_ctx;
+ /* Callbacks for various operations */
+ /* called to verify a certificate */
+ int (*verify) (X509_STORE_CTX *ctx);
+ /* error callback */
+ int (*verify_cb) (int ok, X509_STORE_CTX *ctx);
+ /* get issuers cert from ctx */
+ int (*get_issuer) (X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
+ /* check issued */
+ int (*check_issued) (X509_STORE_CTX *ctx, X509 *x, X509 *issuer);
+ /* Check revocation status of chain */
+ int (*check_revocation) (X509_STORE_CTX *ctx);
+ /* retrieve CRL */
+ int (*get_crl) (X509_STORE_CTX *ctx, X509_CRL **crl, X509 *x);
+ /* Check CRL validity */
+ int (*check_crl) (X509_STORE_CTX *ctx, X509_CRL *crl);
+ /* Check certificate against CRL */
+ int (*cert_crl) (X509_STORE_CTX *ctx, X509_CRL *crl, X509 *x);
+ /* Check policy status of the chain */
+ int (*check_policy) (X509_STORE_CTX *ctx);
+ STACK_OF(X509) *(*lookup_certs) (X509_STORE_CTX *ctx,
+ const X509_NAME *nm);
+ /* cannot constify 'ctx' param due to lookup_certs_sk() in x509_vfy.c */
+ STACK_OF(X509_CRL) *(*lookup_crls) (const X509_STORE_CTX *ctx,
+ const X509_NAME *nm);
+ int (*cleanup) (X509_STORE_CTX *ctx);
+ /* The following is built up */
+ /* if 0, rebuild chain */
+ int valid;
+ /* number of untrusted certs */
+ int num_untrusted;
+ /* chain of X509s - built up and trusted */
+ STACK_OF(X509) *chain;
+ /* Valid policy tree */
+ X509_POLICY_TREE *tree;
+ /* Require explicit policy value */
+ int explicit_policy;
+ /* When something goes wrong, this is why */
+ int error_depth;
+ int error;
+ X509 *current_cert;
+ /* cert currently being tested as valid issuer */
+ X509 *current_issuer;
+ /* current CRL */
+ X509_CRL *current_crl;
+ /* score of current CRL */
+ int current_crl_score;
+ /* Reason mask */
+ unsigned int current_reasons;
+ /* For CRL path validation: parent context */
+ X509_STORE_CTX *parent;
+ CRYPTO_EX_DATA ex_data;
+ SSL_DANE *dane;
+ /* signed via bare TA public key, rather than CA certificate */
+ int bare_ta_signed;
+
+ OSSL_LIB_CTX *libctx;
+ char *propq;
+};
+
+/* PKCS#8 private key info structure */
+
+struct pkcs8_priv_key_info_st {
+ ASN1_INTEGER *version;
+ X509_ALGOR *pkeyalg;
+ ASN1_OCTET_STRING *pkey;
+ STACK_OF(X509_ATTRIBUTE) *attributes;
+};
+
+struct X509_sig_st {
+ X509_ALGOR *algor;
+ ASN1_OCTET_STRING *digest;
+};
+
+struct x509_object_st {
+ /* one of the above types */
+ X509_LOOKUP_TYPE type;
+ union {
+ char *ptr;
+ X509 *x509;
+ X509_CRL *crl;
+ EVP_PKEY *pkey;
+ } data;
+};
+
+int ossl_a2i_ipadd(unsigned char *ipout, const char *ipasc);
+int ossl_x509_set1_time(ASN1_TIME **ptm, const ASN1_TIME *tm);
+int ossl_x509_print_ex_brief(BIO *bio, X509 *cert, unsigned long neg_cflags);
+int ossl_x509v3_cache_extensions(X509 *x);
+int ossl_x509_init_sig_info(X509 *x);
+
+int ossl_x509_set0_libctx(X509 *x, OSSL_LIB_CTX *libctx, const char *propq);
+int ossl_x509_crl_set0_libctx(X509_CRL *x, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int ossl_x509_req_set0_libctx(X509_REQ *x, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int ossl_asn1_item_digest_ex(const ASN1_ITEM *it, const EVP_MD *type,
+ void *data, unsigned char *md, unsigned int *len,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int ossl_x509_add_cert_new(STACK_OF(X509) **sk, X509 *cert, int flags);
+int ossl_x509_add_certs_new(STACK_OF(X509) **p_sk, STACK_OF(X509) *certs,
+ int flags);
+
+STACK_OF(X509_ATTRIBUTE) *ossl_x509at_dup(const STACK_OF(X509_ATTRIBUTE) *x);
+
+int ossl_x509_PUBKEY_get0_libctx(OSSL_LIB_CTX **plibctx, const char **ppropq,
+ const X509_PUBKEY *key);
+/* Calculate default key identifier according to RFC 5280 section 4.2.1.2 (1) */
+ASN1_OCTET_STRING *ossl_x509_pubkey_hash(X509_PUBKEY *pubkey);
+
+X509_PUBKEY *ossl_d2i_X509_PUBKEY_INTERNAL(const unsigned char **pp,
+ long len, OSSL_LIB_CTX *libctx);
+void ossl_X509_PUBKEY_INTERNAL_free(X509_PUBKEY *xpub);
+
+RSA *ossl_d2i_RSA_PSS_PUBKEY(RSA **a, const unsigned char **pp, long length);
+int ossl_i2d_RSA_PSS_PUBKEY(const RSA *a, unsigned char **pp);
+# ifndef OPENSSL_NO_DH
+DH *ossl_d2i_DH_PUBKEY(DH **a, const unsigned char **pp, long length);
+int ossl_i2d_DH_PUBKEY(const DH *a, unsigned char **pp);
+DH *ossl_d2i_DHx_PUBKEY(DH **a, const unsigned char **pp, long length);
+int ossl_i2d_DHx_PUBKEY(const DH *a, unsigned char **pp);
+# endif /* OPENSSL_NO_DH */
+# ifndef OPENSSL_NO_EC
+ECX_KEY *ossl_d2i_ED25519_PUBKEY(ECX_KEY **a,
+ const unsigned char **pp, long length);
+int ossl_i2d_ED25519_PUBKEY(const ECX_KEY *a, unsigned char **pp);
+ECX_KEY *ossl_d2i_ED448_PUBKEY(ECX_KEY **a,
+ const unsigned char **pp, long length);
+int ossl_i2d_ED448_PUBKEY(const ECX_KEY *a, unsigned char **pp);
+ECX_KEY *ossl_d2i_X25519_PUBKEY(ECX_KEY **a,
+ const unsigned char **pp, long length);
+int ossl_i2d_X25519_PUBKEY(const ECX_KEY *a, unsigned char **pp);
+ECX_KEY *ossl_d2i_X448_PUBKEY(ECX_KEY **a,
+ const unsigned char **pp, long length);
+int ossl_i2d_X448_PUBKEY(const ECX_KEY *a, unsigned char **pp);
+# endif /* OPENSSL_NO_EC */
+EVP_PKEY *ossl_d2i_PUBKEY_legacy(EVP_PKEY **a, const unsigned char **pp,
+ long length);
+
+int x509v3_add_len_value_uchar(const char *name, const unsigned char *value,
+ size_t vallen, STACK_OF(CONF_VALUE) **extlist);
+#endif /* OSSL_CRYPTO_X509_H */
diff --git a/include/crypto/x509err.h b/include/crypto/x509err.h
new file mode 100644
index 00000000..53f567d9
--- /dev/null
+++ b/include/crypto/x509err.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_X509ERR_H
+# define OSSL_CRYPTO_X509ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_X509_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/crypto/x509v3err.h b/include/crypto/x509v3err.h
new file mode 100644
index 00000000..66d3ad92
--- /dev/null
+++ b/include/crypto/x509v3err.h
@@ -0,0 +1,27 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_CRYPTO_X509V3ERR_H
+# define OSSL_CRYPTO_X509V3ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_X509V3_strings(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/httplib.h b/include/httplib.h
new file mode 100644
index 00000000..2b52f0fc
--- /dev/null
+++ b/include/httplib.h
@@ -0,0 +1,7832 @@
+//
+// httplib.h
+//
+// Copyright (c) 2021 Yuji Hirose. All rights reserved.
+// MIT License
+//
+
+#ifndef CPPHTTPLIB_HTTPLIB_H
+#define CPPHTTPLIB_HTTPLIB_H
+
+/*
+ * Configuration
+ */
+
+#ifndef CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND
+#define CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND 5
+#endif
+
+#ifndef CPPHTTPLIB_KEEPALIVE_MAX_COUNT
+#define CPPHTTPLIB_KEEPALIVE_MAX_COUNT 5
+#endif
+
+#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND
+#define CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND 300
+#endif
+
+#ifndef CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND
+#define CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND 0
+#endif
+
+#ifndef CPPHTTPLIB_READ_TIMEOUT_SECOND
+#define CPPHTTPLIB_READ_TIMEOUT_SECOND 5
+#endif
+
+#ifndef CPPHTTPLIB_READ_TIMEOUT_USECOND
+#define CPPHTTPLIB_READ_TIMEOUT_USECOND 0
+#endif
+
+#ifndef CPPHTTPLIB_WRITE_TIMEOUT_SECOND
+#define CPPHTTPLIB_WRITE_TIMEOUT_SECOND 5
+#endif
+
+#ifndef CPPHTTPLIB_WRITE_TIMEOUT_USECOND
+#define CPPHTTPLIB_WRITE_TIMEOUT_USECOND 0
+#endif
+
+#ifndef CPPHTTPLIB_IDLE_INTERVAL_SECOND
+#define CPPHTTPLIB_IDLE_INTERVAL_SECOND 0
+#endif
+
+#ifndef CPPHTTPLIB_IDLE_INTERVAL_USECOND
+#ifdef _WIN32
+#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 10000
+#else
+#define CPPHTTPLIB_IDLE_INTERVAL_USECOND 0
+#endif
+#endif
+
+#ifndef CPPHTTPLIB_REQUEST_URI_MAX_LENGTH
+#define CPPHTTPLIB_REQUEST_URI_MAX_LENGTH 8192
+#endif
+
+#ifndef CPPHTTPLIB_REDIRECT_MAX_COUNT
+#define CPPHTTPLIB_REDIRECT_MAX_COUNT 20
+#endif
+
+#ifndef CPPHTTPLIB_PAYLOAD_MAX_LENGTH
+#define CPPHTTPLIB_PAYLOAD_MAX_LENGTH ((std::numeric_limits<size_t>::max)())
+#endif
+
+#ifndef CPPHTTPLIB_TCP_NODELAY
+#define CPPHTTPLIB_TCP_NODELAY false
+#endif
+
+#ifndef CPPHTTPLIB_RECV_BUFSIZ
+#define CPPHTTPLIB_RECV_BUFSIZ size_t(4096u)
+#endif
+
+#ifndef CPPHTTPLIB_COMPRESSION_BUFSIZ
+#define CPPHTTPLIB_COMPRESSION_BUFSIZ size_t(16384u)
+#endif
+
+#ifndef CPPHTTPLIB_THREAD_POOL_COUNT
+#define CPPHTTPLIB_THREAD_POOL_COUNT \
+ ((std::max)(8u, std::thread::hardware_concurrency() > 0 \
+ ? std::thread::hardware_concurrency() - 1 \
+ : 0))
+#endif
+
+#ifndef CPPHTTPLIB_RECV_FLAGS
+#define CPPHTTPLIB_RECV_FLAGS 0
+#endif
+
+#ifndef CPPHTTPLIB_SEND_FLAGS
+#define CPPHTTPLIB_SEND_FLAGS 0
+#endif
+
+/*
+ * Headers
+ */
+
+#ifdef _WIN32
+#ifndef _CRT_SECURE_NO_WARNINGS
+#define _CRT_SECURE_NO_WARNINGS
+#endif //_CRT_SECURE_NO_WARNINGS
+
+#ifndef _CRT_NONSTDC_NO_DEPRECATE
+#define _CRT_NONSTDC_NO_DEPRECATE
+#endif //_CRT_NONSTDC_NO_DEPRECATE
+
+#if defined(_MSC_VER)
+#ifdef _WIN64
+using ssize_t = __int64;
+#else
+using ssize_t = int;
+#endif
+
+#if _MSC_VER < 1900
+#define snprintf _snprintf_s
+#endif
+#endif // _MSC_VER
+
+#ifndef S_ISREG
+#define S_ISREG(m) (((m)&S_IFREG) == S_IFREG)
+#endif // S_ISREG
+
+#ifndef S_ISDIR
+#define S_ISDIR(m) (((m)&S_IFDIR) == S_IFDIR)
+#endif // S_ISDIR
+
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif // NOMINMAX
+
+#include <io.h>
+#include <winsock2.h>
+
+#include <wincrypt.h>
+#include <ws2tcpip.h>
+
+#ifndef WSA_FLAG_NO_HANDLE_INHERIT
+#define WSA_FLAG_NO_HANDLE_INHERIT 0x80
+#endif
+
+#ifdef _MSC_VER
+#pragma comment(lib, "ws2_32.lib")
+#pragma comment(lib, "crypt32.lib")
+#pragma comment(lib, "cryptui.lib")
+#endif
+
+#ifndef strcasecmp
+#define strcasecmp _stricmp
+#endif // strcasecmp
+
+using socket_t = SOCKET;
+#ifdef CPPHTTPLIB_USE_POLL
+#define poll(fds, nfds, timeout) WSAPoll(fds, nfds, timeout)
+#endif
+
+#else // not _WIN32
+
+#include <arpa/inet.h>
+#include <cstring>
+#include <ifaddrs.h>
+#include <netdb.h>
+#include <netinet/in.h>
+#ifdef __linux__
+#include <resolv.h>
+#endif
+#include <netinet/tcp.h>
+#ifdef CPPHTTPLIB_USE_POLL
+#include <poll.h>
+#endif
+#include <csignal>
+#include <pthread.h>
+#include <sys/select.h>
+#include <sys/socket.h>
+#include <unistd.h>
+
+using socket_t = int;
+#define INVALID_SOCKET (-1)
+#endif //_WIN32
+
+#include <algorithm>
+#include <array>
+#include <atomic>
+#include <cassert>
+#include <cctype>
+#include <climits>
+#include <condition_variable>
+#include <errno.h>
+#include <fcntl.h>
+#include <fstream>
+#include <functional>
+#include <iomanip>
+#include <iostream>
+#include <list>
+#include <map>
+#include <memory>
+#include <mutex>
+#include <random>
+#include <regex>
+#include <set>
+#include <sstream>
+#include <string>
+#include <sys/stat.h>
+#include <thread>
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+#include <openssl/err.h>
+#include <openssl/md5.h>
+#include <openssl/ssl.h>
+#include <openssl/x509v3.h>
+
+#if defined(_WIN32) && defined(OPENSSL_USE_APPLINK)
+#include <openssl/applink.c>
+#endif
+
+#include <iostream>
+#include <sstream>
+
+#if OPENSSL_VERSION_NUMBER < 0x1010100fL
+#error Sorry, OpenSSL versions prior to 1.1.1 are not supported
+#endif
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+#include <openssl/crypto.h>
+inline const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *asn1) {
+ return M_ASN1_STRING_data(asn1);
+}
+#endif
+#endif
+
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+#include <zlib.h>
+#endif
+
+#ifdef CPPHTTPLIB_BROTLI_SUPPORT
+#include <brotli/decode.h>
+#include <brotli/encode.h>
+#endif
+
+/*
+ * Declaration
+ */
+namespace httplib {
+
+namespace detail {
+
+/*
+ * Backport std::make_unique from C++14.
+ *
+ * NOTE: This code came up with the following stackoverflow post:
+ * https://stackoverflow.com/questions/10149840/c-arrays-and-make-unique
+ *
+ */
+
+template <class T, class... Args>
+typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
+make_unique(Args &&... args) {
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+template <class T>
+typename std::enable_if<std::is_array<T>::value, std::unique_ptr<T>>::type
+make_unique(std::size_t n) {
+ typedef typename std::remove_extent<T>::type RT;
+ return std::unique_ptr<T>(new RT[n]);
+}
+
+struct ci {
+ bool operator()(const std::string &s1, const std::string &s2) const {
+ return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(),
+ s2.end(),
+ [](unsigned char c1, unsigned char c2) {
+ return ::tolower(c1) < ::tolower(c2);
+ });
+ }
+};
+
+} // namespace detail
+
+using Headers = std::multimap<std::string, std::string, detail::ci>;
+
+using Params = std::multimap<std::string, std::string>;
+using Match = std::smatch;
+
+using Progress = std::function<bool(uint64_t current, uint64_t total)>;
+
+struct Response;
+using ResponseHandler = std::function<bool(const Response &response)>;
+
+struct MultipartFormData {
+ std::string name;
+ std::string content;
+ std::string filename;
+ std::string content_type;
+};
+using MultipartFormDataItems = std::vector<MultipartFormData>;
+using MultipartFormDataMap = std::multimap<std::string, MultipartFormData>;
+
+class DataSink {
+public:
+ DataSink() : os(&sb_), sb_(*this) {}
+
+ DataSink(const DataSink &) = delete;
+ DataSink &operator=(const DataSink &) = delete;
+ DataSink(DataSink &&) = delete;
+ DataSink &operator=(DataSink &&) = delete;
+
+ std::function<bool(const char *data, size_t data_len)> write;
+ std::function<void()> done;
+ std::function<bool()> is_writable;
+ std::ostream os;
+
+private:
+ class data_sink_streambuf : public std::streambuf {
+ public:
+ explicit data_sink_streambuf(DataSink &sink) : sink_(sink) {}
+
+ protected:
+ std::streamsize xsputn(const char *s, std::streamsize n) {
+ sink_.write(s, static_cast<size_t>(n));
+ return n;
+ }
+
+ private:
+ DataSink &sink_;
+ };
+
+ data_sink_streambuf sb_;
+};
+
+using ContentProvider =
+ std::function<bool(size_t offset, size_t length, DataSink &sink)>;
+
+using ContentProviderWithoutLength =
+ std::function<bool(size_t offset, DataSink &sink)>;
+
+using ContentProviderResourceReleaser = std::function<void(bool success)>;
+
+using ContentReceiverWithProgress =
+ std::function<bool(const char *data, size_t data_length, uint64_t offset,
+ uint64_t total_length)>;
+
+using ContentReceiver =
+ std::function<bool(const char *data, size_t data_length)>;
+
+using MultipartContentHeader =
+ std::function<bool(const MultipartFormData &file)>;
+
+class ContentReader {
+public:
+ using Reader = std::function<bool(ContentReceiver receiver)>;
+ using MultipartReader = std::function<bool(MultipartContentHeader header,
+ ContentReceiver receiver)>;
+
+ ContentReader(Reader reader, MultipartReader multipart_reader)
+ : reader_(std::move(reader)),
+ multipart_reader_(std::move(multipart_reader)) {}
+
+ bool operator()(MultipartContentHeader header,
+ ContentReceiver receiver) const {
+ return multipart_reader_(std::move(header), std::move(receiver));
+ }
+
+ bool operator()(ContentReceiver receiver) const {
+ return reader_(std::move(receiver));
+ }
+
+ Reader reader_;
+ MultipartReader multipart_reader_;
+};
+
+using Range = std::pair<ssize_t, ssize_t>;
+using Ranges = std::vector<Range>;
+
+struct Request {
+ std::string method;
+ std::string path;
+ Headers headers;
+ std::string body;
+
+ std::string remote_addr;
+ int remote_port = -1;
+
+ // for server
+ std::string version;
+ std::string target;
+ Params params;
+ MultipartFormDataMap files;
+ Ranges ranges;
+ Match matches;
+
+ // for client
+ ResponseHandler response_handler;
+ ContentReceiverWithProgress content_receiver;
+ Progress progress;
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ const SSL *ssl = nullptr;
+#endif
+
+ bool has_header(const char *key) const;
+ std::string get_header_value(const char *key, size_t id = 0) const;
+ template <typename T>
+ T get_header_value(const char *key, size_t id = 0) const;
+ size_t get_header_value_count(const char *key) const;
+ void set_header(const char *key, const char *val);
+ void set_header(const char *key, const std::string &val);
+
+ bool has_param(const char *key) const;
+ std::string get_param_value(const char *key, size_t id = 0) const;
+ size_t get_param_value_count(const char *key) const;
+
+ bool is_multipart_form_data() const;
+
+ bool has_file(const char *key) const;
+ MultipartFormData get_file_value(const char *key) const;
+
+ // private members...
+ size_t redirect_count_ = CPPHTTPLIB_REDIRECT_MAX_COUNT;
+ size_t content_length_ = 0;
+ ContentProvider content_provider_;
+ bool is_chunked_content_provider_ = false;
+ size_t authorization_count_ = 0;
+};
+
+struct Response {
+ std::string version;
+ int status = -1;
+ std::string reason;
+ Headers headers;
+ std::string body;
+ std::string location; // Redirect location
+
+ bool has_header(const char *key) const;
+ std::string get_header_value(const char *key, size_t id = 0) const;
+ template <typename T>
+ T get_header_value(const char *key, size_t id = 0) const;
+ size_t get_header_value_count(const char *key) const;
+ void set_header(const char *key, const char *val);
+ void set_header(const char *key, const std::string &val);
+
+ void set_redirect(const char *url, int status = 302);
+ void set_redirect(const std::string &url, int status = 302);
+ void set_content(const char *s, size_t n, const char *content_type);
+ void set_content(const std::string &s, const char *content_type);
+
+ void set_content_provider(
+ size_t length, const char *content_type, ContentProvider provider,
+ ContentProviderResourceReleaser resource_releaser = nullptr);
+
+ void set_content_provider(
+ const char *content_type, ContentProviderWithoutLength provider,
+ ContentProviderResourceReleaser resource_releaser = nullptr);
+
+ void set_chunked_content_provider(
+ const char *content_type, ContentProviderWithoutLength provider,
+ ContentProviderResourceReleaser resource_releaser = nullptr);
+
+ Response() = default;
+ Response(const Response &) = default;
+ Response &operator=(const Response &) = default;
+ Response(Response &&) = default;
+ Response &operator=(Response &&) = default;
+ ~Response() {
+ if (content_provider_resource_releaser_) {
+ content_provider_resource_releaser_(content_provider_success_);
+ }
+ }
+
+ // private members...
+ size_t content_length_ = 0;
+ ContentProvider content_provider_;
+ ContentProviderResourceReleaser content_provider_resource_releaser_;
+ bool is_chunked_content_provider_ = false;
+ bool content_provider_success_ = false;
+};
+
+class Stream {
+public:
+ virtual ~Stream() = default;
+
+ virtual bool is_readable() const = 0;
+ virtual bool is_writable() const = 0;
+
+ virtual ssize_t read(char *ptr, size_t size) = 0;
+ virtual ssize_t write(const char *ptr, size_t size) = 0;
+ virtual void get_remote_ip_and_port(std::string &ip, int &port) const = 0;
+ virtual socket_t socket() const = 0;
+
+ template <typename... Args>
+ ssize_t write_format(const char *fmt, const Args &... args);
+ ssize_t write(const char *ptr);
+ ssize_t write(const std::string &s);
+};
+
+class TaskQueue {
+public:
+ TaskQueue() = default;
+ virtual ~TaskQueue() = default;
+
+ virtual void enqueue(std::function<void()> fn) = 0;
+ virtual void shutdown() = 0;
+
+ virtual void on_idle(){};
+};
+
+class ThreadPool : public TaskQueue {
+public:
+ explicit ThreadPool(size_t n) : shutdown_(false) {
+ while (n) {
+ threads_.emplace_back(worker(*this));
+ n--;
+ }
+ }
+
+ ThreadPool(const ThreadPool &) = delete;
+ ~ThreadPool() override = default;
+
+ void enqueue(std::function<void()> fn) override {
+ std::unique_lock<std::mutex> lock(mutex_);
+ jobs_.push_back(std::move(fn));
+ cond_.notify_one();
+ }
+
+ void shutdown() override {
+ // Stop all worker threads...
+ {
+ std::unique_lock<std::mutex> lock(mutex_);
+ shutdown_ = true;
+ }
+
+ cond_.notify_all();
+
+ // Join...
+ for (auto &t : threads_) {
+ t.join();
+ }
+ }
+
+private:
+ struct worker {
+ explicit worker(ThreadPool &pool) : pool_(pool) {}
+
+ void operator()() {
+ for (;;) {
+ std::function<void()> fn;
+ {
+ std::unique_lock<std::mutex> lock(pool_.mutex_);
+
+ pool_.cond_.wait(
+ lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; });
+
+ if (pool_.shutdown_ && pool_.jobs_.empty()) { break; }
+
+ fn = pool_.jobs_.front();
+ pool_.jobs_.pop_front();
+ }
+
+ assert(true == static_cast<bool>(fn));
+ fn();
+ }
+ }
+
+ ThreadPool &pool_;
+ };
+ friend struct worker;
+
+ std::vector<std::thread> threads_;
+ std::list<std::function<void()>> jobs_;
+
+ bool shutdown_;
+
+ std::condition_variable cond_;
+ std::mutex mutex_;
+};
+
+using Logger = std::function<void(const Request &, const Response &)>;
+
+using SocketOptions = std::function<void(socket_t sock)>;
+
+inline void default_socket_options(socket_t sock) {
+ int yes = 1;
+#ifdef _WIN32
+ setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&yes),
+ sizeof(yes));
+ setsockopt(sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE,
+ reinterpret_cast<char *>(&yes), sizeof(yes));
+#else
+#ifdef SO_REUSEPORT
+ setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, reinterpret_cast<void *>(&yes),
+ sizeof(yes));
+#else
+ setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<void *>(&yes),
+ sizeof(yes));
+#endif
+#endif
+}
+
+class Server {
+public:
+ using Handler = std::function<void(const Request &, Response &)>;
+
+ using ExceptionHandler =
+ std::function<void(const Request &, Response &, std::exception &e)>;
+
+ enum class HandlerResponse {
+ Handled,
+ Unhandled,
+ };
+ using HandlerWithResponse =
+ std::function<HandlerResponse(const Request &, Response &)>;
+
+ using HandlerWithContentReader = std::function<void(
+ const Request &, Response &, const ContentReader &content_reader)>;
+
+ using Expect100ContinueHandler =
+ std::function<int(const Request &, Response &)>;
+
+ Server();
+
+ virtual ~Server();
+
+ virtual bool is_valid() const;
+
+ Server &Get(const std::string &pattern, Handler handler);
+ Server &Post(const std::string &pattern, Handler handler);
+ Server &Post(const std::string &pattern, HandlerWithContentReader handler);
+ Server &Put(const std::string &pattern, Handler handler);
+ Server &Put(const std::string &pattern, HandlerWithContentReader handler);
+ Server &Patch(const std::string &pattern, Handler handler);
+ Server &Patch(const std::string &pattern, HandlerWithContentReader handler);
+ Server &Delete(const std::string &pattern, Handler handler);
+ Server &Delete(const std::string &pattern, HandlerWithContentReader handler);
+ Server &Options(const std::string &pattern, Handler handler);
+
+ bool set_base_dir(const std::string &dir,
+ const std::string &mount_point = nullptr);
+ bool set_mount_point(const std::string &mount_point, const std::string &dir,
+ Headers headers = Headers());
+ bool remove_mount_point(const std::string &mount_point);
+ Server &set_file_extension_and_mimetype_mapping(const char *ext,
+ const char *mime);
+ Server &set_file_request_handler(Handler handler);
+
+ Server &set_error_handler(HandlerWithResponse handler);
+ Server &set_error_handler(Handler handler);
+ Server &set_exception_handler(ExceptionHandler handler);
+ Server &set_pre_routing_handler(HandlerWithResponse handler);
+ Server &set_post_routing_handler(Handler handler);
+
+ Server &set_expect_100_continue_handler(Expect100ContinueHandler handler);
+ Server &set_logger(Logger logger);
+
+ Server &set_address_family(int family);
+ Server &set_tcp_nodelay(bool on);
+ Server &set_socket_options(SocketOptions socket_options);
+
+ Server &set_default_headers(Headers headers);
+
+ Server &set_keep_alive_max_count(size_t count);
+ Server &set_keep_alive_timeout(time_t sec);
+
+ Server &set_read_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ Server &set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ Server &set_write_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ Server &set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ Server &set_idle_interval(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ Server &set_idle_interval(const std::chrono::duration<Rep, Period> &duration);
+
+ Server &set_payload_max_length(size_t length);
+
+ bool bind_to_port(const char *host, int port, int socket_flags = 0);
+ int bind_to_any_port(const char *host, int socket_flags = 0);
+ bool listen_after_bind();
+
+ bool listen(const char *host, int port, int socket_flags = 0);
+
+ bool is_running() const;
+ void stop();
+
+ std::function<TaskQueue *(void)> new_task_queue;
+
+protected:
+ bool process_request(Stream &strm, bool close_connection,
+ bool &connection_closed,
+ const std::function<void(Request &)> &setup_request);
+
+ std::atomic<socket_t> svr_sock_;
+ size_t keep_alive_max_count_ = CPPHTTPLIB_KEEPALIVE_MAX_COUNT;
+ time_t keep_alive_timeout_sec_ = CPPHTTPLIB_KEEPALIVE_TIMEOUT_SECOND;
+ time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
+ time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
+ time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
+ time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
+ time_t idle_interval_sec_ = CPPHTTPLIB_IDLE_INTERVAL_SECOND;
+ time_t idle_interval_usec_ = CPPHTTPLIB_IDLE_INTERVAL_USECOND;
+ size_t payload_max_length_ = CPPHTTPLIB_PAYLOAD_MAX_LENGTH;
+
+private:
+ using Handlers = std::vector<std::pair<std::regex, Handler>>;
+ using HandlersForContentReader =
+ std::vector<std::pair<std::regex, HandlerWithContentReader>>;
+
+ socket_t create_server_socket(const char *host, int port, int socket_flags,
+ SocketOptions socket_options) const;
+ int bind_internal(const char *host, int port, int socket_flags);
+ bool listen_internal();
+
+ bool routing(Request &req, Response &res, Stream &strm);
+ bool handle_file_request(const Request &req, Response &res,
+ bool head = false);
+ bool dispatch_request(Request &req, Response &res, const Handlers &handlers);
+ bool
+ dispatch_request_for_content_reader(Request &req, Response &res,
+ ContentReader content_reader,
+ const HandlersForContentReader &handlers);
+
+ bool parse_request_line(const char *s, Request &req);
+ void apply_ranges(const Request &req, Response &res,
+ std::string &content_type, std::string &boundary);
+ bool write_response(Stream &strm, bool close_connection, const Request &req,
+ Response &res);
+ bool write_response_with_content(Stream &strm, bool close_connection,
+ const Request &req, Response &res);
+ bool write_response_core(Stream &strm, bool close_connection,
+ const Request &req, Response &res,
+ bool need_apply_ranges);
+ bool write_content_with_provider(Stream &strm, const Request &req,
+ Response &res, const std::string &boundary,
+ const std::string &content_type);
+ bool read_content(Stream &strm, Request &req, Response &res);
+ bool
+ read_content_with_content_receiver(Stream &strm, Request &req, Response &res,
+ ContentReceiver receiver,
+ MultipartContentHeader multipart_header,
+ ContentReceiver multipart_receiver);
+ bool read_content_core(Stream &strm, Request &req, Response &res,
+ ContentReceiver receiver,
+ MultipartContentHeader mulitpart_header,
+ ContentReceiver multipart_receiver);
+
+ virtual bool process_and_close_socket(socket_t sock);
+
+ struct MountPointEntry {
+ std::string mount_point;
+ std::string base_dir;
+ Headers headers;
+ };
+ std::vector<MountPointEntry> base_dirs_;
+
+ std::atomic<bool> is_running_;
+ std::map<std::string, std::string> file_extension_and_mimetype_map_;
+ Handler file_request_handler_;
+ Handlers get_handlers_;
+ Handlers post_handlers_;
+ HandlersForContentReader post_handlers_for_content_reader_;
+ Handlers put_handlers_;
+ HandlersForContentReader put_handlers_for_content_reader_;
+ Handlers patch_handlers_;
+ HandlersForContentReader patch_handlers_for_content_reader_;
+ Handlers delete_handlers_;
+ HandlersForContentReader delete_handlers_for_content_reader_;
+ Handlers options_handlers_;
+ HandlerWithResponse error_handler_;
+ ExceptionHandler exception_handler_;
+ HandlerWithResponse pre_routing_handler_;
+ Handler post_routing_handler_;
+ Logger logger_;
+ Expect100ContinueHandler expect_100_continue_handler_;
+
+ int address_family_ = AF_UNSPEC;
+ bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
+ SocketOptions socket_options_ = default_socket_options;
+
+ Headers default_headers_;
+};
+
+enum class Error {
+ Success = 0,
+ Unknown,
+ Connection,
+ BindIPAddress,
+ Read,
+ Write,
+ ExceedRedirectCount,
+ Canceled,
+ SSLConnection,
+ SSLLoadingCerts,
+ SSLServerVerification,
+ UnsupportedMultipartBoundaryChars,
+ Compression,
+};
+
+inline std::string to_string(const Error error) {
+ switch (error) {
+ case Error::Success: return "Success";
+ case Error::Connection: return "Connection";
+ case Error::BindIPAddress: return "BindIPAddress";
+ case Error::Read: return "Read";
+ case Error::Write: return "Write";
+ case Error::ExceedRedirectCount: return "ExceedRedirectCount";
+ case Error::Canceled: return "Canceled";
+ case Error::SSLConnection: return "SSLConnection";
+ case Error::SSLLoadingCerts: return "SSLLoadingCerts";
+ case Error::SSLServerVerification: return "SSLServerVerification";
+ case Error::UnsupportedMultipartBoundaryChars:
+ return "UnsupportedMultipartBoundaryChars";
+ case Error::Compression: return "Compression";
+ case Error::Unknown: return "Unknown";
+ default: break;
+ }
+
+ return "Invalid";
+}
+
+inline std::ostream &operator<<(std::ostream &os, const Error &obj) {
+ os << to_string(obj);
+ os << " (" << static_cast<std::underlying_type<Error>::type>(obj) << ')';
+ return os;
+}
+
+class Result {
+public:
+ Result(std::unique_ptr<Response> &&res, Error err,
+ Headers &&request_headers = Headers{})
+ : res_(std::move(res)), err_(err),
+ request_headers_(std::move(request_headers)) {}
+ // Response
+ operator bool() const { return res_ != nullptr; }
+ bool operator==(std::nullptr_t) const { return res_ == nullptr; }
+ bool operator!=(std::nullptr_t) const { return res_ != nullptr; }
+ const Response &value() const { return *res_; }
+ Response &value() { return *res_; }
+ const Response &operator*() const { return *res_; }
+ Response &operator*() { return *res_; }
+ const Response *operator->() const { return res_.get(); }
+ Response *operator->() { return res_.get(); }
+
+ // Error
+ Error error() const { return err_; }
+
+ // Request Headers
+ bool has_request_header(const char *key) const;
+ std::string get_request_header_value(const char *key, size_t id = 0) const;
+ template <typename T>
+ T get_request_header_value(const char *key, size_t id = 0) const;
+ size_t get_request_header_value_count(const char *key) const;
+
+private:
+ std::unique_ptr<Response> res_;
+ Error err_;
+ Headers request_headers_;
+};
+
+class ClientImpl {
+public:
+ explicit ClientImpl(const std::string &host);
+
+ explicit ClientImpl(const std::string &host, int port);
+
+ explicit ClientImpl(const std::string &host, int port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path);
+
+ virtual ~ClientImpl();
+
+ virtual bool is_valid() const;
+
+ Result Get(const char *path);
+ Result Get(const char *path, const Headers &headers);
+ Result Get(const char *path, Progress progress);
+ Result Get(const char *path, const Headers &headers, Progress progress);
+ Result Get(const char *path, ContentReceiver content_receiver);
+ Result Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver);
+ Result Get(const char *path, ContentReceiver content_receiver,
+ Progress progress);
+ Result Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver, Progress progress);
+ Result Get(const char *path, ResponseHandler response_handler,
+ ContentReceiver content_receiver);
+ Result Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver);
+ Result Get(const char *path, ResponseHandler response_handler,
+ ContentReceiver content_receiver, Progress progress);
+ Result Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler, ContentReceiver content_receiver,
+ Progress progress);
+
+ Result Get(const char *path, const Params &params, const Headers &headers,
+ Progress progress = nullptr);
+ Result Get(const char *path, const Params &params, const Headers &headers,
+ ContentReceiver content_receiver, Progress progress = nullptr);
+ Result Get(const char *path, const Params &params, const Headers &headers,
+ ResponseHandler response_handler, ContentReceiver content_receiver,
+ Progress progress = nullptr);
+
+ Result Head(const char *path);
+ Result Head(const char *path, const Headers &headers);
+
+ Result Post(const char *path);
+ Result Post(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Post(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Post(const char *path, const std::string &body,
+ const char *content_type);
+ Result Post(const char *path, const Headers &headers, const std::string &body,
+ const char *content_type);
+ Result Post(const char *path, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Post(const char *path, ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Post(const char *path, const Headers &headers, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Post(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Post(const char *path, const Params &params);
+ Result Post(const char *path, const Headers &headers, const Params &params);
+ Result Post(const char *path, const MultipartFormDataItems &items);
+ Result Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items);
+ Result Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items, const std::string &boundary);
+
+ Result Put(const char *path);
+ Result Put(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Put(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Put(const char *path, const std::string &body,
+ const char *content_type);
+ Result Put(const char *path, const Headers &headers, const std::string &body,
+ const char *content_type);
+ Result Put(const char *path, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Put(const char *path, ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Put(const char *path, const Headers &headers, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Put(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Put(const char *path, const Params &params);
+ Result Put(const char *path, const Headers &headers, const Params &params);
+
+ Result Patch(const char *path);
+ Result Patch(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Patch(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Patch(const char *path, const std::string &body,
+ const char *content_type);
+ Result Patch(const char *path, const Headers &headers,
+ const std::string &body, const char *content_type);
+ Result Patch(const char *path, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Patch(const char *path, ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Patch(const char *path, const Headers &headers, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Patch(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type);
+
+ Result Delete(const char *path);
+ Result Delete(const char *path, const Headers &headers);
+ Result Delete(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Delete(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Delete(const char *path, const std::string &body,
+ const char *content_type);
+ Result Delete(const char *path, const Headers &headers,
+ const std::string &body, const char *content_type);
+
+ Result Options(const char *path);
+ Result Options(const char *path, const Headers &headers);
+
+ bool send(Request &req, Response &res, Error &error);
+ Result send(const Request &req);
+
+ size_t is_socket_open() const;
+
+ void stop();
+
+ void set_default_headers(Headers headers);
+
+ void set_address_family(int family);
+ void set_tcp_nodelay(bool on);
+ void set_socket_options(SocketOptions socket_options);
+
+ void set_connection_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ void
+ set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ void set_read_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ void set_write_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ void set_basic_auth(const char *username, const char *password);
+ void set_bearer_token_auth(const char *token);
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void set_digest_auth(const char *username, const char *password);
+#endif
+
+ void set_keep_alive(bool on);
+ void set_follow_location(bool on);
+
+ void set_url_encode(bool on);
+
+ void set_compress(bool on);
+
+ void set_decompress(bool on);
+
+ void set_interface(const char *intf);
+
+ void set_proxy(const char *host, int port);
+ void set_proxy_basic_auth(const char *username, const char *password);
+ void set_proxy_bearer_token_auth(const char *token);
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void set_proxy_digest_auth(const char *username, const char *password);
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void set_ca_cert_path(const char *ca_cert_file_path,
+ const char *ca_cert_dir_path = nullptr);
+ void set_ca_cert_store(X509_STORE *ca_cert_store);
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void enable_server_certificate_verification(bool enabled);
+#endif
+
+ void set_logger(Logger logger);
+
+protected:
+ struct Socket {
+ socket_t sock = INVALID_SOCKET;
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ SSL *ssl = nullptr;
+#endif
+
+ bool is_open() const { return sock != INVALID_SOCKET; }
+ };
+
+ Result send_(Request &&req);
+
+ virtual bool create_and_connect_socket(Socket &socket, Error &error);
+
+ // All of:
+ // shutdown_ssl
+ // shutdown_socket
+ // close_socket
+ // should ONLY be called when socket_mutex_ is locked.
+ // Also, shutdown_ssl and close_socket should also NOT be called concurrently
+ // with a DIFFERENT thread sending requests using that socket.
+ virtual void shutdown_ssl(Socket &socket, bool shutdown_gracefully);
+ void shutdown_socket(Socket &socket);
+ void close_socket(Socket &socket);
+
+ bool process_request(Stream &strm, Request &req, Response &res,
+ bool close_connection, Error &error);
+
+ bool write_content_with_provider(Stream &strm, const Request &req,
+ Error &error);
+
+ void copy_settings(const ClientImpl &rhs);
+
+ // Socket endoint information
+ const std::string host_;
+ const int port_;
+ const std::string host_and_port_;
+
+ // Current open socket
+ Socket socket_;
+ mutable std::mutex socket_mutex_;
+ std::recursive_mutex request_mutex_;
+
+ // These are all protected under socket_mutex
+ size_t socket_requests_in_flight_ = 0;
+ std::thread::id socket_requests_are_from_thread_ = std::thread::id();
+ bool socket_should_be_closed_when_request_is_done_ = false;
+
+ // Default headers
+ Headers default_headers_;
+
+ // Settings
+ std::string client_cert_path_;
+ std::string client_key_path_;
+
+ time_t connection_timeout_sec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_SECOND;
+ time_t connection_timeout_usec_ = CPPHTTPLIB_CONNECTION_TIMEOUT_USECOND;
+ time_t read_timeout_sec_ = CPPHTTPLIB_READ_TIMEOUT_SECOND;
+ time_t read_timeout_usec_ = CPPHTTPLIB_READ_TIMEOUT_USECOND;
+ time_t write_timeout_sec_ = CPPHTTPLIB_WRITE_TIMEOUT_SECOND;
+ time_t write_timeout_usec_ = CPPHTTPLIB_WRITE_TIMEOUT_USECOND;
+
+ std::string basic_auth_username_;
+ std::string basic_auth_password_;
+ std::string bearer_token_auth_token_;
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ std::string digest_auth_username_;
+ std::string digest_auth_password_;
+#endif
+
+ bool keep_alive_ = false;
+ bool follow_location_ = false;
+
+ bool url_encode_ = true;
+
+ int address_family_ = AF_UNSPEC;
+ bool tcp_nodelay_ = CPPHTTPLIB_TCP_NODELAY;
+ SocketOptions socket_options_ = nullptr;
+
+ bool compress_ = false;
+ bool decompress_ = true;
+
+ std::string interface_;
+
+ std::string proxy_host_;
+ int proxy_port_ = -1;
+
+ std::string proxy_basic_auth_username_;
+ std::string proxy_basic_auth_password_;
+ std::string proxy_bearer_token_auth_token_;
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ std::string proxy_digest_auth_username_;
+ std::string proxy_digest_auth_password_;
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ std::string ca_cert_file_path_;
+ std::string ca_cert_dir_path_;
+
+ X509_STORE *ca_cert_store_ = nullptr;
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ bool server_certificate_verification_ = true;
+#endif
+
+ Logger logger_;
+
+private:
+ socket_t create_client_socket(Error &error) const;
+ bool read_response_line(Stream &strm, const Request &req, Response &res);
+ bool write_request(Stream &strm, Request &req, bool close_connection,
+ Error &error);
+ bool redirect(Request &req, Response &res, Error &error);
+ bool handle_request(Stream &strm, Request &req, Response &res,
+ bool close_connection, Error &error);
+ std::unique_ptr<Response> send_with_content_provider(
+ Request &req,
+ // const char *method, const char *path, const Headers &headers,
+ const char *body, size_t content_length, ContentProvider content_provider,
+ ContentProviderWithoutLength content_provider_without_length,
+ const char *content_type, Error &error);
+ Result send_with_content_provider(
+ const char *method, const char *path, const Headers &headers,
+ const char *body, size_t content_length, ContentProvider content_provider,
+ ContentProviderWithoutLength content_provider_without_length,
+ const char *content_type);
+
+ std::string adjust_host_string(const std::string &host) const;
+
+ virtual bool process_socket(const Socket &socket,
+ std::function<bool(Stream &strm)> callback);
+ virtual bool is_ssl() const;
+};
+
+class Client {
+public:
+ // Universal interface
+ explicit Client(const std::string &scheme_host_port);
+
+ explicit Client(const std::string &scheme_host_port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path);
+
+ // HTTP only interface
+ explicit Client(const std::string &host, int port);
+
+ explicit Client(const std::string &host, int port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path);
+
+ ~Client();
+
+ bool is_valid() const;
+
+ Result Get(const char *path);
+ Result Get(const char *path, const Headers &headers);
+ Result Get(const char *path, Progress progress);
+ Result Get(const char *path, const Headers &headers, Progress progress);
+ Result Get(const char *path, ContentReceiver content_receiver);
+ Result Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver);
+ Result Get(const char *path, ContentReceiver content_receiver,
+ Progress progress);
+ Result Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver, Progress progress);
+ Result Get(const char *path, ResponseHandler response_handler,
+ ContentReceiver content_receiver);
+ Result Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver);
+ Result Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler, ContentReceiver content_receiver,
+ Progress progress);
+ Result Get(const char *path, ResponseHandler response_handler,
+ ContentReceiver content_receiver, Progress progress);
+
+ Result Get(const char *path, const Params &params, const Headers &headers,
+ Progress progress = nullptr);
+ Result Get(const char *path, const Params &params, const Headers &headers,
+ ContentReceiver content_receiver, Progress progress = nullptr);
+ Result Get(const char *path, const Params &params, const Headers &headers,
+ ResponseHandler response_handler, ContentReceiver content_receiver,
+ Progress progress = nullptr);
+
+ Result Head(const char *path);
+ Result Head(const char *path, const Headers &headers);
+
+ Result Post(const char *path);
+ Result Post(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Post(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Post(const char *path, const std::string &body,
+ const char *content_type);
+ Result Post(const char *path, const Headers &headers, const std::string &body,
+ const char *content_type);
+ Result Post(const char *path, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Post(const char *path, ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Post(const char *path, const Headers &headers, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Post(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Post(const char *path, const Params &params);
+ Result Post(const char *path, const Headers &headers, const Params &params);
+ Result Post(const char *path, const MultipartFormDataItems &items);
+ Result Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items);
+ Result Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items, const std::string &boundary);
+ Result Put(const char *path);
+ Result Put(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Put(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Put(const char *path, const std::string &body,
+ const char *content_type);
+ Result Put(const char *path, const Headers &headers, const std::string &body,
+ const char *content_type);
+ Result Put(const char *path, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Put(const char *path, ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Put(const char *path, const Headers &headers, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Put(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Put(const char *path, const Params &params);
+ Result Put(const char *path, const Headers &headers, const Params &params);
+ Result Patch(const char *path);
+ Result Patch(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Patch(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Patch(const char *path, const std::string &body,
+ const char *content_type);
+ Result Patch(const char *path, const Headers &headers,
+ const std::string &body, const char *content_type);
+ Result Patch(const char *path, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Patch(const char *path, ContentProviderWithoutLength content_provider,
+ const char *content_type);
+ Result Patch(const char *path, const Headers &headers, size_t content_length,
+ ContentProvider content_provider, const char *content_type);
+ Result Patch(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type);
+
+ Result Delete(const char *path);
+ Result Delete(const char *path, const Headers &headers);
+ Result Delete(const char *path, const char *body, size_t content_length,
+ const char *content_type);
+ Result Delete(const char *path, const Headers &headers, const char *body,
+ size_t content_length, const char *content_type);
+ Result Delete(const char *path, const std::string &body,
+ const char *content_type);
+ Result Delete(const char *path, const Headers &headers,
+ const std::string &body, const char *content_type);
+
+ Result Options(const char *path);
+ Result Options(const char *path, const Headers &headers);
+
+ bool send(Request &req, Response &res, Error &error);
+ Result send(const Request &req);
+
+ size_t is_socket_open() const;
+
+ void stop();
+
+ void set_default_headers(Headers headers);
+
+ void set_address_family(int family);
+ void set_tcp_nodelay(bool on);
+ void set_socket_options(SocketOptions socket_options);
+
+ void set_connection_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ void
+ set_connection_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ void set_read_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ void set_read_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ void set_write_timeout(time_t sec, time_t usec = 0);
+ template <class Rep, class Period>
+ void set_write_timeout(const std::chrono::duration<Rep, Period> &duration);
+
+ void set_basic_auth(const char *username, const char *password);
+ void set_bearer_token_auth(const char *token);
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void set_digest_auth(const char *username, const char *password);
+#endif
+
+ void set_keep_alive(bool on);
+ void set_follow_location(bool on);
+
+ void set_url_encode(bool on);
+
+ void set_compress(bool on);
+
+ void set_decompress(bool on);
+
+ void set_interface(const char *intf);
+
+ void set_proxy(const char *host, int port);
+ void set_proxy_basic_auth(const char *username, const char *password);
+ void set_proxy_bearer_token_auth(const char *token);
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void set_proxy_digest_auth(const char *username, const char *password);
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void enable_server_certificate_verification(bool enabled);
+#endif
+
+ void set_logger(Logger logger);
+
+ // SSL
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ void set_ca_cert_path(const char *ca_cert_file_path,
+ const char *ca_cert_dir_path = nullptr);
+
+ void set_ca_cert_store(X509_STORE *ca_cert_store);
+
+ long get_openssl_verify_result() const;
+
+ SSL_CTX *ssl_context() const;
+#endif
+
+private:
+ std::unique_ptr<ClientImpl> cli_;
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ bool is_ssl_ = false;
+#endif
+};
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+class SSLServer : public Server {
+public:
+ SSLServer(const char *cert_path, const char *private_key_path,
+ const char *client_ca_cert_file_path = nullptr,
+ const char *client_ca_cert_dir_path = nullptr);
+
+ SSLServer(X509 *cert, EVP_PKEY *private_key,
+ X509_STORE *client_ca_cert_store = nullptr);
+
+ ~SSLServer() override;
+
+ bool is_valid() const override;
+
+private:
+ bool process_and_close_socket(socket_t sock) override;
+
+ SSL_CTX *ctx_;
+ std::mutex ctx_mutex_;
+};
+
+class SSLClient : public ClientImpl {
+public:
+ explicit SSLClient(const std::string &host);
+
+ explicit SSLClient(const std::string &host, int port);
+
+ explicit SSLClient(const std::string &host, int port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path);
+
+ explicit SSLClient(const std::string &host, int port, X509 *client_cert,
+ EVP_PKEY *client_key);
+
+ ~SSLClient() override;
+
+ bool is_valid() const override;
+
+ void set_ca_cert_store(X509_STORE *ca_cert_store);
+
+ long get_openssl_verify_result() const;
+
+ SSL_CTX *ssl_context() const;
+
+private:
+ bool create_and_connect_socket(Socket &socket, Error &error) override;
+ void shutdown_ssl(Socket &socket, bool shutdown_gracefully) override;
+ void shutdown_ssl_impl(Socket &socket, bool shutdown_socket);
+
+ bool process_socket(const Socket &socket,
+ std::function<bool(Stream &strm)> callback) override;
+ bool is_ssl() const override;
+
+ bool connect_with_proxy(Socket &sock, Response &res, bool &success,
+ Error &error);
+ bool initialize_ssl(Socket &socket, Error &error);
+
+ bool load_certs();
+
+ bool verify_host(X509 *server_cert) const;
+ bool verify_host_with_subject_alt_name(X509 *server_cert) const;
+ bool verify_host_with_common_name(X509 *server_cert) const;
+ bool check_host_name(const char *pattern, size_t pattern_len) const;
+
+ SSL_CTX *ctx_;
+ std::mutex ctx_mutex_;
+ std::once_flag initialize_cert_;
+
+ std::vector<std::string> host_components_;
+
+ long verify_result_ = 0;
+
+ friend class ClientImpl;
+};
+#endif
+
+/*
+ * Implementation of template methods.
+ */
+
+namespace detail {
+
+template <typename T, typename U>
+inline void duration_to_sec_and_usec(const T &duration, U callback) {
+ auto sec = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
+ auto usec = std::chrono::duration_cast<std::chrono::microseconds>(
+ duration - std::chrono::seconds(sec))
+ .count();
+ callback(sec, usec);
+}
+
+template <typename T>
+inline T get_header_value(const Headers & /*headers*/, const char * /*key*/,
+ size_t /*id*/ = 0, uint64_t /*def*/ = 0) {}
+
+template <>
+inline uint64_t get_header_value<uint64_t>(const Headers &headers,
+ const char *key, size_t id,
+ uint64_t def) {
+ auto rng = headers.equal_range(key);
+ auto it = rng.first;
+ std::advance(it, static_cast<ssize_t>(id));
+ if (it != rng.second) {
+ return std::strtoull(it->second.data(), nullptr, 10);
+ }
+ return def;
+}
+
+} // namespace detail
+
+template <typename T>
+inline T Request::get_header_value(const char *key, size_t id) const {
+ return detail::get_header_value<T>(headers, key, id, 0);
+}
+
+template <typename T>
+inline T Response::get_header_value(const char *key, size_t id) const {
+ return detail::get_header_value<T>(headers, key, id, 0);
+}
+
+template <typename... Args>
+inline ssize_t Stream::write_format(const char *fmt, const Args &... args) {
+ const auto bufsiz = 2048;
+ std::array<char, bufsiz> buf;
+
+#if defined(_MSC_VER) && _MSC_VER < 1900
+ auto sn = _snprintf_s(buf.data(), bufsiz - 1, buf.size() - 1, fmt, args...);
+#else
+ auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...);
+#endif
+ if (sn <= 0) { return sn; }
+
+ auto n = static_cast<size_t>(sn);
+
+ if (n >= buf.size() - 1) {
+ std::vector<char> glowable_buf(buf.size());
+
+ while (n >= glowable_buf.size() - 1) {
+ glowable_buf.resize(glowable_buf.size() * 2);
+#if defined(_MSC_VER) && _MSC_VER < 1900
+ n = static_cast<size_t>(_snprintf_s(&glowable_buf[0], glowable_buf.size(),
+ glowable_buf.size() - 1, fmt,
+ args...));
+#else
+ n = static_cast<size_t>(
+ snprintf(&glowable_buf[0], glowable_buf.size() - 1, fmt, args...));
+#endif
+ }
+ return write(&glowable_buf[0], n);
+ } else {
+ return write(buf.data(), n);
+ }
+}
+
+template <class Rep, class Period>
+inline Server &
+Server::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
+ detail::duration_to_sec_and_usec(
+ duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
+ return *this;
+}
+
+template <class Rep, class Period>
+inline Server &
+Server::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
+ detail::duration_to_sec_and_usec(
+ duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
+ return *this;
+}
+
+template <class Rep, class Period>
+inline Server &
+Server::set_idle_interval(const std::chrono::duration<Rep, Period> &duration) {
+ detail::duration_to_sec_and_usec(
+ duration, [&](time_t sec, time_t usec) { set_idle_interval(sec, usec); });
+ return *this;
+}
+
+template <typename T>
+inline T Result::get_request_header_value(const char *key, size_t id) const {
+ return detail::get_header_value<T>(request_headers_, key, id, 0);
+}
+
+template <class Rep, class Period>
+inline void ClientImpl::set_connection_timeout(
+ const std::chrono::duration<Rep, Period> &duration) {
+ detail::duration_to_sec_and_usec(duration, [&](time_t sec, time_t usec) {
+ set_connection_timeout(sec, usec);
+ });
+}
+
+template <class Rep, class Period>
+inline void ClientImpl::set_read_timeout(
+ const std::chrono::duration<Rep, Period> &duration) {
+ detail::duration_to_sec_and_usec(
+ duration, [&](time_t sec, time_t usec) { set_read_timeout(sec, usec); });
+}
+
+template <class Rep, class Period>
+inline void ClientImpl::set_write_timeout(
+ const std::chrono::duration<Rep, Period> &duration) {
+ detail::duration_to_sec_and_usec(
+ duration, [&](time_t sec, time_t usec) { set_write_timeout(sec, usec); });
+}
+
+template <class Rep, class Period>
+inline void Client::set_connection_timeout(
+ const std::chrono::duration<Rep, Period> &duration) {
+ cli_->set_connection_timeout(duration);
+}
+
+template <class Rep, class Period>
+inline void
+Client::set_read_timeout(const std::chrono::duration<Rep, Period> &duration) {
+ cli_->set_read_timeout(duration);
+}
+
+template <class Rep, class Period>
+inline void
+Client::set_write_timeout(const std::chrono::duration<Rep, Period> &duration) {
+ cli_->set_write_timeout(duration);
+}
+
+/*
+ * Forward declarations and types that will be part of the .h file if split into
+ * .h + .cc.
+ */
+
+std::pair<std::string, std::string> make_range_header(Ranges ranges);
+
+std::pair<std::string, std::string>
+make_basic_authentication_header(const std::string &username,
+ const std::string &password,
+ bool is_proxy = false);
+
+namespace detail {
+
+std::string encode_query_param(const std::string &value);
+
+void read_file(const std::string &path, std::string &out);
+
+std::string trim_copy(const std::string &s);
+
+void split(const char *b, const char *e, char d,
+ std::function<void(const char *, const char *)> fn);
+
+bool process_client_socket(socket_t sock, time_t read_timeout_sec,
+ time_t read_timeout_usec, time_t write_timeout_sec,
+ time_t write_timeout_usec,
+ std::function<bool(Stream &)> callback);
+
+socket_t create_client_socket(const char *host, int port, int address_family,
+ bool tcp_nodelay, SocketOptions socket_options,
+ time_t connection_timeout_sec,
+ time_t connection_timeout_usec,
+ time_t read_timeout_sec, time_t read_timeout_usec,
+ time_t write_timeout_sec,
+ time_t write_timeout_usec,
+ const std::string &intf, Error &error);
+
+const char *get_header_value(const Headers &headers, const char *key,
+ size_t id = 0, const char *def = nullptr);
+
+std::string params_to_query_str(const Params &params);
+
+void parse_query_text(const std::string &s, Params &params);
+
+bool parse_range_header(const std::string &s, Ranges &ranges);
+
+int close_socket(socket_t sock);
+
+enum class EncodingType { None = 0, Gzip, Brotli };
+
+EncodingType encoding_type(const Request &req, const Response &res);
+
+class BufferStream : public Stream {
+public:
+ BufferStream() = default;
+ ~BufferStream() override = default;
+
+ bool is_readable() const override;
+ bool is_writable() const override;
+ ssize_t read(char *ptr, size_t size) override;
+ ssize_t write(const char *ptr, size_t size) override;
+ void get_remote_ip_and_port(std::string &ip, int &port) const override;
+ socket_t socket() const override;
+
+ const std::string &get_buffer() const;
+
+private:
+ std::string buffer;
+ size_t position = 0;
+};
+
+class compressor {
+public:
+ virtual ~compressor() = default;
+
+ typedef std::function<bool(const char *data, size_t data_len)> Callback;
+ virtual bool compress(const char *data, size_t data_length, bool last,
+ Callback callback) = 0;
+};
+
+class decompressor {
+public:
+ virtual ~decompressor() = default;
+
+ virtual bool is_valid() const = 0;
+
+ typedef std::function<bool(const char *data, size_t data_len)> Callback;
+ virtual bool decompress(const char *data, size_t data_length,
+ Callback callback) = 0;
+};
+
+class nocompressor : public compressor {
+public:
+ virtual ~nocompressor() = default;
+
+ bool compress(const char *data, size_t data_length, bool /*last*/,
+ Callback callback) override;
+};
+
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+class gzip_compressor : public compressor {
+public:
+ gzip_compressor();
+ ~gzip_compressor();
+
+ bool compress(const char *data, size_t data_length, bool last,
+ Callback callback) override;
+
+private:
+ bool is_valid_ = false;
+ z_stream strm_;
+};
+
+class gzip_decompressor : public decompressor {
+public:
+ gzip_decompressor();
+ ~gzip_decompressor();
+
+ bool is_valid() const override;
+
+ bool decompress(const char *data, size_t data_length,
+ Callback callback) override;
+
+private:
+ bool is_valid_ = false;
+ z_stream strm_;
+};
+#endif
+
+#ifdef CPPHTTPLIB_BROTLI_SUPPORT
+class brotli_compressor : public compressor {
+public:
+ brotli_compressor();
+ ~brotli_compressor();
+
+ bool compress(const char *data, size_t data_length, bool last,
+ Callback callback) override;
+
+private:
+ BrotliEncoderState *state_ = nullptr;
+};
+
+class brotli_decompressor : public decompressor {
+public:
+ brotli_decompressor();
+ ~brotli_decompressor();
+
+ bool is_valid() const override;
+
+ bool decompress(const char *data, size_t data_length,
+ Callback callback) override;
+
+private:
+ BrotliDecoderResult decoder_r;
+ BrotliDecoderState *decoder_s = nullptr;
+};
+#endif
+
+// NOTE: until the read size reaches `fixed_buffer_size`, use `fixed_buffer`
+// to store data. The call can set memory on stack for performance.
+class stream_line_reader {
+public:
+ stream_line_reader(Stream &strm, char *fixed_buffer,
+ size_t fixed_buffer_size);
+ const char *ptr() const;
+ size_t size() const;
+ bool end_with_crlf() const;
+ bool getline();
+
+private:
+ void append(char c);
+
+ Stream &strm_;
+ char *fixed_buffer_;
+ const size_t fixed_buffer_size_;
+ size_t fixed_buffer_used_size_ = 0;
+ std::string glowable_buffer_;
+};
+
+} // namespace detail
+
+// ----------------------------------------------------------------------------
+
+/*
+ * Implementation that will be part of the .cc file if split into .h + .cc.
+ */
+
+namespace detail {
+
+inline bool is_hex(char c, int &v) {
+ if (0x20 <= c && isdigit(c)) {
+ v = c - '0';
+ return true;
+ } else if ('A' <= c && c <= 'F') {
+ v = c - 'A' + 10;
+ return true;
+ } else if ('a' <= c && c <= 'f') {
+ v = c - 'a' + 10;
+ return true;
+ }
+ return false;
+}
+
+inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt,
+ int &val) {
+ if (i >= s.size()) { return false; }
+
+ val = 0;
+ for (; cnt; i++, cnt--) {
+ if (!s[i]) { return false; }
+ int v = 0;
+ if (is_hex(s[i], v)) {
+ val = val * 16 + v;
+ } else {
+ return false;
+ }
+ }
+ return true;
+}
+
+inline std::string from_i_to_hex(size_t n) {
+ const char *charset = "0123456789abcdef";
+ std::string ret;
+ do {
+ ret = charset[n & 15] + ret;
+ n >>= 4;
+ } while (n > 0);
+ return ret;
+}
+
+inline size_t to_utf8(int code, char *buff) {
+ if (code < 0x0080) {
+ buff[0] = (code & 0x7F);
+ return 1;
+ } else if (code < 0x0800) {
+ buff[0] = static_cast<char>(0xC0 | ((code >> 6) & 0x1F));
+ buff[1] = static_cast<char>(0x80 | (code & 0x3F));
+ return 2;
+ } else if (code < 0xD800) {
+ buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
+ buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
+ buff[2] = static_cast<char>(0x80 | (code & 0x3F));
+ return 3;
+ } else if (code < 0xE000) { // D800 - DFFF is invalid...
+ return 0;
+ } else if (code < 0x10000) {
+ buff[0] = static_cast<char>(0xE0 | ((code >> 12) & 0xF));
+ buff[1] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
+ buff[2] = static_cast<char>(0x80 | (code & 0x3F));
+ return 3;
+ } else if (code < 0x110000) {
+ buff[0] = static_cast<char>(0xF0 | ((code >> 18) & 0x7));
+ buff[1] = static_cast<char>(0x80 | ((code >> 12) & 0x3F));
+ buff[2] = static_cast<char>(0x80 | ((code >> 6) & 0x3F));
+ buff[3] = static_cast<char>(0x80 | (code & 0x3F));
+ return 4;
+ }
+
+ // NOTREACHED
+ return 0;
+}
+
+// NOTE: This code came up with the following stackoverflow post:
+// https://stackoverflow.com/questions/180947/base64-decode-snippet-in-c
+inline std::string base64_encode(const std::string &in) {
+ static const auto lookup =
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
+
+ std::string out;
+ out.reserve(in.size());
+
+ int val = 0;
+ int valb = -6;
+
+ for (auto c : in) {
+ val = (val << 8) + static_cast<uint8_t>(c);
+ valb += 8;
+ while (valb >= 0) {
+ out.push_back(lookup[(val >> valb) & 0x3F]);
+ valb -= 6;
+ }
+ }
+
+ if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); }
+
+ while (out.size() % 4) {
+ out.push_back('=');
+ }
+
+ return out;
+}
+
+inline bool is_file(const std::string &path) {
+ struct stat st;
+ return stat(path.c_str(), &st) >= 0 && S_ISREG(st.st_mode);
+}
+
+inline bool is_dir(const std::string &path) {
+ struct stat st;
+ return stat(path.c_str(), &st) >= 0 && S_ISDIR(st.st_mode);
+}
+
+inline bool is_valid_path(const std::string &path) {
+ size_t level = 0;
+ size_t i = 0;
+
+ // Skip slash
+ while (i < path.size() && path[i] == '/') {
+ i++;
+ }
+
+ while (i < path.size()) {
+ // Read component
+ auto beg = i;
+ while (i < path.size() && path[i] != '/') {
+ i++;
+ }
+
+ auto len = i - beg;
+ assert(len > 0);
+
+ if (!path.compare(beg, len, ".")) {
+ ;
+ } else if (!path.compare(beg, len, "..")) {
+ if (level == 0) { return false; }
+ level--;
+ } else {
+ level++;
+ }
+
+ // Skip slash
+ while (i < path.size() && path[i] == '/') {
+ i++;
+ }
+ }
+
+ return true;
+}
+
+inline std::string encode_query_param(const std::string &value) {
+ std::ostringstream escaped;
+ escaped.fill('0');
+ escaped << std::hex;
+
+ for (auto c : value) {
+ if (std::isalnum(static_cast<uint8_t>(c)) || c == '-' || c == '_' ||
+ c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' ||
+ c == ')') {
+ escaped << c;
+ } else {
+ escaped << std::uppercase;
+ escaped << '%' << std::setw(2)
+ << static_cast<int>(static_cast<unsigned char>(c));
+ escaped << std::nouppercase;
+ }
+ }
+
+ return escaped.str();
+}
+
+inline std::string encode_url(const std::string &s) {
+ std::string result;
+ result.reserve(s.size());
+
+ for (size_t i = 0; s[i]; i++) {
+ switch (s[i]) {
+ case ' ': result += "%20"; break;
+ case '+': result += "%2B"; break;
+ case '\r': result += "%0D"; break;
+ case '\n': result += "%0A"; break;
+ case '\'': result += "%27"; break;
+ case ',': result += "%2C"; break;
+ // case ':': result += "%3A"; break; // ok? probably...
+ case ';': result += "%3B"; break;
+ default:
+ auto c = static_cast<uint8_t>(s[i]);
+ if (c >= 0x80) {
+ result += '%';
+ char hex[4];
+ auto len = snprintf(hex, sizeof(hex) - 1, "%02X", c);
+ assert(len == 2);
+ result.append(hex, static_cast<size_t>(len));
+ } else {
+ result += s[i];
+ }
+ break;
+ }
+ }
+
+ return result;
+}
+
+inline std::string decode_url(const std::string &s,
+ bool convert_plus_to_space) {
+ std::string result;
+
+ for (size_t i = 0; i < s.size(); i++) {
+ if (s[i] == '%' && i + 1 < s.size()) {
+ if (s[i + 1] == 'u') {
+ int val = 0;
+ if (from_hex_to_i(s, i + 2, 4, val)) {
+ // 4 digits Unicode codes
+ char buff[4];
+ size_t len = to_utf8(val, buff);
+ if (len > 0) { result.append(buff, len); }
+ i += 5; // 'u0000'
+ } else {
+ result += s[i];
+ }
+ } else {
+ int val = 0;
+ if (from_hex_to_i(s, i + 1, 2, val)) {
+ // 2 digits hex codes
+ result += static_cast<char>(val);
+ i += 2; // '00'
+ } else {
+ result += s[i];
+ }
+ }
+ } else if (convert_plus_to_space && s[i] == '+') {
+ result += ' ';
+ } else {
+ result += s[i];
+ }
+ }
+
+ return result;
+}
+
+inline void read_file(const std::string &path, std::string &out) {
+ std::ifstream fs(path, std::ios_base::binary);
+ fs.seekg(0, std::ios_base::end);
+ auto size = fs.tellg();
+ fs.seekg(0);
+ out.resize(static_cast<size_t>(size));
+ fs.read(&out[0], static_cast<std::streamsize>(size));
+}
+
+inline std::string file_extension(const std::string &path) {
+ std::smatch m;
+ static auto re = std::regex("\\.([a-zA-Z0-9]+)$");
+ if (std::regex_search(path, m, re)) { return m[1].str(); }
+ return std::string();
+}
+
+inline bool is_space_or_tab(char c) { return c == ' ' || c == '\t'; }
+
+inline std::pair<size_t, size_t> trim(const char *b, const char *e, size_t left,
+ size_t right) {
+ while (b + left < e && is_space_or_tab(b[left])) {
+ left++;
+ }
+ while (right > 0 && is_space_or_tab(b[right - 1])) {
+ right--;
+ }
+ return std::make_pair(left, right);
+}
+
+inline std::string trim_copy(const std::string &s) {
+ auto r = trim(s.data(), s.data() + s.size(), 0, s.size());
+ return s.substr(r.first, r.second - r.first);
+}
+
+inline void split(const char *b, const char *e, char d,
+ std::function<void(const char *, const char *)> fn) {
+ size_t i = 0;
+ size_t beg = 0;
+
+ while (e ? (b + i < e) : (b[i] != '\0')) {
+ if (b[i] == d) {
+ auto r = trim(b, e, beg, i);
+ if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
+ beg = i + 1;
+ }
+ i++;
+ }
+
+ if (i) {
+ auto r = trim(b, e, beg, i);
+ if (r.first < r.second) { fn(&b[r.first], &b[r.second]); }
+ }
+}
+
+inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer,
+ size_t fixed_buffer_size)
+ : strm_(strm), fixed_buffer_(fixed_buffer),
+ fixed_buffer_size_(fixed_buffer_size) {}
+
+inline const char *stream_line_reader::ptr() const {
+ if (glowable_buffer_.empty()) {
+ return fixed_buffer_;
+ } else {
+ return glowable_buffer_.data();
+ }
+}
+
+inline size_t stream_line_reader::size() const {
+ if (glowable_buffer_.empty()) {
+ return fixed_buffer_used_size_;
+ } else {
+ return glowable_buffer_.size();
+ }
+}
+
+inline bool stream_line_reader::end_with_crlf() const {
+ auto end = ptr() + size();
+ return size() >= 2 && end[-2] == '\r' && end[-1] == '\n';
+}
+
+inline bool stream_line_reader::getline() {
+ fixed_buffer_used_size_ = 0;
+ glowable_buffer_.clear();
+
+ for (size_t i = 0;; i++) {
+ char byte;
+ auto n = strm_.read(&byte, 1);
+
+ if (n < 0) {
+ return false;
+ } else if (n == 0) {
+ if (i == 0) {
+ return false;
+ } else {
+ break;
+ }
+ }
+
+ append(byte);
+
+ if (byte == '\n') { break; }
+ }
+
+ return true;
+}
+
+inline void stream_line_reader::append(char c) {
+ if (fixed_buffer_used_size_ < fixed_buffer_size_ - 1) {
+ fixed_buffer_[fixed_buffer_used_size_++] = c;
+ fixed_buffer_[fixed_buffer_used_size_] = '\0';
+ } else {
+ if (glowable_buffer_.empty()) {
+ assert(fixed_buffer_[fixed_buffer_used_size_] == '\0');
+ glowable_buffer_.assign(fixed_buffer_, fixed_buffer_used_size_);
+ }
+ glowable_buffer_ += c;
+ }
+}
+
+inline int close_socket(socket_t sock) {
+#ifdef _WIN32
+ return closesocket(sock);
+#else
+ return close(sock);
+#endif
+}
+
+template <typename T> inline ssize_t handle_EINTR(T fn) {
+ ssize_t res = false;
+ while (true) {
+ res = fn();
+ if (res < 0 && errno == EINTR) { continue; }
+ break;
+ }
+ return res;
+}
+
+inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) {
+#ifdef CPPHTTPLIB_USE_POLL
+ struct pollfd pfd_read;
+ pfd_read.fd = sock;
+ pfd_read.events = POLLIN;
+
+ auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
+
+ return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
+#else
+#ifndef _WIN32
+ if (sock >= FD_SETSIZE) { return 1; }
+#endif
+
+ fd_set fds;
+ FD_ZERO(&fds);
+ FD_SET(sock, &fds);
+
+ timeval tv;
+ tv.tv_sec = static_cast<long>(sec);
+ tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
+
+ return handle_EINTR([&]() {
+ return select(static_cast<int>(sock + 1), &fds, nullptr, nullptr, &tv);
+ });
+#endif
+}
+
+inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) {
+#ifdef CPPHTTPLIB_USE_POLL
+ struct pollfd pfd_read;
+ pfd_read.fd = sock;
+ pfd_read.events = POLLOUT;
+
+ auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
+
+ return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
+#else
+#ifndef _WIN32
+ if (sock >= FD_SETSIZE) { return 1; }
+#endif
+
+ fd_set fds;
+ FD_ZERO(&fds);
+ FD_SET(sock, &fds);
+
+ timeval tv;
+ tv.tv_sec = static_cast<long>(sec);
+ tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
+
+ return handle_EINTR([&]() {
+ return select(static_cast<int>(sock + 1), nullptr, &fds, nullptr, &tv);
+ });
+#endif
+}
+
+inline bool wait_until_socket_is_ready(socket_t sock, time_t sec, time_t usec) {
+#ifdef CPPHTTPLIB_USE_POLL
+ struct pollfd pfd_read;
+ pfd_read.fd = sock;
+ pfd_read.events = POLLIN | POLLOUT;
+
+ auto timeout = static_cast<int>(sec * 1000 + usec / 1000);
+
+ auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); });
+
+ if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) {
+ int error = 0;
+ socklen_t len = sizeof(error);
+ auto res = getsockopt(sock, SOL_SOCKET, SO_ERROR,
+ reinterpret_cast<char *>(&error), &len);
+ return res >= 0 && !error;
+ }
+ return false;
+#else
+#ifndef _WIN32
+ if (sock >= FD_SETSIZE) { return false; }
+#endif
+
+ fd_set fdsr;
+ FD_ZERO(&fdsr);
+ FD_SET(sock, &fdsr);
+
+ auto fdsw = fdsr;
+ auto fdse = fdsr;
+
+ timeval tv;
+ tv.tv_sec = static_cast<long>(sec);
+ tv.tv_usec = static_cast<decltype(tv.tv_usec)>(usec);
+
+ auto ret = handle_EINTR([&]() {
+ return select(static_cast<int>(sock + 1), &fdsr, &fdsw, &fdse, &tv);
+ });
+
+ if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) {
+ int error = 0;
+ socklen_t len = sizeof(error);
+ return getsockopt(sock, SOL_SOCKET, SO_ERROR,
+ reinterpret_cast<char *>(&error), &len) >= 0 &&
+ !error;
+ }
+ return false;
+#endif
+}
+
+class SocketStream : public Stream {
+public:
+ SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec,
+ time_t write_timeout_sec, time_t write_timeout_usec);
+ ~SocketStream() override;
+
+ bool is_readable() const override;
+ bool is_writable() const override;
+ ssize_t read(char *ptr, size_t size) override;
+ ssize_t write(const char *ptr, size_t size) override;
+ void get_remote_ip_and_port(std::string &ip, int &port) const override;
+ socket_t socket() const override;
+
+private:
+ socket_t sock_;
+ time_t read_timeout_sec_;
+ time_t read_timeout_usec_;
+ time_t write_timeout_sec_;
+ time_t write_timeout_usec_;
+};
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+class SSLSocketStream : public Stream {
+public:
+ SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_sec,
+ time_t read_timeout_usec, time_t write_timeout_sec,
+ time_t write_timeout_usec);
+ ~SSLSocketStream() override;
+
+ bool is_readable() const override;
+ bool is_writable() const override;
+ ssize_t read(char *ptr, size_t size) override;
+ ssize_t write(const char *ptr, size_t size) override;
+ void get_remote_ip_and_port(std::string &ip, int &port) const override;
+ socket_t socket() const override;
+
+private:
+ socket_t sock_;
+ SSL *ssl_;
+ time_t read_timeout_sec_;
+ time_t read_timeout_usec_;
+ time_t write_timeout_sec_;
+ time_t write_timeout_usec_;
+};
+#endif
+
+inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) {
+ using namespace std::chrono;
+ auto start = steady_clock::now();
+ while (true) {
+ auto val = select_read(sock, 0, 10000);
+ if (val < 0) {
+ return false;
+ } else if (val == 0) {
+ auto current = steady_clock::now();
+ auto duration = duration_cast<milliseconds>(current - start);
+ auto timeout = keep_alive_timeout_sec * 1000;
+ if (duration.count() > timeout) { return false; }
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ } else {
+ return true;
+ }
+ }
+}
+
+template <typename T>
+inline bool
+process_server_socket_core(socket_t sock, size_t keep_alive_max_count,
+ time_t keep_alive_timeout_sec, T callback) {
+ assert(keep_alive_max_count > 0);
+ auto ret = false;
+ auto count = keep_alive_max_count;
+ while (count > 0 && keep_alive(sock, keep_alive_timeout_sec)) {
+ auto close_connection = count == 1;
+ auto connection_closed = false;
+ ret = callback(close_connection, connection_closed);
+ if (!ret || connection_closed) { break; }
+ count--;
+ }
+ return ret;
+}
+
+template <typename T>
+inline bool
+process_server_socket(socket_t sock, size_t keep_alive_max_count,
+ time_t keep_alive_timeout_sec, time_t read_timeout_sec,
+ time_t read_timeout_usec, time_t write_timeout_sec,
+ time_t write_timeout_usec, T callback) {
+ return process_server_socket_core(
+ sock, keep_alive_max_count, keep_alive_timeout_sec,
+ [&](bool close_connection, bool &connection_closed) {
+ SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
+ write_timeout_sec, write_timeout_usec);
+ return callback(strm, close_connection, connection_closed);
+ });
+}
+
+inline bool process_client_socket(socket_t sock, time_t read_timeout_sec,
+ time_t read_timeout_usec,
+ time_t write_timeout_sec,
+ time_t write_timeout_usec,
+ std::function<bool(Stream &)> callback) {
+ SocketStream strm(sock, read_timeout_sec, read_timeout_usec,
+ write_timeout_sec, write_timeout_usec);
+ return callback(strm);
+}
+
+inline int shutdown_socket(socket_t sock) {
+#ifdef _WIN32
+ return shutdown(sock, SD_BOTH);
+#else
+ return shutdown(sock, SHUT_RDWR);
+#endif
+}
+
+template <typename BindOrConnect>
+socket_t create_socket(const char *host, int port, int address_family,
+ int socket_flags, bool tcp_nodelay,
+ SocketOptions socket_options,
+ BindOrConnect bind_or_connect) {
+ // Get address info
+ struct addrinfo hints;
+ struct addrinfo *result;
+
+ memset(&hints, 0, sizeof(struct addrinfo));
+ hints.ai_family = address_family;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_flags = socket_flags;
+ hints.ai_protocol = 0;
+
+ auto service = std::to_string(port);
+
+ if (getaddrinfo(host, service.c_str(), &hints, &result)) {
+#ifdef __linux__
+ res_init();
+#endif
+ return INVALID_SOCKET;
+ }
+
+ for (auto rp = result; rp; rp = rp->ai_next) {
+ // Create a socket
+#ifdef _WIN32
+ auto sock =
+ WSASocketW(rp->ai_family, rp->ai_socktype, rp->ai_protocol, nullptr, 0,
+ WSA_FLAG_NO_HANDLE_INHERIT | WSA_FLAG_OVERLAPPED);
+ /**
+ * Since the WSA_FLAG_NO_HANDLE_INHERIT is only supported on Windows 7 SP1
+ * and above the socket creation fails on older Windows Systems.
+ *
+ * Let's try to create a socket the old way in this case.
+ *
+ * Reference:
+ * https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasocketa
+ *
+ * WSA_FLAG_NO_HANDLE_INHERIT:
+ * This flag is supported on Windows 7 with SP1, Windows Server 2008 R2 with
+ * SP1, and later
+ *
+ */
+ if (sock == INVALID_SOCKET) {
+ sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+ }
+#else
+ auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+#endif
+ if (sock == INVALID_SOCKET) { continue; }
+
+#ifndef _WIN32
+ if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { continue; }
+#endif
+
+ if (tcp_nodelay) {
+ int yes = 1;
+ setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast<char *>(&yes),
+ sizeof(yes));
+ }
+
+ if (socket_options) { socket_options(sock); }
+
+ if (rp->ai_family == AF_INET6) {
+ int no = 0;
+ setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, reinterpret_cast<char *>(&no),
+ sizeof(no));
+ }
+
+ // bind or connect
+ if (bind_or_connect(sock, *rp)) {
+ freeaddrinfo(result);
+ return sock;
+ }
+
+ close_socket(sock);
+ }
+
+ freeaddrinfo(result);
+ return INVALID_SOCKET;
+}
+
+inline void set_nonblocking(socket_t sock, bool nonblocking) {
+#ifdef _WIN32
+ auto flags = nonblocking ? 1UL : 0UL;
+ ioctlsocket(sock, FIONBIO, &flags);
+#else
+ auto flags = fcntl(sock, F_GETFL, 0);
+ fcntl(sock, F_SETFL,
+ nonblocking ? (flags | O_NONBLOCK) : (flags & (~O_NONBLOCK)));
+#endif
+}
+
+inline bool is_connection_error() {
+#ifdef _WIN32
+ return WSAGetLastError() != WSAEWOULDBLOCK;
+#else
+ return errno != EINPROGRESS;
+#endif
+}
+
+inline bool bind_ip_address(socket_t sock, const char *host) {
+ struct addrinfo hints;
+ struct addrinfo *result;
+
+ memset(&hints, 0, sizeof(struct addrinfo));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+ hints.ai_protocol = 0;
+
+ if (getaddrinfo(host, "0", &hints, &result)) { return false; }
+
+ auto ret = false;
+ for (auto rp = result; rp; rp = rp->ai_next) {
+ const auto &ai = *rp;
+ if (!::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
+ ret = true;
+ break;
+ }
+ }
+
+ freeaddrinfo(result);
+ return ret;
+}
+
+#if !defined _WIN32 && !defined ANDROID
+#define USE_IF2IP
+#endif
+
+#ifdef USE_IF2IP
+inline std::string if2ip(const std::string &ifn) {
+ struct ifaddrs *ifap;
+ getifaddrs(&ifap);
+ for (auto ifa = ifap; ifa; ifa = ifa->ifa_next) {
+ if (ifa->ifa_addr && ifn == ifa->ifa_name) {
+ if (ifa->ifa_addr->sa_family == AF_INET) {
+ auto sa = reinterpret_cast<struct sockaddr_in *>(ifa->ifa_addr);
+ char buf[INET_ADDRSTRLEN];
+ if (inet_ntop(AF_INET, &sa->sin_addr, buf, INET_ADDRSTRLEN)) {
+ freeifaddrs(ifap);
+ return std::string(buf, INET_ADDRSTRLEN);
+ }
+ }
+ }
+ }
+ freeifaddrs(ifap);
+ return std::string();
+}
+#endif
+
+inline socket_t create_client_socket(
+ const char *host, int port, int address_family, bool tcp_nodelay,
+ SocketOptions socket_options, time_t connection_timeout_sec,
+ time_t connection_timeout_usec, time_t read_timeout_sec,
+ time_t read_timeout_usec, time_t write_timeout_sec,
+ time_t write_timeout_usec, const std::string &intf, Error &error) {
+ auto sock = create_socket(
+ host, port, address_family, 0, tcp_nodelay, std::move(socket_options),
+ [&](socket_t sock2, struct addrinfo &ai) -> bool {
+ if (!intf.empty()) {
+#ifdef USE_IF2IP
+ auto ip = if2ip(intf);
+ if (ip.empty()) { ip = intf; }
+ if (!bind_ip_address(sock2, ip.c_str())) {
+ error = Error::BindIPAddress;
+ return false;
+ }
+#endif
+ }
+
+ set_nonblocking(sock2, true);
+
+ auto ret =
+ ::connect(sock2, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen));
+
+ if (ret < 0) {
+ if (is_connection_error() ||
+ !wait_until_socket_is_ready(sock2, connection_timeout_sec,
+ connection_timeout_usec)) {
+ error = Error::Connection;
+ return false;
+ }
+ }
+
+ set_nonblocking(sock2, false);
+
+ {
+ timeval tv;
+ tv.tv_sec = static_cast<long>(read_timeout_sec);
+ tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec);
+ setsockopt(sock2, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
+ }
+ {
+ timeval tv;
+ tv.tv_sec = static_cast<long>(write_timeout_sec);
+ tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec);
+ setsockopt(sock2, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
+ }
+
+ error = Error::Success;
+ return true;
+ });
+
+ if (sock != INVALID_SOCKET) {
+ error = Error::Success;
+ } else {
+ if (error == Error::Success) { error = Error::Connection; }
+ }
+
+ return sock;
+}
+
+inline void get_remote_ip_and_port(const struct sockaddr_storage &addr,
+ socklen_t addr_len, std::string &ip,
+ int &port) {
+ if (addr.ss_family == AF_INET) {
+ port = ntohs(reinterpret_cast<const struct sockaddr_in *>(&addr)->sin_port);
+ } else if (addr.ss_family == AF_INET6) {
+ port =
+ ntohs(reinterpret_cast<const struct sockaddr_in6 *>(&addr)->sin6_port);
+ }
+
+ std::array<char, NI_MAXHOST> ipstr{};
+ if (!getnameinfo(reinterpret_cast<const struct sockaddr *>(&addr), addr_len,
+ ipstr.data(), static_cast<socklen_t>(ipstr.size()), nullptr,
+ 0, NI_NUMERICHOST)) {
+ ip = ipstr.data();
+ }
+}
+
+inline void get_remote_ip_and_port(socket_t sock, std::string &ip, int &port) {
+ struct sockaddr_storage addr;
+ socklen_t addr_len = sizeof(addr);
+
+ if (!getpeername(sock, reinterpret_cast<struct sockaddr *>(&addr),
+ &addr_len)) {
+ get_remote_ip_and_port(addr, addr_len, ip, port);
+ }
+}
+
+inline constexpr unsigned int str2tag_core(const char *s, size_t l,
+ unsigned int h) {
+ return (l == 0) ? h
+ : str2tag_core(s + 1, l - 1,
+ (h * 33) ^ static_cast<unsigned char>(*s));
+}
+
+inline unsigned int str2tag(const std::string &s) {
+ return str2tag_core(s.data(), s.size(), 0);
+}
+
+namespace udl {
+
+inline constexpr unsigned int operator"" _t(const char *s, size_t l) {
+ return str2tag_core(s, l, 0);
+}
+
+} // namespace udl
+
+inline const char *
+find_content_type(const std::string &path,
+ const std::map<std::string, std::string> &user_data) {
+ auto ext = file_extension(path);
+
+ auto it = user_data.find(ext);
+ if (it != user_data.end()) { return it->second.c_str(); }
+
+ using udl::operator""_t;
+
+ switch (str2tag(ext)) {
+ default: return nullptr;
+ case "css"_t: return "text/css";
+ case "csv"_t: return "text/csv";
+ case "txt"_t: return "text/plain";
+ case "vtt"_t: return "text/vtt";
+ case "htm"_t:
+ case "html"_t: return "text/html";
+
+ case "apng"_t: return "image/apng";
+ case "avif"_t: return "image/avif";
+ case "bmp"_t: return "image/bmp";
+ case "gif"_t: return "image/gif";
+ case "png"_t: return "image/png";
+ case "svg"_t: return "image/svg+xml";
+ case "webp"_t: return "image/webp";
+ case "ico"_t: return "image/x-icon";
+ case "tif"_t: return "image/tiff";
+ case "tiff"_t: return "image/tiff";
+ case "jpg"_t:
+ case "jpeg"_t: return "image/jpeg";
+
+ case "mp4"_t: return "video/mp4";
+ case "mpeg"_t: return "video/mpeg";
+ case "webm"_t: return "video/webm";
+
+ case "mp3"_t: return "audio/mp3";
+ case "mpga"_t: return "audio/mpeg";
+ case "weba"_t: return "audio/webm";
+ case "wav"_t: return "audio/wave";
+
+ case "otf"_t: return "font/otf";
+ case "ttf"_t: return "font/ttf";
+ case "woff"_t: return "font/woff";
+ case "woff2"_t: return "font/woff2";
+
+ case "7z"_t: return "application/x-7z-compressed";
+ case "atom"_t: return "application/atom+xml";
+ case "pdf"_t: return "application/pdf";
+ case "js"_t:
+ case "mjs"_t: return "application/javascript";
+ case "json"_t: return "application/json";
+ case "rss"_t: return "application/rss+xml";
+ case "tar"_t: return "application/x-tar";
+ case "xht"_t:
+ case "xhtml"_t: return "application/xhtml+xml";
+ case "xslt"_t: return "application/xslt+xml";
+ case "xml"_t: return "application/xml";
+ case "gz"_t: return "application/gzip";
+ case "zip"_t: return "application/zip";
+ case "wasm"_t: return "application/wasm";
+ }
+}
+
+inline const char *status_message(int status) {
+ switch (status) {
+ case 100: return "Continue";
+ case 101: return "Switching Protocol";
+ case 102: return "Processing";
+ case 103: return "Early Hints";
+ case 200: return "OK";
+ case 201: return "Created";
+ case 202: return "Accepted";
+ case 203: return "Non-Authoritative Information";
+ case 204: return "No Content";
+ case 205: return "Reset Content";
+ case 206: return "Partial Content";
+ case 207: return "Multi-Status";
+ case 208: return "Already Reported";
+ case 226: return "IM Used";
+ case 300: return "Multiple Choice";
+ case 301: return "Moved Permanently";
+ case 302: return "Found";
+ case 303: return "See Other";
+ case 304: return "Not Modified";
+ case 305: return "Use Proxy";
+ case 306: return "unused";
+ case 307: return "Temporary Redirect";
+ case 308: return "Permanent Redirect";
+ case 400: return "Bad Request";
+ case 401: return "Unauthorized";
+ case 402: return "Payment Required";
+ case 403: return "Forbidden";
+ case 404: return "Not Found";
+ case 405: return "Method Not Allowed";
+ case 406: return "Not Acceptable";
+ case 407: return "Proxy Authentication Required";
+ case 408: return "Request Timeout";
+ case 409: return "Conflict";
+ case 410: return "Gone";
+ case 411: return "Length Required";
+ case 412: return "Precondition Failed";
+ case 413: return "Payload Too Large";
+ case 414: return "URI Too Long";
+ case 415: return "Unsupported Media Type";
+ case 416: return "Range Not Satisfiable";
+ case 417: return "Expectation Failed";
+ case 418: return "I'm a teapot";
+ case 421: return "Misdirected Request";
+ case 422: return "Unprocessable Entity";
+ case 423: return "Locked";
+ case 424: return "Failed Dependency";
+ case 425: return "Too Early";
+ case 426: return "Upgrade Required";
+ case 428: return "Precondition Required";
+ case 429: return "Too Many Requests";
+ case 431: return "Request Header Fields Too Large";
+ case 451: return "Unavailable For Legal Reasons";
+ case 501: return "Not Implemented";
+ case 502: return "Bad Gateway";
+ case 503: return "Service Unavailable";
+ case 504: return "Gateway Timeout";
+ case 505: return "HTTP Version Not Supported";
+ case 506: return "Variant Also Negotiates";
+ case 507: return "Insufficient Storage";
+ case 508: return "Loop Detected";
+ case 510: return "Not Extended";
+ case 511: return "Network Authentication Required";
+
+ default:
+ case 500: return "Internal Server Error";
+ }
+}
+
+inline bool can_compress_content_type(const std::string &content_type) {
+ return (!content_type.find("text/") && content_type != "text/event-stream") ||
+ content_type == "image/svg+xml" ||
+ content_type == "application/javascript" ||
+ content_type == "application/json" ||
+ content_type == "application/xml" ||
+ content_type == "application/xhtml+xml";
+}
+
+inline EncodingType encoding_type(const Request &req, const Response &res) {
+ auto ret =
+ detail::can_compress_content_type(res.get_header_value("Content-Type"));
+ if (!ret) { return EncodingType::None; }
+
+ const auto &s = req.get_header_value("Accept-Encoding");
+ (void)(s);
+
+#ifdef CPPHTTPLIB_BROTLI_SUPPORT
+ // TODO: 'Accept-Encoding' has br, not br;q=0
+ ret = s.find("br") != std::string::npos;
+ if (ret) { return EncodingType::Brotli; }
+#endif
+
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+ // TODO: 'Accept-Encoding' has gzip, not gzip;q=0
+ ret = s.find("gzip") != std::string::npos;
+ if (ret) { return EncodingType::Gzip; }
+#endif
+
+ return EncodingType::None;
+}
+
+inline bool nocompressor::compress(const char *data, size_t data_length,
+ bool /*last*/, Callback callback) {
+ if (!data_length) { return true; }
+ return callback(data, data_length);
+}
+
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+inline gzip_compressor::gzip_compressor() {
+ std::memset(&strm_, 0, sizeof(strm_));
+ strm_.zalloc = Z_NULL;
+ strm_.zfree = Z_NULL;
+ strm_.opaque = Z_NULL;
+
+ is_valid_ = deflateInit2(&strm_, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8,
+ Z_DEFAULT_STRATEGY) == Z_OK;
+}
+
+inline gzip_compressor::~gzip_compressor() { deflateEnd(&strm_); }
+
+inline bool gzip_compressor::compress(const char *data, size_t data_length,
+ bool last, Callback callback) {
+ assert(is_valid_);
+
+ do {
+ constexpr size_t max_avail_in =
+ std::numeric_limits<decltype(strm_.avail_in)>::max();
+
+ strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
+ std::min(data_length, max_avail_in));
+ strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
+
+ data_length -= strm_.avail_in;
+ data += strm_.avail_in;
+
+ auto flush = (last && data_length == 0) ? Z_FINISH : Z_NO_FLUSH;
+ int ret = Z_OK;
+
+ std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
+ do {
+ strm_.avail_out = static_cast<uInt>(buff.size());
+ strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
+
+ ret = deflate(&strm_, flush);
+ if (ret == Z_STREAM_ERROR) { return false; }
+
+ if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
+ return false;
+ }
+ } while (strm_.avail_out == 0);
+
+ assert((flush == Z_FINISH && ret == Z_STREAM_END) ||
+ (flush == Z_NO_FLUSH && ret == Z_OK));
+ assert(strm_.avail_in == 0);
+
+ } while (data_length > 0);
+
+ return true;
+}
+
+inline gzip_decompressor::gzip_decompressor() {
+ std::memset(&strm_, 0, sizeof(strm_));
+ strm_.zalloc = Z_NULL;
+ strm_.zfree = Z_NULL;
+ strm_.opaque = Z_NULL;
+
+ // 15 is the value of wbits, which should be at the maximum possible value
+ // to ensure that any gzip stream can be decoded. The offset of 32 specifies
+ // that the stream type should be automatically detected either gzip or
+ // deflate.
+ is_valid_ = inflateInit2(&strm_, 32 + 15) == Z_OK;
+}
+
+inline gzip_decompressor::~gzip_decompressor() { inflateEnd(&strm_); }
+
+inline bool gzip_decompressor::is_valid() const { return is_valid_; }
+
+inline bool gzip_decompressor::decompress(const char *data, size_t data_length,
+ Callback callback) {
+ assert(is_valid_);
+
+ int ret = Z_OK;
+
+ do {
+ constexpr size_t max_avail_in =
+ std::numeric_limits<decltype(strm_.avail_in)>::max();
+
+ strm_.avail_in = static_cast<decltype(strm_.avail_in)>(
+ std::min(data_length, max_avail_in));
+ strm_.next_in = const_cast<Bytef *>(reinterpret_cast<const Bytef *>(data));
+
+ data_length -= strm_.avail_in;
+ data += strm_.avail_in;
+
+ std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
+ while (strm_.avail_in > 0) {
+ strm_.avail_out = static_cast<uInt>(buff.size());
+ strm_.next_out = reinterpret_cast<Bytef *>(buff.data());
+
+ ret = inflate(&strm_, Z_NO_FLUSH);
+ assert(ret != Z_STREAM_ERROR);
+ switch (ret) {
+ case Z_NEED_DICT:
+ case Z_DATA_ERROR:
+ case Z_MEM_ERROR: inflateEnd(&strm_); return false;
+ }
+
+ if (!callback(buff.data(), buff.size() - strm_.avail_out)) {
+ return false;
+ }
+ }
+
+ if (ret != Z_OK && ret != Z_STREAM_END) return false;
+
+ } while (data_length > 0);
+
+ return true;
+}
+#endif
+
+#ifdef CPPHTTPLIB_BROTLI_SUPPORT
+inline brotli_compressor::brotli_compressor() {
+ state_ = BrotliEncoderCreateInstance(nullptr, nullptr, nullptr);
+}
+
+inline brotli_compressor::~brotli_compressor() {
+ BrotliEncoderDestroyInstance(state_);
+}
+
+inline bool brotli_compressor::compress(const char *data, size_t data_length,
+ bool last, Callback callback) {
+ std::array<uint8_t, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
+
+ auto operation = last ? BROTLI_OPERATION_FINISH : BROTLI_OPERATION_PROCESS;
+ auto available_in = data_length;
+ auto next_in = reinterpret_cast<const uint8_t *>(data);
+
+ for (;;) {
+ if (last) {
+ if (BrotliEncoderIsFinished(state_)) { break; }
+ } else {
+ if (!available_in) { break; }
+ }
+
+ auto available_out = buff.size();
+ auto next_out = buff.data();
+
+ if (!BrotliEncoderCompressStream(state_, operation, &available_in, &next_in,
+ &available_out, &next_out, nullptr)) {
+ return false;
+ }
+
+ auto output_bytes = buff.size() - available_out;
+ if (output_bytes) {
+ callback(reinterpret_cast<const char *>(buff.data()), output_bytes);
+ }
+ }
+
+ return true;
+}
+
+inline brotli_decompressor::brotli_decompressor() {
+ decoder_s = BrotliDecoderCreateInstance(0, 0, 0);
+ decoder_r = decoder_s ? BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT
+ : BROTLI_DECODER_RESULT_ERROR;
+}
+
+inline brotli_decompressor::~brotli_decompressor() {
+ if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); }
+}
+
+inline bool brotli_decompressor::is_valid() const { return decoder_s; }
+
+inline bool brotli_decompressor::decompress(const char *data,
+ size_t data_length,
+ Callback callback) {
+ if (decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
+ decoder_r == BROTLI_DECODER_RESULT_ERROR) {
+ return 0;
+ }
+
+ const uint8_t *next_in = (const uint8_t *)data;
+ size_t avail_in = data_length;
+ size_t total_out;
+
+ decoder_r = BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT;
+
+ std::array<char, CPPHTTPLIB_COMPRESSION_BUFSIZ> buff{};
+ while (decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT) {
+ char *next_out = buff.data();
+ size_t avail_out = buff.size();
+
+ decoder_r = BrotliDecoderDecompressStream(
+ decoder_s, &avail_in, &next_in, &avail_out,
+ reinterpret_cast<uint8_t **>(&next_out), &total_out);
+
+ if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; }
+
+ if (!callback(buff.data(), buff.size() - avail_out)) { return false; }
+ }
+
+ return decoder_r == BROTLI_DECODER_RESULT_SUCCESS ||
+ decoder_r == BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT;
+}
+#endif
+
+inline bool has_header(const Headers &headers, const char *key) {
+ return headers.find(key) != headers.end();
+}
+
+inline const char *get_header_value(const Headers &headers, const char *key,
+ size_t id, const char *def) {
+ auto rng = headers.equal_range(key);
+ auto it = rng.first;
+ std::advance(it, static_cast<ssize_t>(id));
+ if (it != rng.second) { return it->second.c_str(); }
+ return def;
+}
+
+template <typename T>
+inline bool parse_header(const char *beg, const char *end, T fn) {
+ // Skip trailing spaces and tabs.
+ while (beg < end && is_space_or_tab(end[-1])) {
+ end--;
+ }
+
+ auto p = beg;
+ while (p < end && *p != ':') {
+ p++;
+ }
+
+ if (p == end) { return false; }
+
+ auto key_end = p;
+
+ if (*p++ != ':') { return false; }
+
+ while (p < end && is_space_or_tab(*p)) {
+ p++;
+ }
+
+ if (p < end) {
+ fn(std::string(beg, key_end), decode_url(std::string(p, end), false));
+ return true;
+ }
+
+ return false;
+}
+
+inline bool read_headers(Stream &strm, Headers &headers) {
+ const auto bufsiz = 2048;
+ char buf[bufsiz];
+ stream_line_reader line_reader(strm, buf, bufsiz);
+
+ for (;;) {
+ if (!line_reader.getline()) { return false; }
+
+ // Check if the line ends with CRLF.
+ if (line_reader.end_with_crlf()) {
+ // Blank line indicates end of headers.
+ if (line_reader.size() == 2) { break; }
+ } else {
+ continue; // Skip invalid line.
+ }
+
+ // Exclude CRLF
+ auto end = line_reader.ptr() + line_reader.size() - 2;
+
+ parse_header(line_reader.ptr(), end,
+ [&](std::string &&key, std::string &&val) {
+ headers.emplace(std::move(key), std::move(val));
+ });
+ }
+
+ return true;
+}
+
+inline bool read_content_with_length(Stream &strm, uint64_t len,
+ Progress progress,
+ ContentReceiverWithProgress out) {
+ char buf[CPPHTTPLIB_RECV_BUFSIZ];
+
+ uint64_t r = 0;
+ while (r < len) {
+ auto read_len = static_cast<size_t>(len - r);
+ auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
+ if (n <= 0) { return false; }
+
+ if (!out(buf, static_cast<size_t>(n), r, len)) { return false; }
+ r += static_cast<uint64_t>(n);
+
+ if (progress) {
+ if (!progress(r, len)) { return false; }
+ }
+ }
+
+ return true;
+}
+
+inline void skip_content_with_length(Stream &strm, uint64_t len) {
+ char buf[CPPHTTPLIB_RECV_BUFSIZ];
+ uint64_t r = 0;
+ while (r < len) {
+ auto read_len = static_cast<size_t>(len - r);
+ auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ));
+ if (n <= 0) { return; }
+ r += static_cast<uint64_t>(n);
+ }
+}
+
+inline bool read_content_without_length(Stream &strm,
+ ContentReceiverWithProgress out) {
+ char buf[CPPHTTPLIB_RECV_BUFSIZ];
+ uint64_t r = 0;
+ for (;;) {
+ auto n = strm.read(buf, CPPHTTPLIB_RECV_BUFSIZ);
+ if (n < 0) {
+ return false;
+ } else if (n == 0) {
+ return true;
+ }
+
+ if (!out(buf, static_cast<size_t>(n), r, 0)) { return false; }
+ r += static_cast<uint64_t>(n);
+ }
+
+ return true;
+}
+
+inline bool read_content_chunked(Stream &strm,
+ ContentReceiverWithProgress out) {
+ const auto bufsiz = 16;
+ char buf[bufsiz];
+
+ stream_line_reader line_reader(strm, buf, bufsiz);
+
+ if (!line_reader.getline()) { return false; }
+
+ unsigned long chunk_len;
+ while (true) {
+ char *end_ptr;
+
+ chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16);
+
+ if (end_ptr == line_reader.ptr()) { return false; }
+ if (chunk_len == ULONG_MAX) { return false; }
+
+ if (chunk_len == 0) { break; }
+
+ if (!read_content_with_length(strm, chunk_len, nullptr, out)) {
+ return false;
+ }
+
+ if (!line_reader.getline()) { return false; }
+
+ if (strcmp(line_reader.ptr(), "\r\n")) { break; }
+
+ if (!line_reader.getline()) { return false; }
+ }
+
+ if (chunk_len == 0) {
+ // Reader terminator after chunks
+ if (!line_reader.getline() || strcmp(line_reader.ptr(), "\r\n"))
+ return false;
+ }
+
+ return true;
+}
+
+inline bool is_chunked_transfer_encoding(const Headers &headers) {
+ return !strcasecmp(get_header_value(headers, "Transfer-Encoding", 0, ""),
+ "chunked");
+}
+
+template <typename T, typename U>
+bool prepare_content_receiver(T &x, int &status,
+ ContentReceiverWithProgress receiver,
+ bool decompress, U callback) {
+ if (decompress) {
+ std::string encoding = x.get_header_value("Content-Encoding");
+ std::unique_ptr<decompressor> decompressor;
+
+ if (encoding.find("gzip") != std::string::npos ||
+ encoding.find("deflate") != std::string::npos) {
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+ decompressor = detail::make_unique<gzip_decompressor>();
+#else
+ status = 415;
+ return false;
+#endif
+ } else if (encoding.find("br") != std::string::npos) {
+#ifdef CPPHTTPLIB_BROTLI_SUPPORT
+ decompressor = detail::make_unique<brotli_decompressor>();
+#else
+ status = 415;
+ return false;
+#endif
+ }
+
+ if (decompressor) {
+ if (decompressor->is_valid()) {
+ ContentReceiverWithProgress out = [&](const char *buf, size_t n,
+ uint64_t off, uint64_t len) {
+ return decompressor->decompress(buf, n,
+ [&](const char *buf2, size_t n2) {
+ return receiver(buf2, n2, off, len);
+ });
+ };
+ return callback(std::move(out));
+ } else {
+ status = 500;
+ return false;
+ }
+ }
+ }
+
+ ContentReceiverWithProgress out = [&](const char *buf, size_t n, uint64_t off,
+ uint64_t len) {
+ return receiver(buf, n, off, len);
+ };
+ return callback(std::move(out));
+}
+
+template <typename T>
+bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status,
+ Progress progress, ContentReceiverWithProgress receiver,
+ bool decompress) {
+ return prepare_content_receiver(
+ x, status, std::move(receiver), decompress,
+ [&](const ContentReceiverWithProgress &out) {
+ auto ret = true;
+ auto exceed_payload_max_length = false;
+
+ if (is_chunked_transfer_encoding(x.headers)) {
+ ret = read_content_chunked(strm, out);
+ } else if (!has_header(x.headers, "Content-Length")) {
+ ret = read_content_without_length(strm, out);
+ } else {
+ auto len = get_header_value<uint64_t>(x.headers, "Content-Length");
+ if (len > payload_max_length) {
+ exceed_payload_max_length = true;
+ skip_content_with_length(strm, len);
+ ret = false;
+ } else if (len > 0) {
+ ret = read_content_with_length(strm, len, std::move(progress), out);
+ }
+ }
+
+ if (!ret) { status = exceed_payload_max_length ? 413 : 400; }
+ return ret;
+ });
+}
+
+inline ssize_t write_headers(Stream &strm, const Headers &headers) {
+ ssize_t write_len = 0;
+ for (const auto &x : headers) {
+ auto len =
+ strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str());
+ if (len < 0) { return len; }
+ write_len += len;
+ }
+ auto len = strm.write("\r\n");
+ if (len < 0) { return len; }
+ write_len += len;
+ return write_len;
+}
+
+inline bool write_data(Stream &strm, const char *d, size_t l) {
+ size_t offset = 0;
+ while (offset < l) {
+ auto length = strm.write(d + offset, l - offset);
+ if (length < 0) { return false; }
+ offset += static_cast<size_t>(length);
+ }
+ return true;
+}
+
+template <typename T>
+inline bool write_content(Stream &strm, const ContentProvider &content_provider,
+ size_t offset, size_t length, T is_shutting_down,
+ Error &error) {
+ size_t end_offset = offset + length;
+ auto ok = true;
+ DataSink data_sink;
+
+ data_sink.write = [&](const char *d, size_t l) -> bool {
+ if (ok) {
+ if (write_data(strm, d, l)) {
+ offset += l;
+ } else {
+ ok = false;
+ }
+ }
+ return ok;
+ };
+
+ data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
+
+ while (offset < end_offset && !is_shutting_down()) {
+ if (!content_provider(offset, end_offset - offset, data_sink)) {
+ error = Error::Canceled;
+ return false;
+ }
+ if (!ok) {
+ error = Error::Write;
+ return false;
+ }
+ }
+
+ error = Error::Success;
+ return true;
+}
+
+template <typename T>
+inline bool write_content(Stream &strm, const ContentProvider &content_provider,
+ size_t offset, size_t length,
+ const T &is_shutting_down) {
+ auto error = Error::Success;
+ return write_content(strm, content_provider, offset, length, is_shutting_down,
+ error);
+}
+
+template <typename T>
+inline bool
+write_content_without_length(Stream &strm,
+ const ContentProvider &content_provider,
+ const T &is_shutting_down) {
+ size_t offset = 0;
+ auto data_available = true;
+ auto ok = true;
+ DataSink data_sink;
+
+ data_sink.write = [&](const char *d, size_t l) -> bool {
+ if (ok) {
+ offset += l;
+ if (!write_data(strm, d, l)) { ok = false; }
+ }
+ return ok;
+ };
+
+ data_sink.done = [&](void) { data_available = false; };
+
+ data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
+
+ while (data_available && !is_shutting_down()) {
+ if (!content_provider(offset, 0, data_sink)) { return false; }
+ if (!ok) { return false; }
+ }
+ return true;
+}
+
+template <typename T, typename U>
+inline bool
+write_content_chunked(Stream &strm, const ContentProvider &content_provider,
+ const T &is_shutting_down, U &compressor, Error &error) {
+ size_t offset = 0;
+ auto data_available = true;
+ auto ok = true;
+ DataSink data_sink;
+
+ data_sink.write = [&](const char *d, size_t l) -> bool {
+ if (ok) {
+ data_available = l > 0;
+ offset += l;
+
+ std::string payload;
+ if (compressor.compress(d, l, false,
+ [&](const char *data, size_t data_len) {
+ payload.append(data, data_len);
+ return true;
+ })) {
+ if (!payload.empty()) {
+ // Emit chunked response header and footer for each chunk
+ auto chunk =
+ from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
+ if (!write_data(strm, chunk.data(), chunk.size())) { ok = false; }
+ }
+ } else {
+ ok = false;
+ }
+ }
+ return ok;
+ };
+
+ data_sink.done = [&](void) {
+ if (!ok) { return; }
+
+ data_available = false;
+
+ std::string payload;
+ if (!compressor.compress(nullptr, 0, true,
+ [&](const char *data, size_t data_len) {
+ payload.append(data, data_len);
+ return true;
+ })) {
+ ok = false;
+ return;
+ }
+
+ if (!payload.empty()) {
+ // Emit chunked response header and footer for each chunk
+ auto chunk = from_i_to_hex(payload.size()) + "\r\n" + payload + "\r\n";
+ if (!write_data(strm, chunk.data(), chunk.size())) {
+ ok = false;
+ return;
+ }
+ }
+
+ static const std::string done_marker("0\r\n\r\n");
+ if (!write_data(strm, done_marker.data(), done_marker.size())) {
+ ok = false;
+ }
+ };
+
+ data_sink.is_writable = [&](void) { return ok && strm.is_writable(); };
+
+ while (data_available && !is_shutting_down()) {
+ if (!content_provider(offset, 0, data_sink)) {
+ error = Error::Canceled;
+ return false;
+ }
+ if (!ok) {
+ error = Error::Write;
+ return false;
+ }
+ }
+
+ error = Error::Success;
+ return true;
+}
+
+template <typename T, typename U>
+inline bool write_content_chunked(Stream &strm,
+ const ContentProvider &content_provider,
+ const T &is_shutting_down, U &compressor) {
+ auto error = Error::Success;
+ return write_content_chunked(strm, content_provider, is_shutting_down,
+ compressor, error);
+}
+
+template <typename T>
+inline bool redirect(T &cli, Request &req, Response &res,
+ const std::string &path, const std::string &location,
+ Error &error) {
+ Request new_req = req;
+ new_req.path = path;
+ new_req.redirect_count_ -= 1;
+
+ if (res.status == 303 && (req.method != "GET" && req.method != "HEAD")) {
+ new_req.method = "GET";
+ new_req.body.clear();
+ new_req.headers.clear();
+ }
+
+ Response new_res;
+
+ auto ret = cli.send(new_req, new_res, error);
+ if (ret) {
+ req = new_req;
+ res = new_res;
+ res.location = location;
+ }
+ return ret;
+}
+
+inline std::string params_to_query_str(const Params &params) {
+ std::string query;
+
+ for (auto it = params.begin(); it != params.end(); ++it) {
+ if (it != params.begin()) { query += "&"; }
+ query += it->first;
+ query += "=";
+ query += encode_query_param(it->second);
+ }
+ return query;
+}
+
+inline std::string append_query_params(const char *path, const Params &params) {
+ std::string path_with_query = path;
+ const static std::regex re("[^?]+\\?.*");
+ auto delm = std::regex_match(path, re) ? '&' : '?';
+ path_with_query += delm + params_to_query_str(params);
+ return path_with_query;
+}
+
+inline void parse_query_text(const std::string &s, Params &params) {
+ std::set<std::string> cache;
+ split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) {
+ std::string kv(b, e);
+ if (cache.find(kv) != cache.end()) { return; }
+ cache.insert(kv);
+
+ std::string key;
+ std::string val;
+ split(b, e, '=', [&](const char *b2, const char *e2) {
+ if (key.empty()) {
+ key.assign(b2, e2);
+ } else {
+ val.assign(b2, e2);
+ }
+ });
+
+ if (!key.empty()) {
+ params.emplace(decode_url(key, true), decode_url(val, true));
+ }
+ });
+}
+
+inline bool parse_multipart_boundary(const std::string &content_type,
+ std::string &boundary) {
+ auto pos = content_type.find("boundary=");
+ if (pos == std::string::npos) { return false; }
+ boundary = content_type.substr(pos + 9);
+ if (boundary.length() >= 2 && boundary.front() == '"' &&
+ boundary.back() == '"') {
+ boundary = boundary.substr(1, boundary.size() - 2);
+ }
+ return !boundary.empty();
+}
+
+inline bool parse_range_header(const std::string &s, Ranges &ranges) try {
+ static auto re_first_range = std::regex(R"(bytes=(\d*-\d*(?:,\s*\d*-\d*)*))");
+ std::smatch m;
+ if (std::regex_match(s, m, re_first_range)) {
+ auto pos = static_cast<size_t>(m.position(1));
+ auto len = static_cast<size_t>(m.length(1));
+ bool all_valid_ranges = true;
+ split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) {
+ if (!all_valid_ranges) return;
+ static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))");
+ std::cmatch cm;
+ if (std::regex_match(b, e, cm, re_another_range)) {
+ ssize_t first = -1;
+ if (!cm.str(1).empty()) {
+ first = static_cast<ssize_t>(std::stoll(cm.str(1)));
+ }
+
+ ssize_t last = -1;
+ if (!cm.str(2).empty()) {
+ last = static_cast<ssize_t>(std::stoll(cm.str(2)));
+ }
+
+ if (first != -1 && last != -1 && first > last) {
+ all_valid_ranges = false;
+ return;
+ }
+ ranges.emplace_back(std::make_pair(first, last));
+ }
+ });
+ return all_valid_ranges;
+ }
+ return false;
+} catch (...) { return false; }
+
+class MultipartFormDataParser {
+public:
+ MultipartFormDataParser() = default;
+
+ void set_boundary(std::string &&boundary) { boundary_ = boundary; }
+
+ bool is_valid() const { return is_valid_; }
+
+ bool parse(const char *buf, size_t n, const ContentReceiver &content_callback,
+ const MultipartContentHeader &header_callback) {
+
+ static const std::regex re_content_disposition(
+ "^Content-Disposition:\\s*form-data;\\s*name=\"(.*?)\"(?:;\\s*filename="
+ "\"(.*?)\")?\\s*$",
+ std::regex_constants::icase);
+ static const std::string dash_ = "--";
+ static const std::string crlf_ = "\r\n";
+
+ buf_.append(buf, n); // TODO: performance improvement
+
+ while (!buf_.empty()) {
+ switch (state_) {
+ case 0: { // Initial boundary
+ auto pattern = dash_ + boundary_ + crlf_;
+ if (pattern.size() > buf_.size()) { return true; }
+ auto pos = buf_.find(pattern);
+ if (pos != 0) { return false; }
+ buf_.erase(0, pattern.size());
+ off_ += pattern.size();
+ state_ = 1;
+ break;
+ }
+ case 1: { // New entry
+ clear_file_info();
+ state_ = 2;
+ break;
+ }
+ case 2: { // Headers
+ auto pos = buf_.find(crlf_);
+ while (pos != std::string::npos) {
+ // Empty line
+ if (pos == 0) {
+ if (!header_callback(file_)) {
+ is_valid_ = false;
+ return false;
+ }
+ buf_.erase(0, crlf_.size());
+ off_ += crlf_.size();
+ state_ = 3;
+ break;
+ }
+
+ static const std::string header_name = "content-type:";
+ const auto header = buf_.substr(0, pos);
+ if (start_with_case_ignore(header, header_name)) {
+ file_.content_type = trim_copy(header.substr(header_name.size()));
+ } else {
+ std::smatch m;
+ if (std::regex_match(header, m, re_content_disposition)) {
+ file_.name = m[1];
+ file_.filename = m[2];
+ }
+ }
+
+ buf_.erase(0, pos + crlf_.size());
+ off_ += pos + crlf_.size();
+ pos = buf_.find(crlf_);
+ }
+ if (state_ != 3) { return true; }
+ break;
+ }
+ case 3: { // Body
+ {
+ auto pattern = crlf_ + dash_;
+ if (pattern.size() > buf_.size()) { return true; }
+
+ auto pos = find_string(buf_, pattern);
+
+ if (!content_callback(buf_.data(), pos)) {
+ is_valid_ = false;
+ return false;
+ }
+
+ off_ += pos;
+ buf_.erase(0, pos);
+ }
+ {
+ auto pattern = crlf_ + dash_ + boundary_;
+ if (pattern.size() > buf_.size()) { return true; }
+
+ auto pos = buf_.find(pattern);
+ if (pos != std::string::npos) {
+ if (!content_callback(buf_.data(), pos)) {
+ is_valid_ = false;
+ return false;
+ }
+
+ off_ += pos + pattern.size();
+ buf_.erase(0, pos + pattern.size());
+ state_ = 4;
+ } else {
+ if (!content_callback(buf_.data(), pattern.size())) {
+ is_valid_ = false;
+ return false;
+ }
+
+ off_ += pattern.size();
+ buf_.erase(0, pattern.size());
+ }
+ }
+ break;
+ }
+ case 4: { // Boundary
+ if (crlf_.size() > buf_.size()) { return true; }
+ if (buf_.compare(0, crlf_.size(), crlf_) == 0) {
+ buf_.erase(0, crlf_.size());
+ off_ += crlf_.size();
+ state_ = 1;
+ } else {
+ auto pattern = dash_ + crlf_;
+ if (pattern.size() > buf_.size()) { return true; }
+ if (buf_.compare(0, pattern.size(), pattern) == 0) {
+ buf_.erase(0, pattern.size());
+ off_ += pattern.size();
+ is_valid_ = true;
+ state_ = 5;
+ } else {
+ return true;
+ }
+ }
+ break;
+ }
+ case 5: { // Done
+ is_valid_ = false;
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+private:
+ void clear_file_info() {
+ file_.name.clear();
+ file_.filename.clear();
+ file_.content_type.clear();
+ }
+
+ bool start_with_case_ignore(const std::string &a,
+ const std::string &b) const {
+ if (a.size() < b.size()) { return false; }
+ for (size_t i = 0; i < b.size(); i++) {
+ if (::tolower(a[i]) != ::tolower(b[i])) { return false; }
+ }
+ return true;
+ }
+
+ bool start_with(const std::string &a, size_t off,
+ const std::string &b) const {
+ if (a.size() - off < b.size()) { return false; }
+ for (size_t i = 0; i < b.size(); i++) {
+ if (a[i + off] != b[i]) { return false; }
+ }
+ return true;
+ }
+
+ size_t find_string(const std::string &s, const std::string &pattern) const {
+ auto c = pattern.front();
+
+ size_t off = 0;
+ while (off < s.size()) {
+ auto pos = s.find(c, off);
+ if (pos == std::string::npos) { return s.size(); }
+
+ auto rem = s.size() - pos;
+ if (pattern.size() > rem) { return pos; }
+
+ if (start_with(s, pos, pattern)) { return pos; }
+
+ off = pos + 1;
+ }
+
+ return s.size();
+ }
+
+ std::string boundary_;
+
+ std::string buf_;
+ size_t state_ = 0;
+ bool is_valid_ = false;
+ size_t off_ = 0;
+ MultipartFormData file_;
+};
+
+inline std::string to_lower(const char *beg, const char *end) {
+ std::string out;
+ auto it = beg;
+ while (it != end) {
+ out += static_cast<char>(::tolower(*it));
+ it++;
+ }
+ return out;
+}
+
+inline std::string make_multipart_data_boundary() {
+ static const char data[] =
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
+
+ // std::random_device might actually be deterministic on some
+ // platforms, but due to lack of support in the c++ standard library,
+ // doing better requires either some ugly hacks or breaking portability.
+ std::random_device seed_gen;
+ // Request 128 bits of entropy for initialization
+ std::seed_seq seed_sequence{seed_gen(), seed_gen(), seed_gen(), seed_gen()};
+ std::mt19937 engine(seed_sequence);
+
+ std::string result = "--cpp-httplib-multipart-data-";
+
+ for (auto i = 0; i < 16; i++) {
+ result += data[engine() % (sizeof(data) - 1)];
+ }
+
+ return result;
+}
+
+inline std::pair<size_t, size_t>
+get_range_offset_and_length(const Request &req, size_t content_length,
+ size_t index) {
+ auto r = req.ranges[index];
+
+ if (r.first == -1 && r.second == -1) {
+ return std::make_pair(0, content_length);
+ }
+
+ auto slen = static_cast<ssize_t>(content_length);
+
+ if (r.first == -1) {
+ r.first = (std::max)(static_cast<ssize_t>(0), slen - r.second);
+ r.second = slen - 1;
+ }
+
+ if (r.second == -1) { r.second = slen - 1; }
+ return std::make_pair(r.first, static_cast<size_t>(r.second - r.first) + 1);
+}
+
+inline std::string make_content_range_header_field(size_t offset, size_t length,
+ size_t content_length) {
+ std::string field = "bytes ";
+ field += std::to_string(offset);
+ field += "-";
+ field += std::to_string(offset + length - 1);
+ field += "/";
+ field += std::to_string(content_length);
+ return field;
+}
+
+template <typename SToken, typename CToken, typename Content>
+bool process_multipart_ranges_data(const Request &req, Response &res,
+ const std::string &boundary,
+ const std::string &content_type,
+ SToken stoken, CToken ctoken,
+ Content content) {
+ for (size_t i = 0; i < req.ranges.size(); i++) {
+ ctoken("--");
+ stoken(boundary);
+ ctoken("\r\n");
+ if (!content_type.empty()) {
+ ctoken("Content-Type: ");
+ stoken(content_type);
+ ctoken("\r\n");
+ }
+
+ auto offsets = get_range_offset_and_length(req, res.body.size(), i);
+ auto offset = offsets.first;
+ auto length = offsets.second;
+
+ ctoken("Content-Range: ");
+ stoken(make_content_range_header_field(offset, length, res.body.size()));
+ ctoken("\r\n");
+ ctoken("\r\n");
+ if (!content(offset, length)) { return false; }
+ ctoken("\r\n");
+ }
+
+ ctoken("--");
+ stoken(boundary);
+ ctoken("--\r\n");
+
+ return true;
+}
+
+inline bool make_multipart_ranges_data(const Request &req, Response &res,
+ const std::string &boundary,
+ const std::string &content_type,
+ std::string &data) {
+ return process_multipart_ranges_data(
+ req, res, boundary, content_type,
+ [&](const std::string &token) { data += token; },
+ [&](const char *token) { data += token; },
+ [&](size_t offset, size_t length) {
+ if (offset < res.body.size()) {
+ data += res.body.substr(offset, length);
+ return true;
+ }
+ return false;
+ });
+}
+
+inline size_t
+get_multipart_ranges_data_length(const Request &req, Response &res,
+ const std::string &boundary,
+ const std::string &content_type) {
+ size_t data_length = 0;
+
+ process_multipart_ranges_data(
+ req, res, boundary, content_type,
+ [&](const std::string &token) { data_length += token.size(); },
+ [&](const char *token) { data_length += strlen(token); },
+ [&](size_t /*offset*/, size_t length) {
+ data_length += length;
+ return true;
+ });
+
+ return data_length;
+}
+
+template <typename T>
+inline bool write_multipart_ranges_data(Stream &strm, const Request &req,
+ Response &res,
+ const std::string &boundary,
+ const std::string &content_type,
+ const T &is_shutting_down) {
+ return process_multipart_ranges_data(
+ req, res, boundary, content_type,
+ [&](const std::string &token) { strm.write(token); },
+ [&](const char *token) { strm.write(token); },
+ [&](size_t offset, size_t length) {
+ return write_content(strm, res.content_provider_, offset, length,
+ is_shutting_down);
+ });
+}
+
+inline std::pair<size_t, size_t>
+get_range_offset_and_length(const Request &req, const Response &res,
+ size_t index) {
+ auto r = req.ranges[index];
+
+ if (r.second == -1) {
+ r.second = static_cast<ssize_t>(res.content_length_) - 1;
+ }
+
+ return std::make_pair(r.first, r.second - r.first + 1);
+}
+
+inline bool expect_content(const Request &req) {
+ if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH" ||
+ req.method == "PRI" || req.method == "DELETE") {
+ return true;
+ }
+ // TODO: check if Content-Length is set
+ return false;
+}
+
+inline bool has_crlf(const char *s) {
+ auto p = s;
+ while (*p) {
+ if (*p == '\r' || *p == '\n') { return true; }
+ p++;
+ }
+ return false;
+}
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+template <typename CTX, typename Init, typename Update, typename Final>
+inline std::string message_digest(const std::string &s, Init init,
+ Update update, Final final,
+ size_t digest_length) {
+ using namespace std;
+
+ std::vector<unsigned char> md(digest_length, 0);
+ CTX ctx;
+ init(&ctx);
+ update(&ctx, s.data(), s.size());
+ final(md.data(), &ctx);
+
+ stringstream ss;
+ for (auto c : md) {
+ ss << setfill('0') << setw(2) << hex << (unsigned int)c;
+ }
+ return ss.str();
+}
+
+inline std::string MD5(const std::string &s) {
+ return message_digest<MD5_CTX>(s, MD5_Init, MD5_Update, MD5_Final,
+ MD5_DIGEST_LENGTH);
+}
+
+inline std::string SHA_256(const std::string &s) {
+ return message_digest<SHA256_CTX>(s, SHA256_Init, SHA256_Update, SHA256_Final,
+ SHA256_DIGEST_LENGTH);
+}
+
+inline std::string SHA_512(const std::string &s) {
+ return message_digest<SHA512_CTX>(s, SHA512_Init, SHA512_Update, SHA512_Final,
+ SHA512_DIGEST_LENGTH);
+}
+#endif
+
+#ifdef _WIN32
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+// NOTE: This code came up with the following stackoverflow post:
+// https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store
+inline bool load_system_certs_on_windows(X509_STORE *store) {
+ auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT");
+
+ if (!hStore) { return false; }
+
+ PCCERT_CONTEXT pContext = NULL;
+ while ((pContext = CertEnumCertificatesInStore(hStore, pContext)) !=
+ nullptr) {
+ auto encoded_cert =
+ static_cast<const unsigned char *>(pContext->pbCertEncoded);
+
+ auto x509 = d2i_X509(NULL, &encoded_cert, pContext->cbCertEncoded);
+ if (x509) {
+ X509_STORE_add_cert(store, x509);
+ X509_free(x509);
+ }
+ }
+
+ CertFreeCertificateContext(pContext);
+ CertCloseStore(hStore, 0);
+
+ return true;
+}
+#endif
+
+class WSInit {
+public:
+ WSInit() {
+ WSADATA wsaData;
+ WSAStartup(0x0002, &wsaData);
+ }
+
+ ~WSInit() { WSACleanup(); }
+};
+
+static WSInit wsinit_;
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline std::pair<std::string, std::string> make_digest_authentication_header(
+ const Request &req, const std::map<std::string, std::string> &auth,
+ size_t cnonce_count, const std::string &cnonce, const std::string &username,
+ const std::string &password, bool is_proxy = false) {
+ using namespace std;
+
+ string nc;
+ {
+ stringstream ss;
+ ss << setfill('0') << setw(8) << hex << cnonce_count;
+ nc = ss.str();
+ }
+
+ auto qop = auth.at("qop");
+ if (qop.find("auth-int") != std::string::npos) {
+ qop = "auth-int";
+ } else {
+ qop = "auth";
+ }
+
+ std::string algo = "MD5";
+ if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); }
+
+ string response;
+ {
+ auto H = algo == "SHA-256"
+ ? detail::SHA_256
+ : algo == "SHA-512" ? detail::SHA_512 : detail::MD5;
+
+ auto A1 = username + ":" + auth.at("realm") + ":" + password;
+
+ auto A2 = req.method + ":" + req.path;
+ if (qop == "auth-int") { A2 += ":" + H(req.body); }
+
+ response = H(H(A1) + ":" + auth.at("nonce") + ":" + nc + ":" + cnonce +
+ ":" + qop + ":" + H(A2));
+ }
+
+ auto field = "Digest username=\"" + username + "\", realm=\"" +
+ auth.at("realm") + "\", nonce=\"" + auth.at("nonce") +
+ "\", uri=\"" + req.path + "\", algorithm=" + algo +
+ ", qop=" + qop + ", nc=\"" + nc + "\", cnonce=\"" + cnonce +
+ "\", response=\"" + response + "\"";
+
+ auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
+ return std::make_pair(key, field);
+}
+#endif
+
+inline bool parse_www_authenticate(const Response &res,
+ std::map<std::string, std::string> &auth,
+ bool is_proxy) {
+ auto auth_key = is_proxy ? "Proxy-Authenticate" : "WWW-Authenticate";
+ if (res.has_header(auth_key)) {
+ static auto re = std::regex(R"~((?:(?:,\s*)?(.+?)=(?:"(.*?)"|([^,]*))))~");
+ auto s = res.get_header_value(auth_key);
+ auto pos = s.find(' ');
+ if (pos != std::string::npos) {
+ auto type = s.substr(0, pos);
+ if (type == "Basic") {
+ return false;
+ } else if (type == "Digest") {
+ s = s.substr(pos + 1);
+ auto beg = std::sregex_iterator(s.begin(), s.end(), re);
+ for (auto i = beg; i != std::sregex_iterator(); ++i) {
+ auto m = *i;
+ auto key = s.substr(static_cast<size_t>(m.position(1)),
+ static_cast<size_t>(m.length(1)));
+ auto val = m.length(2) > 0
+ ? s.substr(static_cast<size_t>(m.position(2)),
+ static_cast<size_t>(m.length(2)))
+ : s.substr(static_cast<size_t>(m.position(3)),
+ static_cast<size_t>(m.length(3)));
+ auth[key] = val;
+ }
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+// https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c/440240#answer-440240
+inline std::string random_string(size_t length) {
+ auto randchar = []() -> char {
+ const char charset[] = "0123456789"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz";
+ const size_t max_index = (sizeof(charset) - 1);
+ return charset[static_cast<size_t>(std::rand()) % max_index];
+ };
+ std::string str(length, 0);
+ std::generate_n(str.begin(), length, randchar);
+ return str;
+}
+
+class ContentProviderAdapter {
+public:
+ explicit ContentProviderAdapter(
+ ContentProviderWithoutLength &&content_provider)
+ : content_provider_(content_provider) {}
+
+ bool operator()(size_t offset, size_t, DataSink &sink) {
+ return content_provider_(offset, sink);
+ }
+
+private:
+ ContentProviderWithoutLength content_provider_;
+};
+
+} // namespace detail
+
+// Header utilities
+inline std::pair<std::string, std::string> make_range_header(Ranges ranges) {
+ std::string field = "bytes=";
+ auto i = 0;
+ for (auto r : ranges) {
+ if (i != 0) { field += ", "; }
+ if (r.first != -1) { field += std::to_string(r.first); }
+ field += '-';
+ if (r.second != -1) { field += std::to_string(r.second); }
+ i++;
+ }
+ return std::make_pair("Range", std::move(field));
+}
+
+inline std::pair<std::string, std::string>
+make_basic_authentication_header(const std::string &username,
+ const std::string &password, bool is_proxy) {
+ auto field = "Basic " + detail::base64_encode(username + ":" + password);
+ auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
+ return std::make_pair(key, std::move(field));
+}
+
+inline std::pair<std::string, std::string>
+make_bearer_token_authentication_header(const std::string &token,
+ bool is_proxy = false) {
+ auto field = "Bearer " + token;
+ auto key = is_proxy ? "Proxy-Authorization" : "Authorization";
+ return std::make_pair(key, std::move(field));
+}
+
+// Request implementation
+inline bool Request::has_header(const char *key) const {
+ return detail::has_header(headers, key);
+}
+
+inline std::string Request::get_header_value(const char *key, size_t id) const {
+ return detail::get_header_value(headers, key, id, "");
+}
+
+inline size_t Request::get_header_value_count(const char *key) const {
+ auto r = headers.equal_range(key);
+ return static_cast<size_t>(std::distance(r.first, r.second));
+}
+
+inline void Request::set_header(const char *key, const char *val) {
+ if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
+ headers.emplace(key, val);
+ }
+}
+
+inline void Request::set_header(const char *key, const std::string &val) {
+ if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
+ headers.emplace(key, val);
+ }
+}
+
+inline bool Request::has_param(const char *key) const {
+ return params.find(key) != params.end();
+}
+
+inline std::string Request::get_param_value(const char *key, size_t id) const {
+ auto rng = params.equal_range(key);
+ auto it = rng.first;
+ std::advance(it, static_cast<ssize_t>(id));
+ if (it != rng.second) { return it->second; }
+ return std::string();
+}
+
+inline size_t Request::get_param_value_count(const char *key) const {
+ auto r = params.equal_range(key);
+ return static_cast<size_t>(std::distance(r.first, r.second));
+}
+
+inline bool Request::is_multipart_form_data() const {
+ const auto &content_type = get_header_value("Content-Type");
+ return !content_type.find("multipart/form-data");
+}
+
+inline bool Request::has_file(const char *key) const {
+ return files.find(key) != files.end();
+}
+
+inline MultipartFormData Request::get_file_value(const char *key) const {
+ auto it = files.find(key);
+ if (it != files.end()) { return it->second; }
+ return MultipartFormData();
+}
+
+// Response implementation
+inline bool Response::has_header(const char *key) const {
+ return headers.find(key) != headers.end();
+}
+
+inline std::string Response::get_header_value(const char *key,
+ size_t id) const {
+ return detail::get_header_value(headers, key, id, "");
+}
+
+inline size_t Response::get_header_value_count(const char *key) const {
+ auto r = headers.equal_range(key);
+ return static_cast<size_t>(std::distance(r.first, r.second));
+}
+
+inline void Response::set_header(const char *key, const char *val) {
+ if (!detail::has_crlf(key) && !detail::has_crlf(val)) {
+ headers.emplace(key, val);
+ }
+}
+
+inline void Response::set_header(const char *key, const std::string &val) {
+ if (!detail::has_crlf(key) && !detail::has_crlf(val.c_str())) {
+ headers.emplace(key, val);
+ }
+}
+
+inline void Response::set_redirect(const char *url, int stat) {
+ if (!detail::has_crlf(url)) {
+ set_header("Location", url);
+ if (300 <= stat && stat < 400) {
+ this->status = stat;
+ } else {
+ this->status = 302;
+ }
+ }
+}
+
+inline void Response::set_redirect(const std::string &url, int stat) {
+ set_redirect(url.c_str(), stat);
+}
+
+inline void Response::set_content(const char *s, size_t n,
+ const char *content_type) {
+ body.assign(s, n);
+
+ auto rng = headers.equal_range("Content-Type");
+ headers.erase(rng.first, rng.second);
+ set_header("Content-Type", content_type);
+}
+
+inline void Response::set_content(const std::string &s,
+ const char *content_type) {
+ set_content(s.data(), s.size(), content_type);
+}
+
+inline void Response::set_content_provider(
+ size_t in_length, const char *content_type, ContentProvider provider,
+ ContentProviderResourceReleaser resource_releaser) {
+ assert(in_length > 0);
+ set_header("Content-Type", content_type);
+ content_length_ = in_length;
+ content_provider_ = std::move(provider);
+ content_provider_resource_releaser_ = resource_releaser;
+ is_chunked_content_provider_ = false;
+}
+
+inline void Response::set_content_provider(
+ const char *content_type, ContentProviderWithoutLength provider,
+ ContentProviderResourceReleaser resource_releaser) {
+ set_header("Content-Type", content_type);
+ content_length_ = 0;
+ content_provider_ = detail::ContentProviderAdapter(std::move(provider));
+ content_provider_resource_releaser_ = resource_releaser;
+ is_chunked_content_provider_ = false;
+}
+
+inline void Response::set_chunked_content_provider(
+ const char *content_type, ContentProviderWithoutLength provider,
+ ContentProviderResourceReleaser resource_releaser) {
+ set_header("Content-Type", content_type);
+ content_length_ = 0;
+ content_provider_ = detail::ContentProviderAdapter(std::move(provider));
+ content_provider_resource_releaser_ = resource_releaser;
+ is_chunked_content_provider_ = true;
+}
+
+// Result implementation
+inline bool Result::has_request_header(const char *key) const {
+ return request_headers_.find(key) != request_headers_.end();
+}
+
+inline std::string Result::get_request_header_value(const char *key,
+ size_t id) const {
+ return detail::get_header_value(request_headers_, key, id, "");
+}
+
+inline size_t Result::get_request_header_value_count(const char *key) const {
+ auto r = request_headers_.equal_range(key);
+ return static_cast<size_t>(std::distance(r.first, r.second));
+}
+
+// Stream implementation
+inline ssize_t Stream::write(const char *ptr) {
+ return write(ptr, strlen(ptr));
+}
+
+inline ssize_t Stream::write(const std::string &s) {
+ return write(s.data(), s.size());
+}
+
+namespace detail {
+
+// Socket stream implementation
+inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec,
+ time_t read_timeout_usec,
+ time_t write_timeout_sec,
+ time_t write_timeout_usec)
+ : sock_(sock), read_timeout_sec_(read_timeout_sec),
+ read_timeout_usec_(read_timeout_usec),
+ write_timeout_sec_(write_timeout_sec),
+ write_timeout_usec_(write_timeout_usec) {}
+
+inline SocketStream::~SocketStream() {}
+
+inline bool SocketStream::is_readable() const {
+ return select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
+}
+
+inline bool SocketStream::is_writable() const {
+ return select_write(sock_, write_timeout_sec_, write_timeout_usec_) > 0;
+}
+
+inline ssize_t SocketStream::read(char *ptr, size_t size) {
+ if (!is_readable()) { return -1; }
+
+#ifdef _WIN32
+ if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
+ return -1;
+ }
+ return recv(sock_, ptr, static_cast<int>(size), CPPHTTPLIB_RECV_FLAGS);
+#else
+ return handle_EINTR(
+ [&]() { return recv(sock_, ptr, size, CPPHTTPLIB_RECV_FLAGS); });
+#endif
+}
+
+inline ssize_t SocketStream::write(const char *ptr, size_t size) {
+ if (!is_writable()) { return -1; }
+
+#ifdef _WIN32
+ if (size > static_cast<size_t>((std::numeric_limits<int>::max)())) {
+ return -1;
+ }
+ return send(sock_, ptr, static_cast<int>(size), CPPHTTPLIB_SEND_FLAGS);
+#else
+ return handle_EINTR(
+ [&]() { return send(sock_, ptr, size, CPPHTTPLIB_SEND_FLAGS); });
+#endif
+}
+
+inline void SocketStream::get_remote_ip_and_port(std::string &ip,
+ int &port) const {
+ return detail::get_remote_ip_and_port(sock_, ip, port);
+}
+
+inline socket_t SocketStream::socket() const { return sock_; }
+
+// Buffer stream implementation
+inline bool BufferStream::is_readable() const { return true; }
+
+inline bool BufferStream::is_writable() const { return true; }
+
+inline ssize_t BufferStream::read(char *ptr, size_t size) {
+#if defined(_MSC_VER) && _MSC_VER <= 1900
+ auto len_read = buffer._Copy_s(ptr, size, size, position);
+#else
+ auto len_read = buffer.copy(ptr, size, position);
+#endif
+ position += static_cast<size_t>(len_read);
+ return static_cast<ssize_t>(len_read);
+}
+
+inline ssize_t BufferStream::write(const char *ptr, size_t size) {
+ buffer.append(ptr, size);
+ return static_cast<ssize_t>(size);
+}
+
+inline void BufferStream::get_remote_ip_and_port(std::string & /*ip*/,
+ int & /*port*/) const {}
+
+inline socket_t BufferStream::socket() const { return 0; }
+
+inline const std::string &BufferStream::get_buffer() const { return buffer; }
+
+} // namespace detail
+
+// HTTP server implementation
+inline Server::Server()
+ : new_task_queue(
+ [] { return new ThreadPool(CPPHTTPLIB_THREAD_POOL_COUNT); }),
+ svr_sock_(INVALID_SOCKET), is_running_(false) {
+#ifndef _WIN32
+ signal(SIGPIPE, SIG_IGN);
+#endif
+}
+
+inline Server::~Server() {}
+
+inline Server &Server::Get(const std::string &pattern, Handler handler) {
+ get_handlers_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Post(const std::string &pattern, Handler handler) {
+ post_handlers_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Post(const std::string &pattern,
+ HandlerWithContentReader handler) {
+ post_handlers_for_content_reader_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Put(const std::string &pattern, Handler handler) {
+ put_handlers_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Put(const std::string &pattern,
+ HandlerWithContentReader handler) {
+ put_handlers_for_content_reader_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Patch(const std::string &pattern, Handler handler) {
+ patch_handlers_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Patch(const std::string &pattern,
+ HandlerWithContentReader handler) {
+ patch_handlers_for_content_reader_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Delete(const std::string &pattern, Handler handler) {
+ delete_handlers_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Delete(const std::string &pattern,
+ HandlerWithContentReader handler) {
+ delete_handlers_for_content_reader_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline Server &Server::Options(const std::string &pattern, Handler handler) {
+ options_handlers_.push_back(
+ std::make_pair(std::regex(pattern), std::move(handler)));
+ return *this;
+}
+
+inline bool Server::set_base_dir(const std::string &dir,
+ const std::string &mount_point) {
+ return set_mount_point(mount_point, dir);
+}
+
+inline bool Server::set_mount_point(const std::string &mount_point,
+ const std::string &dir, Headers headers) {
+ if (detail::is_dir(dir)) {
+ std::string mnt = !mount_point.empty() ? mount_point : "/";
+ if (!mnt.empty() && mnt[0] == '/') {
+ base_dirs_.push_back({mnt, dir, std::move(headers)});
+ return true;
+ }
+ }
+ return false;
+}
+
+inline bool Server::remove_mount_point(const std::string &mount_point) {
+ for (auto it = base_dirs_.begin(); it != base_dirs_.end(); ++it) {
+ if (it->mount_point == mount_point) {
+ base_dirs_.erase(it);
+ return true;
+ }
+ }
+ return false;
+}
+
+inline Server &
+Server::set_file_extension_and_mimetype_mapping(const char *ext,
+ const char *mime) {
+ file_extension_and_mimetype_map_[ext] = mime;
+ return *this;
+}
+
+inline Server &Server::set_file_request_handler(Handler handler) {
+ file_request_handler_ = std::move(handler);
+ return *this;
+}
+
+inline Server &Server::set_error_handler(HandlerWithResponse handler) {
+ error_handler_ = std::move(handler);
+ return *this;
+}
+
+inline Server &Server::set_error_handler(Handler handler) {
+ error_handler_ = [handler](const Request &req, Response &res) {
+ handler(req, res);
+ return HandlerResponse::Handled;
+ };
+ return *this;
+}
+
+inline Server &Server::set_exception_handler(ExceptionHandler handler) {
+ exception_handler_ = std::move(handler);
+ return *this;
+}
+
+inline Server &Server::set_pre_routing_handler(HandlerWithResponse handler) {
+ pre_routing_handler_ = std::move(handler);
+ return *this;
+}
+
+inline Server &Server::set_post_routing_handler(Handler handler) {
+ post_routing_handler_ = std::move(handler);
+ return *this;
+}
+
+inline Server &Server::set_logger(Logger logger) {
+ logger_ = std::move(logger);
+ return *this;
+}
+
+inline Server &
+Server::set_expect_100_continue_handler(Expect100ContinueHandler handler) {
+ expect_100_continue_handler_ = std::move(handler);
+
+ return *this;
+}
+
+inline Server &Server::set_address_family(int family) {
+ address_family_ = family;
+ return *this;
+}
+
+inline Server &Server::set_tcp_nodelay(bool on) {
+ tcp_nodelay_ = on;
+ return *this;
+}
+
+inline Server &Server::set_socket_options(SocketOptions socket_options) {
+ socket_options_ = std::move(socket_options);
+ return *this;
+}
+
+inline Server &Server::set_default_headers(Headers headers) {
+ default_headers_ = std::move(headers);
+ return *this;
+}
+
+inline Server &Server::set_keep_alive_max_count(size_t count) {
+ keep_alive_max_count_ = count;
+ return *this;
+}
+
+inline Server &Server::set_keep_alive_timeout(time_t sec) {
+ keep_alive_timeout_sec_ = sec;
+ return *this;
+}
+
+inline Server &Server::set_read_timeout(time_t sec, time_t usec) {
+ read_timeout_sec_ = sec;
+ read_timeout_usec_ = usec;
+ return *this;
+}
+
+inline Server &Server::set_write_timeout(time_t sec, time_t usec) {
+ write_timeout_sec_ = sec;
+ write_timeout_usec_ = usec;
+ return *this;
+}
+
+inline Server &Server::set_idle_interval(time_t sec, time_t usec) {
+ idle_interval_sec_ = sec;
+ idle_interval_usec_ = usec;
+ return *this;
+}
+
+inline Server &Server::set_payload_max_length(size_t length) {
+ payload_max_length_ = length;
+ return *this;
+}
+
+inline bool Server::bind_to_port(const char *host, int port, int socket_flags) {
+ if (bind_internal(host, port, socket_flags) < 0) return false;
+ return true;
+}
+inline int Server::bind_to_any_port(const char *host, int socket_flags) {
+ return bind_internal(host, 0, socket_flags);
+}
+
+inline bool Server::listen_after_bind() { return listen_internal(); }
+
+inline bool Server::listen(const char *host, int port, int socket_flags) {
+ return bind_to_port(host, port, socket_flags) && listen_internal();
+}
+
+inline bool Server::is_running() const { return is_running_; }
+
+inline void Server::stop() {
+ if (is_running_) {
+ assert(svr_sock_ != INVALID_SOCKET);
+ std::atomic<socket_t> sock(svr_sock_.exchange(INVALID_SOCKET));
+ detail::shutdown_socket(sock);
+ detail::close_socket(sock);
+ }
+}
+
+inline bool Server::parse_request_line(const char *s, Request &req) {
+ auto len = strlen(s);
+ if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; }
+ len -= 2;
+
+ {
+ size_t count = 0;
+
+ detail::split(s, s + len, ' ', [&](const char *b, const char *e) {
+ switch (count) {
+ case 0: req.method = std::string(b, e); break;
+ case 1: req.target = std::string(b, e); break;
+ case 2: req.version = std::string(b, e); break;
+ default: break;
+ }
+ count++;
+ });
+
+ if (count != 3) { return false; }
+ }
+
+ static const std::set<std::string> methods{
+ "GET", "HEAD", "POST", "PUT", "DELETE",
+ "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
+
+ if (methods.find(req.method) == methods.end()) { return false; }
+
+ if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; }
+
+ {
+ size_t count = 0;
+
+ detail::split(req.target.data(), req.target.data() + req.target.size(), '?',
+ [&](const char *b, const char *e) {
+ switch (count) {
+ case 0:
+ req.path = detail::decode_url(std::string(b, e), false);
+ break;
+ case 1: {
+ if (e - b > 0) {
+ detail::parse_query_text(std::string(b, e), req.params);
+ }
+ break;
+ }
+ default: break;
+ }
+ count++;
+ });
+
+ if (count > 2) { return false; }
+ }
+
+ return true;
+}
+
+inline bool Server::write_response(Stream &strm, bool close_connection,
+ const Request &req, Response &res) {
+ return write_response_core(strm, close_connection, req, res, false);
+}
+
+inline bool Server::write_response_with_content(Stream &strm,
+ bool close_connection,
+ const Request &req,
+ Response &res) {
+ return write_response_core(strm, close_connection, req, res, true);
+}
+
+inline bool Server::write_response_core(Stream &strm, bool close_connection,
+ const Request &req, Response &res,
+ bool need_apply_ranges) {
+ assert(res.status != -1);
+
+ if (400 <= res.status && error_handler_ &&
+ error_handler_(req, res) == HandlerResponse::Handled) {
+ need_apply_ranges = true;
+ }
+
+ std::string content_type;
+ std::string boundary;
+ if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); }
+
+ // Prepare additional headers
+ if (close_connection || req.get_header_value("Connection") == "close") {
+ res.set_header("Connection", "close");
+ } else {
+ std::stringstream ss;
+ ss << "timeout=" << keep_alive_timeout_sec_
+ << ", max=" << keep_alive_max_count_;
+ res.set_header("Keep-Alive", ss.str());
+ }
+
+ if (!res.has_header("Content-Type") &&
+ (!res.body.empty() || res.content_length_ > 0 || res.content_provider_)) {
+ res.set_header("Content-Type", "text/plain");
+ }
+
+ if (!res.has_header("Content-Length") && res.body.empty() &&
+ !res.content_length_ && !res.content_provider_) {
+ res.set_header("Content-Length", "0");
+ }
+
+ if (!res.has_header("Accept-Ranges") && req.method == "HEAD") {
+ res.set_header("Accept-Ranges", "bytes");
+ }
+
+ if (post_routing_handler_) { post_routing_handler_(req, res); }
+
+ // Response line and headers
+ {
+ detail::BufferStream bstrm;
+
+ if (!bstrm.write_format("HTTP/1.1 %d %s\r\n", res.status,
+ detail::status_message(res.status))) {
+ return false;
+ }
+
+ if (!detail::write_headers(bstrm, res.headers)) { return false; }
+
+ // Flush buffer
+ auto &data = bstrm.get_buffer();
+ strm.write(data.data(), data.size());
+ }
+
+ // Body
+ auto ret = true;
+ if (req.method != "HEAD") {
+ if (!res.body.empty()) {
+ if (!strm.write(res.body)) { ret = false; }
+ } else if (res.content_provider_) {
+ if (write_content_with_provider(strm, req, res, boundary, content_type)) {
+ res.content_provider_success_ = true;
+ } else {
+ res.content_provider_success_ = false;
+ ret = false;
+ }
+ }
+ }
+
+ // Log
+ if (logger_) { logger_(req, res); }
+
+ return ret;
+}
+
+inline bool
+Server::write_content_with_provider(Stream &strm, const Request &req,
+ Response &res, const std::string &boundary,
+ const std::string &content_type) {
+ auto is_shutting_down = [this]() {
+ return this->svr_sock_ == INVALID_SOCKET;
+ };
+
+ if (res.content_length_ > 0) {
+ if (req.ranges.empty()) {
+ return detail::write_content(strm, res.content_provider_, 0,
+ res.content_length_, is_shutting_down);
+ } else if (req.ranges.size() == 1) {
+ auto offsets =
+ detail::get_range_offset_and_length(req, res.content_length_, 0);
+ auto offset = offsets.first;
+ auto length = offsets.second;
+ return detail::write_content(strm, res.content_provider_, offset, length,
+ is_shutting_down);
+ } else {
+ return detail::write_multipart_ranges_data(
+ strm, req, res, boundary, content_type, is_shutting_down);
+ }
+ } else {
+ if (res.is_chunked_content_provider_) {
+ auto type = detail::encoding_type(req, res);
+
+ std::unique_ptr<detail::compressor> compressor;
+ if (type == detail::EncodingType::Gzip) {
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+ compressor = detail::make_unique<detail::gzip_compressor>();
+#endif
+ } else if (type == detail::EncodingType::Brotli) {
+#ifdef CPPHTTPLIB_BROTLI_SUPPORT
+ compressor = detail::make_unique<detail::brotli_compressor>();
+#endif
+ } else {
+ compressor = detail::make_unique<detail::nocompressor>();
+ }
+ assert(compressor != nullptr);
+
+ return detail::write_content_chunked(strm, res.content_provider_,
+ is_shutting_down, *compressor);
+ } else {
+ return detail::write_content_without_length(strm, res.content_provider_,
+ is_shutting_down);
+ }
+ }
+}
+
+inline bool Server::read_content(Stream &strm, Request &req, Response &res) {
+ MultipartFormDataMap::iterator cur;
+ if (read_content_core(
+ strm, req, res,
+ // Regular
+ [&](const char *buf, size_t n) {
+ if (req.body.size() + n > req.body.max_size()) { return false; }
+ req.body.append(buf, n);
+ return true;
+ },
+ // Multipart
+ [&](const MultipartFormData &file) {
+ cur = req.files.emplace(file.name, file);
+ return true;
+ },
+ [&](const char *buf, size_t n) {
+ auto &content = cur->second.content;
+ if (content.size() + n > content.max_size()) { return false; }
+ content.append(buf, n);
+ return true;
+ })) {
+ const auto &content_type = req.get_header_value("Content-Type");
+ if (!content_type.find("application/x-www-form-urlencoded")) {
+ detail::parse_query_text(req.body, req.params);
+ }
+ return true;
+ }
+ return false;
+}
+
+inline bool Server::read_content_with_content_receiver(
+ Stream &strm, Request &req, Response &res, ContentReceiver receiver,
+ MultipartContentHeader multipart_header,
+ ContentReceiver multipart_receiver) {
+ return read_content_core(strm, req, res, std::move(receiver),
+ std::move(multipart_header),
+ std::move(multipart_receiver));
+}
+
+inline bool Server::read_content_core(Stream &strm, Request &req, Response &res,
+ ContentReceiver receiver,
+ MultipartContentHeader mulitpart_header,
+ ContentReceiver multipart_receiver) {
+ detail::MultipartFormDataParser multipart_form_data_parser;
+ ContentReceiverWithProgress out;
+
+ if (req.is_multipart_form_data()) {
+ const auto &content_type = req.get_header_value("Content-Type");
+ std::string boundary;
+ if (!detail::parse_multipart_boundary(content_type, boundary)) {
+ res.status = 400;
+ return false;
+ }
+
+ multipart_form_data_parser.set_boundary(std::move(boundary));
+ out = [&](const char *buf, size_t n, uint64_t /*off*/, uint64_t /*len*/) {
+ /* For debug
+ size_t pos = 0;
+ while (pos < n) {
+ auto read_size = std::min<size_t>(1, n - pos);
+ auto ret = multipart_form_data_parser.parse(
+ buf + pos, read_size, multipart_receiver, mulitpart_header);
+ if (!ret) { return false; }
+ pos += read_size;
+ }
+ return true;
+ */
+ return multipart_form_data_parser.parse(buf, n, multipart_receiver,
+ mulitpart_header);
+ };
+ } else {
+ out = [receiver](const char *buf, size_t n, uint64_t /*off*/,
+ uint64_t /*len*/) { return receiver(buf, n); };
+ }
+
+ if (req.method == "DELETE" && !req.has_header("Content-Length")) {
+ return true;
+ }
+
+ if (!detail::read_content(strm, req, payload_max_length_, res.status, nullptr,
+ out, true)) {
+ return false;
+ }
+
+ if (req.is_multipart_form_data()) {
+ if (!multipart_form_data_parser.is_valid()) {
+ res.status = 400;
+ return false;
+ }
+ }
+
+ return true;
+}
+
+inline bool Server::handle_file_request(const Request &req, Response &res,
+ bool head) {
+ for (const auto &entry : base_dirs_) {
+ // Prefix match
+ if (!req.path.compare(0, entry.mount_point.size(), entry.mount_point)) {
+ std::string sub_path = "/" + req.path.substr(entry.mount_point.size());
+ if (detail::is_valid_path(sub_path)) {
+ auto path = entry.base_dir + sub_path;
+ if (path.back() == '/') { path += "index.html"; }
+
+ if (detail::is_file(path)) {
+ detail::read_file(path, res.body);
+ auto type =
+ detail::find_content_type(path, file_extension_and_mimetype_map_);
+ if (type) { res.set_header("Content-Type", type); }
+ for (const auto &kv : entry.headers) {
+ res.set_header(kv.first.c_str(), kv.second);
+ }
+ res.status = req.has_header("Range") ? 206 : 200;
+ if (!head && file_request_handler_) {
+ file_request_handler_(req, res);
+ }
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+}
+
+inline socket_t
+Server::create_server_socket(const char *host, int port, int socket_flags,
+ SocketOptions socket_options) const {
+ return detail::create_socket(
+ host, port, address_family_, socket_flags, tcp_nodelay_,
+ std::move(socket_options),
+ [](socket_t sock, struct addrinfo &ai) -> bool {
+ if (::bind(sock, ai.ai_addr, static_cast<socklen_t>(ai.ai_addrlen))) {
+ return false;
+ }
+ if (::listen(sock, 5)) { // Listen through 5 channels
+ return false;
+ }
+ return true;
+ });
+}
+
+inline int Server::bind_internal(const char *host, int port, int socket_flags) {
+ if (!is_valid()) { return -1; }
+
+ svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_);
+ if (svr_sock_ == INVALID_SOCKET) { return -1; }
+
+ if (port == 0) {
+ struct sockaddr_storage addr;
+ socklen_t addr_len = sizeof(addr);
+ if (getsockname(svr_sock_, reinterpret_cast<struct sockaddr *>(&addr),
+ &addr_len) == -1) {
+ return -1;
+ }
+ if (addr.ss_family == AF_INET) {
+ return ntohs(reinterpret_cast<struct sockaddr_in *>(&addr)->sin_port);
+ } else if (addr.ss_family == AF_INET6) {
+ return ntohs(reinterpret_cast<struct sockaddr_in6 *>(&addr)->sin6_port);
+ } else {
+ return -1;
+ }
+ } else {
+ return port;
+ }
+}
+
+inline bool Server::listen_internal() {
+ auto ret = true;
+ is_running_ = true;
+
+ {
+ std::unique_ptr<TaskQueue> task_queue(new_task_queue());
+
+ while (svr_sock_ != INVALID_SOCKET) {
+#ifndef _WIN32
+ if (idle_interval_sec_ > 0 || idle_interval_usec_ > 0) {
+#endif
+ auto val = detail::select_read(svr_sock_, idle_interval_sec_,
+ idle_interval_usec_);
+ if (val == 0) { // Timeout
+ task_queue->on_idle();
+ continue;
+ }
+#ifndef _WIN32
+ }
+#endif
+ socket_t sock = accept(svr_sock_, nullptr, nullptr);
+
+ if (sock == INVALID_SOCKET) {
+ if (errno == EMFILE) {
+ // The per-process limit of open file descriptors has been reached.
+ // Try to accept new connections after a short sleep.
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ continue;
+ }
+ if (svr_sock_ != INVALID_SOCKET) {
+ detail::close_socket(svr_sock_);
+ ret = false;
+ } else {
+ ; // The server socket was closed by user.
+ }
+ break;
+ }
+
+ {
+ timeval tv;
+ tv.tv_sec = static_cast<long>(read_timeout_sec_);
+ tv.tv_usec = static_cast<decltype(tv.tv_usec)>(read_timeout_usec_);
+ setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv));
+ }
+ {
+ timeval tv;
+ tv.tv_sec = static_cast<long>(write_timeout_sec_);
+ tv.tv_usec = static_cast<decltype(tv.tv_usec)>(write_timeout_usec_);
+ setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char *)&tv, sizeof(tv));
+ }
+
+#if __cplusplus > 201703L
+ task_queue->enqueue([=, this]() { process_and_close_socket(sock); });
+#else
+ task_queue->enqueue([=]() { process_and_close_socket(sock); });
+#endif
+ }
+
+ task_queue->shutdown();
+ }
+
+ is_running_ = false;
+ return ret;
+}
+
+inline bool Server::routing(Request &req, Response &res, Stream &strm) {
+ if (pre_routing_handler_ &&
+ pre_routing_handler_(req, res) == HandlerResponse::Handled) {
+ return true;
+ }
+
+ // File handler
+ bool is_head_request = req.method == "HEAD";
+ if ((req.method == "GET" || is_head_request) &&
+ handle_file_request(req, res, is_head_request)) {
+ return true;
+ }
+
+ if (detail::expect_content(req)) {
+ // Content reader handler
+ {
+ ContentReader reader(
+ [&](ContentReceiver receiver) {
+ return read_content_with_content_receiver(
+ strm, req, res, std::move(receiver), nullptr, nullptr);
+ },
+ [&](MultipartContentHeader header, ContentReceiver receiver) {
+ return read_content_with_content_receiver(strm, req, res, nullptr,
+ std::move(header),
+ std::move(receiver));
+ });
+
+ if (req.method == "POST") {
+ if (dispatch_request_for_content_reader(
+ req, res, std::move(reader),
+ post_handlers_for_content_reader_)) {
+ return true;
+ }
+ } else if (req.method == "PUT") {
+ if (dispatch_request_for_content_reader(
+ req, res, std::move(reader),
+ put_handlers_for_content_reader_)) {
+ return true;
+ }
+ } else if (req.method == "PATCH") {
+ if (dispatch_request_for_content_reader(
+ req, res, std::move(reader),
+ patch_handlers_for_content_reader_)) {
+ return true;
+ }
+ } else if (req.method == "DELETE") {
+ if (dispatch_request_for_content_reader(
+ req, res, std::move(reader),
+ delete_handlers_for_content_reader_)) {
+ return true;
+ }
+ }
+ }
+
+ // Read content into `req.body`
+ if (!read_content(strm, req, res)) { return false; }
+ }
+
+ // Regular handler
+ if (req.method == "GET" || req.method == "HEAD") {
+ return dispatch_request(req, res, get_handlers_);
+ } else if (req.method == "POST") {
+ return dispatch_request(req, res, post_handlers_);
+ } else if (req.method == "PUT") {
+ return dispatch_request(req, res, put_handlers_);
+ } else if (req.method == "DELETE") {
+ return dispatch_request(req, res, delete_handlers_);
+ } else if (req.method == "OPTIONS") {
+ return dispatch_request(req, res, options_handlers_);
+ } else if (req.method == "PATCH") {
+ return dispatch_request(req, res, patch_handlers_);
+ }
+
+ res.status = 400;
+ return false;
+}
+
+inline bool Server::dispatch_request(Request &req, Response &res,
+ const Handlers &handlers) {
+ for (const auto &x : handlers) {
+ const auto &pattern = x.first;
+ const auto &handler = x.second;
+
+ if (std::regex_match(req.path, req.matches, pattern)) {
+ handler(req, res);
+ return true;
+ }
+ }
+ return false;
+}
+
+inline void Server::apply_ranges(const Request &req, Response &res,
+ std::string &content_type,
+ std::string &boundary) {
+ if (req.ranges.size() > 1) {
+ boundary = detail::make_multipart_data_boundary();
+
+ auto it = res.headers.find("Content-Type");
+ if (it != res.headers.end()) {
+ content_type = it->second;
+ res.headers.erase(it);
+ }
+
+ res.headers.emplace("Content-Type",
+ "multipart/byteranges; boundary=" + boundary);
+ }
+
+ auto type = detail::encoding_type(req, res);
+
+ if (res.body.empty()) {
+ if (res.content_length_ > 0) {
+ size_t length = 0;
+ if (req.ranges.empty()) {
+ length = res.content_length_;
+ } else if (req.ranges.size() == 1) {
+ auto offsets =
+ detail::get_range_offset_and_length(req, res.content_length_, 0);
+ auto offset = offsets.first;
+ length = offsets.second;
+ auto content_range = detail::make_content_range_header_field(
+ offset, length, res.content_length_);
+ res.set_header("Content-Range", content_range);
+ } else {
+ length = detail::get_multipart_ranges_data_length(req, res, boundary,
+ content_type);
+ }
+ res.set_header("Content-Length", std::to_string(length));
+ } else {
+ if (res.content_provider_) {
+ if (res.is_chunked_content_provider_) {
+ res.set_header("Transfer-Encoding", "chunked");
+ if (type == detail::EncodingType::Gzip) {
+ res.set_header("Content-Encoding", "gzip");
+ } else if (type == detail::EncodingType::Brotli) {
+ res.set_header("Content-Encoding", "br");
+ }
+ }
+ }
+ }
+ } else {
+ if (req.ranges.empty()) {
+ ;
+ } else if (req.ranges.size() == 1) {
+ auto offsets =
+ detail::get_range_offset_and_length(req, res.body.size(), 0);
+ auto offset = offsets.first;
+ auto length = offsets.second;
+ auto content_range = detail::make_content_range_header_field(
+ offset, length, res.body.size());
+ res.set_header("Content-Range", content_range);
+ if (offset < res.body.size()) {
+ res.body = res.body.substr(offset, length);
+ } else {
+ res.body.clear();
+ res.status = 416;
+ }
+ } else {
+ std::string data;
+ if (detail::make_multipart_ranges_data(req, res, boundary, content_type,
+ data)) {
+ res.body.swap(data);
+ } else {
+ res.body.clear();
+ res.status = 416;
+ }
+ }
+
+ if (type != detail::EncodingType::None) {
+ std::unique_ptr<detail::compressor> compressor;
+ std::string content_encoding;
+
+ if (type == detail::EncodingType::Gzip) {
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+ compressor = detail::make_unique<detail::gzip_compressor>();
+ content_encoding = "gzip";
+#endif
+ } else if (type == detail::EncodingType::Brotli) {
+#ifdef CPPHTTPLIB_BROTLI_SUPPORT
+ compressor = detail::make_unique<detail::brotli_compressor>();
+ content_encoding = "br";
+#endif
+ }
+
+ if (compressor) {
+ std::string compressed;
+ if (compressor->compress(res.body.data(), res.body.size(), true,
+ [&](const char *data, size_t data_len) {
+ compressed.append(data, data_len);
+ return true;
+ })) {
+ res.body.swap(compressed);
+ res.set_header("Content-Encoding", content_encoding);
+ }
+ }
+ }
+
+ auto length = std::to_string(res.body.size());
+ res.set_header("Content-Length", length);
+ }
+}
+
+inline bool Server::dispatch_request_for_content_reader(
+ Request &req, Response &res, ContentReader content_reader,
+ const HandlersForContentReader &handlers) {
+ for (const auto &x : handlers) {
+ const auto &pattern = x.first;
+ const auto &handler = x.second;
+
+ if (std::regex_match(req.path, req.matches, pattern)) {
+ handler(req, res, content_reader);
+ return true;
+ }
+ }
+ return false;
+}
+
+inline bool
+Server::process_request(Stream &strm, bool close_connection,
+ bool &connection_closed,
+ const std::function<void(Request &)> &setup_request) {
+ std::array<char, 2048> buf{};
+
+ detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
+
+ // Connection has been closed on client
+ if (!line_reader.getline()) { return false; }
+
+ Request req;
+ Response res;
+
+ res.version = "HTTP/1.1";
+
+ for (const auto &header : default_headers_) {
+ if (res.headers.find(header.first) == res.headers.end()) {
+ res.headers.insert(header);
+ }
+ }
+
+#ifdef _WIN32
+ // TODO: Increase FD_SETSIZE statically (libzmq), dynamically (MySQL).
+#else
+#ifndef CPPHTTPLIB_USE_POLL
+ // Socket file descriptor exceeded FD_SETSIZE...
+ if (strm.socket() >= FD_SETSIZE) {
+ Headers dummy;
+ detail::read_headers(strm, dummy);
+ res.status = 500;
+ return write_response(strm, close_connection, req, res);
+ }
+#endif
+#endif
+
+ // Check if the request URI doesn't exceed the limit
+ if (line_reader.size() > CPPHTTPLIB_REQUEST_URI_MAX_LENGTH) {
+ Headers dummy;
+ detail::read_headers(strm, dummy);
+ res.status = 414;
+ return write_response(strm, close_connection, req, res);
+ }
+
+ // Request line and headers
+ if (!parse_request_line(line_reader.ptr(), req) ||
+ !detail::read_headers(strm, req.headers)) {
+ res.status = 400;
+ return write_response(strm, close_connection, req, res);
+ }
+
+ if (req.get_header_value("Connection") == "close") {
+ connection_closed = true;
+ }
+
+ if (req.version == "HTTP/1.0" &&
+ req.get_header_value("Connection") != "Keep-Alive") {
+ connection_closed = true;
+ }
+
+ strm.get_remote_ip_and_port(req.remote_addr, req.remote_port);
+ req.set_header("REMOTE_ADDR", req.remote_addr);
+ req.set_header("REMOTE_PORT", std::to_string(req.remote_port));
+
+ if (req.has_header("Range")) {
+ const auto &range_header_value = req.get_header_value("Range");
+ if (!detail::parse_range_header(range_header_value, req.ranges)) {
+ res.status = 416;
+ return write_response(strm, close_connection, req, res);
+ }
+ }
+
+ if (setup_request) { setup_request(req); }
+
+ if (req.get_header_value("Expect") == "100-continue") {
+ auto status = 100;
+ if (expect_100_continue_handler_) {
+ status = expect_100_continue_handler_(req, res);
+ }
+ switch (status) {
+ case 100:
+ case 417:
+ strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status,
+ detail::status_message(status));
+ break;
+ default: return write_response(strm, close_connection, req, res);
+ }
+ }
+
+ // Rounting
+ bool routed = false;
+ try {
+ routed = routing(req, res, strm);
+ } catch (std::exception &e) {
+ if (exception_handler_) {
+ exception_handler_(req, res, e);
+ routed = true;
+ } else {
+ res.status = 500;
+ res.set_header("EXCEPTION_WHAT", e.what());
+ }
+ } catch (...) {
+ res.status = 500;
+ res.set_header("EXCEPTION_WHAT", "UNKNOWN");
+ }
+
+ if (routed) {
+ if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; }
+ return write_response_with_content(strm, close_connection, req, res);
+ } else {
+ if (res.status == -1) { res.status = 404; }
+ return write_response(strm, close_connection, req, res);
+ }
+}
+
+inline bool Server::is_valid() const { return true; }
+
+inline bool Server::process_and_close_socket(socket_t sock) {
+ auto ret = detail::process_server_socket(
+ sock, keep_alive_max_count_, keep_alive_timeout_sec_, read_timeout_sec_,
+ read_timeout_usec_, write_timeout_sec_, write_timeout_usec_,
+ [this](Stream &strm, bool close_connection, bool &connection_closed) {
+ return process_request(strm, close_connection, connection_closed,
+ nullptr);
+ });
+
+ detail::shutdown_socket(sock);
+ detail::close_socket(sock);
+ return ret;
+}
+
+// HTTP client implementation
+inline ClientImpl::ClientImpl(const std::string &host)
+ : ClientImpl(host, 80, std::string(), std::string()) {}
+
+inline ClientImpl::ClientImpl(const std::string &host, int port)
+ : ClientImpl(host, port, std::string(), std::string()) {}
+
+inline ClientImpl::ClientImpl(const std::string &host, int port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path)
+ : host_(host), port_(port),
+ host_and_port_(adjust_host_string(host) + ":" + std::to_string(port)),
+ client_cert_path_(client_cert_path), client_key_path_(client_key_path) {}
+
+inline ClientImpl::~ClientImpl() {
+ std::lock_guard<std::mutex> guard(socket_mutex_);
+ shutdown_socket(socket_);
+ close_socket(socket_);
+}
+
+inline bool ClientImpl::is_valid() const { return true; }
+
+inline void ClientImpl::copy_settings(const ClientImpl &rhs) {
+ client_cert_path_ = rhs.client_cert_path_;
+ client_key_path_ = rhs.client_key_path_;
+ connection_timeout_sec_ = rhs.connection_timeout_sec_;
+ read_timeout_sec_ = rhs.read_timeout_sec_;
+ read_timeout_usec_ = rhs.read_timeout_usec_;
+ write_timeout_sec_ = rhs.write_timeout_sec_;
+ write_timeout_usec_ = rhs.write_timeout_usec_;
+ basic_auth_username_ = rhs.basic_auth_username_;
+ basic_auth_password_ = rhs.basic_auth_password_;
+ bearer_token_auth_token_ = rhs.bearer_token_auth_token_;
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ digest_auth_username_ = rhs.digest_auth_username_;
+ digest_auth_password_ = rhs.digest_auth_password_;
+#endif
+ keep_alive_ = rhs.keep_alive_;
+ follow_location_ = rhs.follow_location_;
+ url_encode_ = rhs.url_encode_;
+ address_family_ = rhs.address_family_;
+ tcp_nodelay_ = rhs.tcp_nodelay_;
+ socket_options_ = rhs.socket_options_;
+ compress_ = rhs.compress_;
+ decompress_ = rhs.decompress_;
+ interface_ = rhs.interface_;
+ proxy_host_ = rhs.proxy_host_;
+ proxy_port_ = rhs.proxy_port_;
+ proxy_basic_auth_username_ = rhs.proxy_basic_auth_username_;
+ proxy_basic_auth_password_ = rhs.proxy_basic_auth_password_;
+ proxy_bearer_token_auth_token_ = rhs.proxy_bearer_token_auth_token_;
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ proxy_digest_auth_username_ = rhs.proxy_digest_auth_username_;
+ proxy_digest_auth_password_ = rhs.proxy_digest_auth_password_;
+#endif
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ ca_cert_file_path_ = rhs.ca_cert_file_path_;
+ ca_cert_dir_path_ = rhs.ca_cert_dir_path_;
+ ca_cert_store_ = rhs.ca_cert_store_;
+#endif
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ server_certificate_verification_ = rhs.server_certificate_verification_;
+#endif
+ logger_ = rhs.logger_;
+}
+
+inline socket_t ClientImpl::create_client_socket(Error &error) const {
+ if (!proxy_host_.empty() && proxy_port_ != -1) {
+ return detail::create_client_socket(
+ proxy_host_.c_str(), proxy_port_, address_family_, tcp_nodelay_,
+ socket_options_, connection_timeout_sec_, connection_timeout_usec_,
+ read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
+ write_timeout_usec_, interface_, error);
+ }
+ return detail::create_client_socket(
+ host_.c_str(), port_, address_family_, tcp_nodelay_, socket_options_,
+ connection_timeout_sec_, connection_timeout_usec_, read_timeout_sec_,
+ read_timeout_usec_, write_timeout_sec_, write_timeout_usec_, interface_,
+ error);
+}
+
+inline bool ClientImpl::create_and_connect_socket(Socket &socket,
+ Error &error) {
+ auto sock = create_client_socket(error);
+ if (sock == INVALID_SOCKET) { return false; }
+ socket.sock = sock;
+ return true;
+}
+
+inline void ClientImpl::shutdown_ssl(Socket & /*socket*/,
+ bool /*shutdown_gracefully*/) {
+ // If there are any requests in flight from threads other than us, then it's
+ // a thread-unsafe race because individual ssl* objects are not thread-safe.
+ assert(socket_requests_in_flight_ == 0 ||
+ socket_requests_are_from_thread_ == std::this_thread::get_id());
+}
+
+inline void ClientImpl::shutdown_socket(Socket &socket) {
+ if (socket.sock == INVALID_SOCKET) { return; }
+ detail::shutdown_socket(socket.sock);
+}
+
+inline void ClientImpl::close_socket(Socket &socket) {
+ // If there are requests in flight in another thread, usually closing
+ // the socket will be fine and they will simply receive an error when
+ // using the closed socket, but it is still a bug since rarely the OS
+ // may reassign the socket id to be used for a new socket, and then
+ // suddenly they will be operating on a live socket that is different
+ // than the one they intended!
+ assert(socket_requests_in_flight_ == 0 ||
+ socket_requests_are_from_thread_ == std::this_thread::get_id());
+
+ // It is also a bug if this happens while SSL is still active
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ assert(socket.ssl == nullptr);
+#endif
+ if (socket.sock == INVALID_SOCKET) { return; }
+ detail::close_socket(socket.sock);
+ socket.sock = INVALID_SOCKET;
+}
+
+inline bool ClientImpl::read_response_line(Stream &strm, const Request &req,
+ Response &res) {
+ std::array<char, 2048> buf;
+
+ detail::stream_line_reader line_reader(strm, buf.data(), buf.size());
+
+ if (!line_reader.getline()) { return false; }
+
+ const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r\n");
+
+ std::cmatch m;
+ if (!std::regex_match(line_reader.ptr(), m, re)) {
+ return req.method == "CONNECT";
+ }
+ res.version = std::string(m[1]);
+ res.status = std::stoi(std::string(m[2]));
+ res.reason = std::string(m[3]);
+
+ // Ignore '100 Continue'
+ while (res.status == 100) {
+ if (!line_reader.getline()) { return false; } // CRLF
+ if (!line_reader.getline()) { return false; } // next response line
+
+ if (!std::regex_match(line_reader.ptr(), m, re)) { return false; }
+ res.version = std::string(m[1]);
+ res.status = std::stoi(std::string(m[2]));
+ res.reason = std::string(m[3]);
+ }
+
+ return true;
+}
+
+inline bool ClientImpl::send(Request &req, Response &res, Error &error) {
+ std::lock_guard<std::recursive_mutex> request_mutex_guard(request_mutex_);
+
+ {
+ std::lock_guard<std::mutex> guard(socket_mutex_);
+ // Set this to false immediately - if it ever gets set to true by the end of
+ // the request, we know another thread instructed us to close the socket.
+ socket_should_be_closed_when_request_is_done_ = false;
+
+ auto is_alive = false;
+ if (socket_.is_open()) {
+ is_alive = detail::select_write(socket_.sock, 0, 0) > 0;
+ if (!is_alive) {
+ // Attempt to avoid sigpipe by shutting down nongracefully if it seems
+ // like the other side has already closed the connection Also, there
+ // cannot be any requests in flight from other threads since we locked
+ // request_mutex_, so safe to close everything immediately
+ const bool shutdown_gracefully = false;
+ shutdown_ssl(socket_, shutdown_gracefully);
+ shutdown_socket(socket_);
+ close_socket(socket_);
+ }
+ }
+
+ if (!is_alive) {
+ if (!create_and_connect_socket(socket_, error)) { return false; }
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ // TODO: refactoring
+ if (is_ssl()) {
+ auto &scli = static_cast<SSLClient &>(*this);
+ if (!proxy_host_.empty() && proxy_port_ != -1) {
+ bool success = false;
+ if (!scli.connect_with_proxy(socket_, res, success, error)) {
+ return success;
+ }
+ }
+
+ if (!scli.initialize_ssl(socket_, error)) { return false; }
+ }
+#endif
+ }
+
+ // Mark the current socket as being in use so that it cannot be closed by
+ // anyone else while this request is ongoing, even though we will be
+ // releasing the mutex.
+ if (socket_requests_in_flight_ > 1) {
+ assert(socket_requests_are_from_thread_ == std::this_thread::get_id());
+ }
+ socket_requests_in_flight_ += 1;
+ socket_requests_are_from_thread_ = std::this_thread::get_id();
+ }
+
+ for (const auto &header : default_headers_) {
+ if (req.headers.find(header.first) == req.headers.end()) {
+ req.headers.insert(header);
+ }
+ }
+
+ auto close_connection = !keep_alive_;
+ auto ret = process_socket(socket_, [&](Stream &strm) {
+ return handle_request(strm, req, res, close_connection, error);
+ });
+
+ // Briefly lock mutex in order to mark that a request is no longer ongoing
+ {
+ std::lock_guard<std::mutex> guard(socket_mutex_);
+ socket_requests_in_flight_ -= 1;
+ if (socket_requests_in_flight_ <= 0) {
+ assert(socket_requests_in_flight_ == 0);
+ socket_requests_are_from_thread_ = std::thread::id();
+ }
+
+ if (socket_should_be_closed_when_request_is_done_ || close_connection ||
+ !ret) {
+ shutdown_ssl(socket_, true);
+ shutdown_socket(socket_);
+ close_socket(socket_);
+ }
+ }
+
+ if (!ret) {
+ if (error == Error::Success) { error = Error::Unknown; }
+ }
+
+ return ret;
+}
+
+inline Result ClientImpl::send(const Request &req) {
+ auto req2 = req;
+ return send_(std::move(req2));
+}
+
+inline Result ClientImpl::send_(Request &&req) {
+ auto res = detail::make_unique<Response>();
+ auto error = Error::Success;
+ auto ret = send(req, *res, error);
+ return Result{ret ? std::move(res) : nullptr, error, std::move(req.headers)};
+}
+
+inline bool ClientImpl::handle_request(Stream &strm, Request &req,
+ Response &res, bool close_connection,
+ Error &error) {
+ if (req.path.empty()) {
+ error = Error::Connection;
+ return false;
+ }
+
+ auto req_save = req;
+
+ bool ret;
+
+ if (!is_ssl() && !proxy_host_.empty() && proxy_port_ != -1) {
+ auto req2 = req;
+ req2.path = "http://" + host_and_port_ + req.path;
+ ret = process_request(strm, req2, res, close_connection, error);
+ req = req2;
+ req.path = req_save.path;
+ } else {
+ ret = process_request(strm, req, res, close_connection, error);
+ }
+
+ if (!ret) { return false; }
+
+ if (300 < res.status && res.status < 400 && follow_location_) {
+ req = req_save;
+ ret = redirect(req, res, error);
+ }
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ if ((res.status == 401 || res.status == 407) &&
+ req.authorization_count_ < 5) {
+ auto is_proxy = res.status == 407;
+ const auto &username =
+ is_proxy ? proxy_digest_auth_username_ : digest_auth_username_;
+ const auto &password =
+ is_proxy ? proxy_digest_auth_password_ : digest_auth_password_;
+
+ if (!username.empty() && !password.empty()) {
+ std::map<std::string, std::string> auth;
+ if (detail::parse_www_authenticate(res, auth, is_proxy)) {
+ Request new_req = req;
+ new_req.authorization_count_ += 1;
+ new_req.headers.erase(is_proxy ? "Proxy-Authorization"
+ : "Authorization");
+ new_req.headers.insert(detail::make_digest_authentication_header(
+ req, auth, new_req.authorization_count_, detail::random_string(10),
+ username, password, is_proxy));
+
+ Response new_res;
+
+ ret = send(new_req, new_res, error);
+ if (ret) { res = new_res; }
+ }
+ }
+ }
+#endif
+
+ return ret;
+}
+
+inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) {
+ if (req.redirect_count_ == 0) {
+ error = Error::ExceedRedirectCount;
+ return false;
+ }
+
+ auto location = detail::decode_url(res.get_header_value("location"), true);
+ if (location.empty()) { return false; }
+
+ const static std::regex re(
+ R"((?:(https?):)?(?://(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*(?:\?[^#]*)?)(?:#.*)?)");
+
+ std::smatch m;
+ if (!std::regex_match(location, m, re)) { return false; }
+
+ auto scheme = is_ssl() ? "https" : "http";
+
+ auto next_scheme = m[1].str();
+ auto next_host = m[2].str();
+ if (next_host.empty()) { next_host = m[3].str(); }
+ auto port_str = m[4].str();
+ auto next_path = m[5].str();
+
+ auto next_port = port_;
+ if (!port_str.empty()) {
+ next_port = std::stoi(port_str);
+ } else if (!next_scheme.empty()) {
+ next_port = next_scheme == "https" ? 443 : 80;
+ }
+
+ if (next_scheme.empty()) { next_scheme = scheme; }
+ if (next_host.empty()) { next_host = host_; }
+ if (next_path.empty()) { next_path = "/"; }
+
+ if (next_scheme == scheme && next_host == host_ && next_port == port_) {
+ return detail::redirect(*this, req, res, next_path, location, error);
+ } else {
+ if (next_scheme == "https") {
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ SSLClient cli(next_host.c_str(), next_port);
+ cli.copy_settings(*this);
+ if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); }
+ return detail::redirect(cli, req, res, next_path, location, error);
+#else
+ return false;
+#endif
+ } else {
+ ClientImpl cli(next_host.c_str(), next_port);
+ cli.copy_settings(*this);
+ return detail::redirect(cli, req, res, next_path, location, error);
+ }
+ }
+}
+
+inline bool ClientImpl::write_content_with_provider(Stream &strm,
+ const Request &req,
+ Error &error) {
+ auto is_shutting_down = []() { return false; };
+
+ if (req.is_chunked_content_provider_) {
+ // TODO: Brotli suport
+ std::unique_ptr<detail::compressor> compressor;
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+ if (compress_) {
+ compressor = detail::make_unique<detail::gzip_compressor>();
+ } else
+#endif
+ {
+ compressor = detail::make_unique<detail::nocompressor>();
+ }
+
+ return detail::write_content_chunked(strm, req.content_provider_,
+ is_shutting_down, *compressor, error);
+ } else {
+ return detail::write_content(strm, req.content_provider_, 0,
+ req.content_length_, is_shutting_down, error);
+ }
+} // namespace httplib
+
+inline bool ClientImpl::write_request(Stream &strm, Request &req,
+ bool close_connection, Error &error) {
+ // Prepare additional headers
+ if (close_connection) {
+ if (!req.has_header("Connection")) {
+ req.headers.emplace("Connection", "close");
+ }
+ }
+
+ if (!req.has_header("Host")) {
+ if (is_ssl()) {
+ if (port_ == 443) {
+ req.headers.emplace("Host", host_);
+ } else {
+ req.headers.emplace("Host", host_and_port_);
+ }
+ } else {
+ if (port_ == 80) {
+ req.headers.emplace("Host", host_);
+ } else {
+ req.headers.emplace("Host", host_and_port_);
+ }
+ }
+ }
+
+ if (!req.has_header("Accept")) { req.headers.emplace("Accept", "*/*"); }
+
+ if (!req.has_header("User-Agent")) {
+ req.headers.emplace("User-Agent", "cpp-httplib/0.9");
+ }
+
+ if (req.body.empty()) {
+ if (req.content_provider_) {
+ if (!req.is_chunked_content_provider_) {
+ if (!req.has_header("Content-Length")) {
+ auto length = std::to_string(req.content_length_);
+ req.headers.emplace("Content-Length", length);
+ }
+ }
+ } else {
+ if (req.method == "POST" || req.method == "PUT" ||
+ req.method == "PATCH") {
+ req.headers.emplace("Content-Length", "0");
+ }
+ }
+ } else {
+ if (!req.has_header("Content-Type")) {
+ req.headers.emplace("Content-Type", "text/plain");
+ }
+
+ if (!req.has_header("Content-Length")) {
+ auto length = std::to_string(req.body.size());
+ req.headers.emplace("Content-Length", length);
+ }
+ }
+
+ if (!basic_auth_password_.empty() || !basic_auth_username_.empty()) {
+ if (!req.has_header("Authorization")) {
+ req.headers.insert(make_basic_authentication_header(
+ basic_auth_username_, basic_auth_password_, false));
+ }
+ }
+
+ if (!proxy_basic_auth_username_.empty() &&
+ !proxy_basic_auth_password_.empty()) {
+ if (!req.has_header("Proxy-Authorization")) {
+ req.headers.insert(make_basic_authentication_header(
+ proxy_basic_auth_username_, proxy_basic_auth_password_, true));
+ }
+ }
+
+ if (!bearer_token_auth_token_.empty()) {
+ if (!req.has_header("Authorization")) {
+ req.headers.insert(make_bearer_token_authentication_header(
+ bearer_token_auth_token_, false));
+ }
+ }
+
+ if (!proxy_bearer_token_auth_token_.empty()) {
+ if (!req.has_header("Proxy-Authorization")) {
+ req.headers.insert(make_bearer_token_authentication_header(
+ proxy_bearer_token_auth_token_, true));
+ }
+ }
+
+ // Request line and headers
+ {
+ detail::BufferStream bstrm;
+
+ const auto &path = url_encode_ ? detail::encode_url(req.path) : req.path;
+ bstrm.write_format("%s %s HTTP/1.1\r\n", req.method.c_str(), path.c_str());
+
+ detail::write_headers(bstrm, req.headers);
+
+ // Flush buffer
+ auto &data = bstrm.get_buffer();
+ if (!detail::write_data(strm, data.data(), data.size())) {
+ error = Error::Write;
+ return false;
+ }
+ }
+
+ // Body
+ if (req.body.empty()) {
+ return write_content_with_provider(strm, req, error);
+ }
+
+ return detail::write_data(strm, req.body.data(), req.body.size());
+}
+
+inline std::unique_ptr<Response> ClientImpl::send_with_content_provider(
+ Request &req,
+ // const char *method, const char *path, const Headers &headers,
+ const char *body, size_t content_length, ContentProvider content_provider,
+ ContentProviderWithoutLength content_provider_without_length,
+ const char *content_type, Error &error) {
+
+ // Request req;
+ // req.method = method;
+ // req.headers = headers;
+ // req.path = path;
+
+ if (content_type) { req.headers.emplace("Content-Type", content_type); }
+
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+ if (compress_) { req.headers.emplace("Content-Encoding", "gzip"); }
+#endif
+
+#ifdef CPPHTTPLIB_ZLIB_SUPPORT
+ if (compress_ && !content_provider_without_length) {
+ // TODO: Brotli support
+ detail::gzip_compressor compressor;
+
+ if (content_provider) {
+ auto ok = true;
+ size_t offset = 0;
+ DataSink data_sink;
+
+ data_sink.write = [&](const char *data, size_t data_len) -> bool {
+ if (ok) {
+ auto last = offset + data_len == content_length;
+
+ auto ret = compressor.compress(
+ data, data_len, last, [&](const char *data, size_t data_len) {
+ req.body.append(data, data_len);
+ return true;
+ });
+
+ if (ret) {
+ offset += data_len;
+ } else {
+ ok = false;
+ }
+ }
+ return ok;
+ };
+
+ data_sink.is_writable = [&](void) { return ok && true; };
+
+ while (ok && offset < content_length) {
+ if (!content_provider(offset, content_length - offset, data_sink)) {
+ error = Error::Canceled;
+ return nullptr;
+ }
+ }
+ } else {
+ if (!compressor.compress(body, content_length, true,
+ [&](const char *data, size_t data_len) {
+ req.body.append(data, data_len);
+ return true;
+ })) {
+ error = Error::Compression;
+ return nullptr;
+ }
+ }
+ } else
+#endif
+ {
+ if (content_provider) {
+ req.content_length_ = content_length;
+ req.content_provider_ = std::move(content_provider);
+ req.is_chunked_content_provider_ = false;
+ } else if (content_provider_without_length) {
+ req.content_length_ = 0;
+ req.content_provider_ = detail::ContentProviderAdapter(
+ std::move(content_provider_without_length));
+ req.is_chunked_content_provider_ = true;
+ req.headers.emplace("Transfer-Encoding", "chunked");
+ } else {
+ req.body.assign(body, content_length);
+ ;
+ }
+ }
+
+ auto res = detail::make_unique<Response>();
+ return send(req, *res, error) ? std::move(res) : nullptr;
+}
+
+inline Result ClientImpl::send_with_content_provider(
+ const char *method, const char *path, const Headers &headers,
+ const char *body, size_t content_length, ContentProvider content_provider,
+ ContentProviderWithoutLength content_provider_without_length,
+ const char *content_type) {
+ Request req;
+ req.method = method;
+ req.headers = headers;
+ req.path = path;
+
+ auto error = Error::Success;
+
+ auto res = send_with_content_provider(
+ req,
+ // method, path, headers,
+ body, content_length, std::move(content_provider),
+ std::move(content_provider_without_length), content_type, error);
+
+ return Result{std::move(res), error, std::move(req.headers)};
+}
+
+inline std::string
+ClientImpl::adjust_host_string(const std::string &host) const {
+ if (host.find(':') != std::string::npos) { return "[" + host + "]"; }
+ return host;
+}
+
+inline bool ClientImpl::process_request(Stream &strm, Request &req,
+ Response &res, bool close_connection,
+ Error &error) {
+ // Send request
+ if (!write_request(strm, req, close_connection, error)) { return false; }
+
+ // Receive response and headers
+ if (!read_response_line(strm, req, res) ||
+ !detail::read_headers(strm, res.headers)) {
+ error = Error::Read;
+ return false;
+ }
+
+ // Body
+ if ((res.status != 204) && req.method != "HEAD" && req.method != "CONNECT") {
+ auto redirect = 300 < res.status && res.status < 400 && follow_location_;
+
+ if (req.response_handler && !redirect) {
+ if (!req.response_handler(res)) {
+ error = Error::Canceled;
+ return false;
+ }
+ }
+
+ auto out =
+ req.content_receiver
+ ? static_cast<ContentReceiverWithProgress>(
+ [&](const char *buf, size_t n, uint64_t off, uint64_t len) {
+ if (redirect) { return true; }
+ auto ret = req.content_receiver(buf, n, off, len);
+ if (!ret) { error = Error::Canceled; }
+ return ret;
+ })
+ : static_cast<ContentReceiverWithProgress>(
+ [&](const char *buf, size_t n, uint64_t /*off*/,
+ uint64_t /*len*/) {
+ if (res.body.size() + n > res.body.max_size()) {
+ return false;
+ }
+ res.body.append(buf, n);
+ return true;
+ });
+
+ auto progress = [&](uint64_t current, uint64_t total) {
+ if (!req.progress || redirect) { return true; }
+ auto ret = req.progress(current, total);
+ if (!ret) { error = Error::Canceled; }
+ return ret;
+ };
+
+ int dummy_status;
+ if (!detail::read_content(strm, res, (std::numeric_limits<size_t>::max)(),
+ dummy_status, std::move(progress), std::move(out),
+ decompress_)) {
+ if (error != Error::Canceled) { error = Error::Read; }
+ return false;
+ }
+ }
+
+ if (res.get_header_value("Connection") == "close" ||
+ (res.version == "HTTP/1.0" && res.reason != "Connection established")) {
+ // TODO this requires a not-entirely-obvious chain of calls to be correct
+ // for this to be safe. Maybe a code refactor (such as moving this out to
+ // the send function and getting rid of the recursiveness of the mutex)
+ // could make this more obvious.
+
+ // This is safe to call because process_request is only called by
+ // handle_request which is only called by send, which locks the request
+ // mutex during the process. It would be a bug to call it from a different
+ // thread since it's a thread-safety issue to do these things to the socket
+ // if another thread is using the socket.
+ std::lock_guard<std::mutex> guard(socket_mutex_);
+ shutdown_ssl(socket_, true);
+ shutdown_socket(socket_);
+ close_socket(socket_);
+ }
+
+ // Log
+ if (logger_) { logger_(req, res); }
+
+ return true;
+}
+
+inline bool
+ClientImpl::process_socket(const Socket &socket,
+ std::function<bool(Stream &strm)> callback) {
+ return detail::process_client_socket(
+ socket.sock, read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
+ write_timeout_usec_, std::move(callback));
+}
+
+inline bool ClientImpl::is_ssl() const { return false; }
+
+inline Result ClientImpl::Get(const char *path) {
+ return Get(path, Headers(), Progress());
+}
+
+inline Result ClientImpl::Get(const char *path, Progress progress) {
+ return Get(path, Headers(), std::move(progress));
+}
+
+inline Result ClientImpl::Get(const char *path, const Headers &headers) {
+ return Get(path, headers, Progress());
+}
+
+inline Result ClientImpl::Get(const char *path, const Headers &headers,
+ Progress progress) {
+ Request req;
+ req.method = "GET";
+ req.path = path;
+ req.headers = headers;
+ req.progress = std::move(progress);
+
+ return send_(std::move(req));
+}
+
+inline Result ClientImpl::Get(const char *path,
+ ContentReceiver content_receiver) {
+ return Get(path, Headers(), nullptr, std::move(content_receiver), nullptr);
+}
+
+inline Result ClientImpl::Get(const char *path,
+ ContentReceiver content_receiver,
+ Progress progress) {
+ return Get(path, Headers(), nullptr, std::move(content_receiver),
+ std::move(progress));
+}
+
+inline Result ClientImpl::Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver) {
+ return Get(path, headers, nullptr, std::move(content_receiver), nullptr);
+}
+
+inline Result ClientImpl::Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver,
+ Progress progress) {
+ return Get(path, headers, nullptr, std::move(content_receiver),
+ std::move(progress));
+}
+
+inline Result ClientImpl::Get(const char *path,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver) {
+ return Get(path, Headers(), std::move(response_handler),
+ std::move(content_receiver), nullptr);
+}
+
+inline Result ClientImpl::Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver) {
+ return Get(path, headers, std::move(response_handler),
+ std::move(content_receiver), nullptr);
+}
+
+inline Result ClientImpl::Get(const char *path,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver,
+ Progress progress) {
+ return Get(path, Headers(), std::move(response_handler),
+ std::move(content_receiver), std::move(progress));
+}
+
+inline Result ClientImpl::Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver,
+ Progress progress) {
+ Request req;
+ req.method = "GET";
+ req.path = path;
+ req.headers = headers;
+ req.response_handler = std::move(response_handler);
+ req.content_receiver =
+ [content_receiver](const char *data, size_t data_length,
+ uint64_t /*offset*/, uint64_t /*total_length*/) {
+ return content_receiver(data, data_length);
+ };
+ req.progress = std::move(progress);
+
+ return send_(std::move(req));
+}
+
+inline Result ClientImpl::Get(const char *path, const Params &params,
+ const Headers &headers, Progress progress) {
+ if (params.empty()) { return Get(path, headers); }
+
+ std::string path_with_query = detail::append_query_params(path, params);
+ return Get(path_with_query.c_str(), headers, progress);
+}
+
+inline Result ClientImpl::Get(const char *path, const Params &params,
+ const Headers &headers,
+ ContentReceiver content_receiver,
+ Progress progress) {
+ return Get(path, params, headers, nullptr, content_receiver, progress);
+}
+
+inline Result ClientImpl::Get(const char *path, const Params &params,
+ const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver,
+ Progress progress) {
+ if (params.empty()) {
+ return Get(path, headers, response_handler, content_receiver, progress);
+ }
+
+ std::string path_with_query = detail::append_query_params(path, params);
+ return Get(path_with_query.c_str(), headers, response_handler,
+ content_receiver, progress);
+}
+
+inline Result ClientImpl::Head(const char *path) {
+ return Head(path, Headers());
+}
+
+inline Result ClientImpl::Head(const char *path, const Headers &headers) {
+ Request req;
+ req.method = "HEAD";
+ req.headers = headers;
+ req.path = path;
+
+ return send_(std::move(req));
+}
+
+inline Result ClientImpl::Post(const char *path) {
+ return Post(path, std::string(), nullptr);
+}
+
+inline Result ClientImpl::Post(const char *path, const char *body,
+ size_t content_length,
+ const char *content_type) {
+ return Post(path, Headers(), body, content_length, content_type);
+}
+
+inline Result ClientImpl::Post(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ return send_with_content_provider("POST", path, headers, body, content_length,
+ nullptr, nullptr, content_type);
+}
+
+inline Result ClientImpl::Post(const char *path, const std::string &body,
+ const char *content_type) {
+ return Post(path, Headers(), body, content_type);
+}
+
+inline Result ClientImpl::Post(const char *path, const Headers &headers,
+ const std::string &body,
+ const char *content_type) {
+ return send_with_content_provider("POST", path, headers, body.data(),
+ body.size(), nullptr, nullptr,
+ content_type);
+}
+
+inline Result ClientImpl::Post(const char *path, const Params &params) {
+ return Post(path, Headers(), params);
+}
+
+inline Result ClientImpl::Post(const char *path, size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return Post(path, Headers(), content_length, std::move(content_provider),
+ content_type);
+}
+
+inline Result ClientImpl::Post(const char *path,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return Post(path, Headers(), std::move(content_provider), content_type);
+}
+
+inline Result ClientImpl::Post(const char *path, const Headers &headers,
+ size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return send_with_content_provider("POST", path, headers, nullptr,
+ content_length, std::move(content_provider),
+ nullptr, content_type);
+}
+
+inline Result ClientImpl::Post(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return send_with_content_provider("POST", path, headers, nullptr, 0, nullptr,
+ std::move(content_provider), content_type);
+}
+
+inline Result ClientImpl::Post(const char *path, const Headers &headers,
+ const Params &params) {
+ auto query = detail::params_to_query_str(params);
+ return Post(path, headers, query, "application/x-www-form-urlencoded");
+}
+
+inline Result ClientImpl::Post(const char *path,
+ const MultipartFormDataItems &items) {
+ return Post(path, Headers(), items);
+}
+
+inline Result ClientImpl::Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items) {
+ return Post(path, headers, items, detail::make_multipart_data_boundary());
+}
+inline Result ClientImpl::Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items,
+ const std::string &boundary) {
+ for (size_t i = 0; i < boundary.size(); i++) {
+ char c = boundary[i];
+ if (!std::isalnum(c) && c != '-' && c != '_') {
+ return Result{nullptr, Error::UnsupportedMultipartBoundaryChars};
+ }
+ }
+
+ std::string body;
+
+ for (const auto &item : items) {
+ body += "--" + boundary + "\r\n";
+ body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
+ if (!item.filename.empty()) {
+ body += "; filename=\"" + item.filename + "\"";
+ }
+ body += "\r\n";
+ if (!item.content_type.empty()) {
+ body += "Content-Type: " + item.content_type + "\r\n";
+ }
+ body += "\r\n";
+ body += item.content + "\r\n";
+ }
+
+ body += "--" + boundary + "--\r\n";
+
+ std::string content_type = "multipart/form-data; boundary=" + boundary;
+ return Post(path, headers, body, content_type.c_str());
+}
+
+inline Result ClientImpl::Put(const char *path) {
+ return Put(path, std::string(), nullptr);
+}
+
+inline Result ClientImpl::Put(const char *path, const char *body,
+ size_t content_length, const char *content_type) {
+ return Put(path, Headers(), body, content_length, content_type);
+}
+
+inline Result ClientImpl::Put(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ return send_with_content_provider("PUT", path, headers, body, content_length,
+ nullptr, nullptr, content_type);
+}
+
+inline Result ClientImpl::Put(const char *path, const std::string &body,
+ const char *content_type) {
+ return Put(path, Headers(), body, content_type);
+}
+
+inline Result ClientImpl::Put(const char *path, const Headers &headers,
+ const std::string &body,
+ const char *content_type) {
+ return send_with_content_provider("PUT", path, headers, body.data(),
+ body.size(), nullptr, nullptr,
+ content_type);
+}
+
+inline Result ClientImpl::Put(const char *path, size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return Put(path, Headers(), content_length, std::move(content_provider),
+ content_type);
+}
+
+inline Result ClientImpl::Put(const char *path,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return Put(path, Headers(), std::move(content_provider), content_type);
+}
+
+inline Result ClientImpl::Put(const char *path, const Headers &headers,
+ size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return send_with_content_provider("PUT", path, headers, nullptr,
+ content_length, std::move(content_provider),
+ nullptr, content_type);
+}
+
+inline Result ClientImpl::Put(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return send_with_content_provider("PUT", path, headers, nullptr, 0, nullptr,
+ std::move(content_provider), content_type);
+}
+
+inline Result ClientImpl::Put(const char *path, const Params &params) {
+ return Put(path, Headers(), params);
+}
+
+inline Result ClientImpl::Put(const char *path, const Headers &headers,
+ const Params &params) {
+ auto query = detail::params_to_query_str(params);
+ return Put(path, headers, query, "application/x-www-form-urlencoded");
+}
+
+inline Result ClientImpl::Patch(const char *path) {
+ return Patch(path, std::string(), nullptr);
+}
+
+inline Result ClientImpl::Patch(const char *path, const char *body,
+ size_t content_length,
+ const char *content_type) {
+ return Patch(path, Headers(), body, content_length, content_type);
+}
+
+inline Result ClientImpl::Patch(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ return send_with_content_provider("PATCH", path, headers, body,
+ content_length, nullptr, nullptr,
+ content_type);
+}
+
+inline Result ClientImpl::Patch(const char *path, const std::string &body,
+ const char *content_type) {
+ return Patch(path, Headers(), body, content_type);
+}
+
+inline Result ClientImpl::Patch(const char *path, const Headers &headers,
+ const std::string &body,
+ const char *content_type) {
+ return send_with_content_provider("PATCH", path, headers, body.data(),
+ body.size(), nullptr, nullptr,
+ content_type);
+}
+
+inline Result ClientImpl::Patch(const char *path, size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return Patch(path, Headers(), content_length, std::move(content_provider),
+ content_type);
+}
+
+inline Result ClientImpl::Patch(const char *path,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return Patch(path, Headers(), std::move(content_provider), content_type);
+}
+
+inline Result ClientImpl::Patch(const char *path, const Headers &headers,
+ size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return send_with_content_provider("PATCH", path, headers, nullptr,
+ content_length, std::move(content_provider),
+ nullptr, content_type);
+}
+
+inline Result ClientImpl::Patch(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return send_with_content_provider("PATCH", path, headers, nullptr, 0, nullptr,
+ std::move(content_provider), content_type);
+}
+
+inline Result ClientImpl::Delete(const char *path) {
+ return Delete(path, Headers(), std::string(), nullptr);
+}
+
+inline Result ClientImpl::Delete(const char *path, const Headers &headers) {
+ return Delete(path, headers, std::string(), nullptr);
+}
+
+inline Result ClientImpl::Delete(const char *path, const char *body,
+ size_t content_length,
+ const char *content_type) {
+ return Delete(path, Headers(), body, content_length, content_type);
+}
+
+inline Result ClientImpl::Delete(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ Request req;
+ req.method = "DELETE";
+ req.headers = headers;
+ req.path = path;
+
+ if (content_type) { req.headers.emplace("Content-Type", content_type); }
+ req.body.assign(body, content_length);
+
+ return send_(std::move(req));
+}
+
+inline Result ClientImpl::Delete(const char *path, const std::string &body,
+ const char *content_type) {
+ return Delete(path, Headers(), body.data(), body.size(), content_type);
+}
+
+inline Result ClientImpl::Delete(const char *path, const Headers &headers,
+ const std::string &body,
+ const char *content_type) {
+ return Delete(path, headers, body.data(), body.size(), content_type);
+}
+
+inline Result ClientImpl::Options(const char *path) {
+ return Options(path, Headers());
+}
+
+inline Result ClientImpl::Options(const char *path, const Headers &headers) {
+ Request req;
+ req.method = "OPTIONS";
+ req.headers = headers;
+ req.path = path;
+
+ return send_(std::move(req));
+}
+
+inline size_t ClientImpl::is_socket_open() const {
+ std::lock_guard<std::mutex> guard(socket_mutex_);
+ return socket_.is_open();
+}
+
+inline void ClientImpl::stop() {
+ std::lock_guard<std::mutex> guard(socket_mutex_);
+
+ // If there is anything ongoing right now, the ONLY thread-safe thing we can
+ // do is to shutdown_socket, so that threads using this socket suddenly
+ // discover they can't read/write any more and error out. Everything else
+ // (closing the socket, shutting ssl down) is unsafe because these actions are
+ // not thread-safe.
+ if (socket_requests_in_flight_ > 0) {
+ shutdown_socket(socket_);
+
+ // Aside from that, we set a flag for the socket to be closed when we're
+ // done.
+ socket_should_be_closed_when_request_is_done_ = true;
+ return;
+ }
+
+ // Otherwise, sitll holding the mutex, we can shut everything down ourselves
+ shutdown_ssl(socket_, true);
+ shutdown_socket(socket_);
+ close_socket(socket_);
+}
+
+inline void ClientImpl::set_connection_timeout(time_t sec, time_t usec) {
+ connection_timeout_sec_ = sec;
+ connection_timeout_usec_ = usec;
+}
+
+inline void ClientImpl::set_read_timeout(time_t sec, time_t usec) {
+ read_timeout_sec_ = sec;
+ read_timeout_usec_ = usec;
+}
+
+inline void ClientImpl::set_write_timeout(time_t sec, time_t usec) {
+ write_timeout_sec_ = sec;
+ write_timeout_usec_ = usec;
+}
+
+inline void ClientImpl::set_basic_auth(const char *username,
+ const char *password) {
+ basic_auth_username_ = username;
+ basic_auth_password_ = password;
+}
+
+inline void ClientImpl::set_bearer_token_auth(const char *token) {
+ bearer_token_auth_token_ = token;
+}
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void ClientImpl::set_digest_auth(const char *username,
+ const char *password) {
+ digest_auth_username_ = username;
+ digest_auth_password_ = password;
+}
+#endif
+
+inline void ClientImpl::set_keep_alive(bool on) { keep_alive_ = on; }
+
+inline void ClientImpl::set_follow_location(bool on) { follow_location_ = on; }
+
+inline void ClientImpl::set_url_encode(bool on) { url_encode_ = on; }
+
+inline void ClientImpl::set_default_headers(Headers headers) {
+ default_headers_ = std::move(headers);
+}
+
+inline void ClientImpl::set_address_family(int family) {
+ address_family_ = family;
+}
+
+inline void ClientImpl::set_tcp_nodelay(bool on) { tcp_nodelay_ = on; }
+
+inline void ClientImpl::set_socket_options(SocketOptions socket_options) {
+ socket_options_ = std::move(socket_options);
+}
+
+inline void ClientImpl::set_compress(bool on) { compress_ = on; }
+
+inline void ClientImpl::set_decompress(bool on) { decompress_ = on; }
+
+inline void ClientImpl::set_interface(const char *intf) { interface_ = intf; }
+
+inline void ClientImpl::set_proxy(const char *host, int port) {
+ proxy_host_ = host;
+ proxy_port_ = port;
+}
+
+inline void ClientImpl::set_proxy_basic_auth(const char *username,
+ const char *password) {
+ proxy_basic_auth_username_ = username;
+ proxy_basic_auth_password_ = password;
+}
+
+inline void ClientImpl::set_proxy_bearer_token_auth(const char *token) {
+ proxy_bearer_token_auth_token_ = token;
+}
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void ClientImpl::set_proxy_digest_auth(const char *username,
+ const char *password) {
+ proxy_digest_auth_username_ = username;
+ proxy_digest_auth_password_ = password;
+}
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void ClientImpl::set_ca_cert_path(const char *ca_cert_file_path,
+ const char *ca_cert_dir_path) {
+ if (ca_cert_file_path) { ca_cert_file_path_ = ca_cert_file_path; }
+ if (ca_cert_dir_path) { ca_cert_dir_path_ = ca_cert_dir_path; }
+}
+
+inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) {
+ if (ca_cert_store && ca_cert_store != ca_cert_store_) {
+ ca_cert_store_ = ca_cert_store;
+ }
+}
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void ClientImpl::enable_server_certificate_verification(bool enabled) {
+ server_certificate_verification_ = enabled;
+}
+#endif
+
+inline void ClientImpl::set_logger(Logger logger) {
+ logger_ = std::move(logger);
+}
+
+/*
+ * SSL Implementation
+ */
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+namespace detail {
+
+template <typename U, typename V>
+inline SSL *ssl_new(socket_t sock, SSL_CTX *ctx, std::mutex &ctx_mutex,
+ U SSL_connect_or_accept, V setup) {
+ SSL *ssl = nullptr;
+ {
+ std::lock_guard<std::mutex> guard(ctx_mutex);
+ ssl = SSL_new(ctx);
+ }
+
+ if (ssl) {
+ set_nonblocking(sock, true);
+ auto bio = BIO_new_socket(static_cast<int>(sock), BIO_NOCLOSE);
+ BIO_set_nbio(bio, 1);
+ SSL_set_bio(ssl, bio, bio);
+
+ if (!setup(ssl) || SSL_connect_or_accept(ssl) != 1) {
+ SSL_shutdown(ssl);
+ {
+ std::lock_guard<std::mutex> guard(ctx_mutex);
+ SSL_free(ssl);
+ }
+ set_nonblocking(sock, false);
+ return nullptr;
+ }
+ BIO_set_nbio(bio, 0);
+ set_nonblocking(sock, false);
+ }
+
+ return ssl;
+}
+
+inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl,
+ bool shutdown_gracefully) {
+ // sometimes we may want to skip this to try to avoid SIGPIPE if we know
+ // the remote has closed the network connection
+ // Note that it is not always possible to avoid SIGPIPE, this is merely a
+ // best-efforts.
+ if (shutdown_gracefully) { SSL_shutdown(ssl); }
+
+ std::lock_guard<std::mutex> guard(ctx_mutex);
+ SSL_free(ssl);
+}
+
+template <typename U>
+bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl,
+ U ssl_connect_or_accept,
+ time_t timeout_sec,
+ time_t timeout_usec) {
+ int res = 0;
+ while ((res = ssl_connect_or_accept(ssl)) != 1) {
+ auto err = SSL_get_error(ssl, res);
+ switch (err) {
+ case SSL_ERROR_WANT_READ:
+ if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; }
+ break;
+ case SSL_ERROR_WANT_WRITE:
+ if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; }
+ break;
+ default: break;
+ }
+ return false;
+ }
+ return true;
+}
+
+template <typename T>
+inline bool
+process_server_socket_ssl(SSL *ssl, socket_t sock, size_t keep_alive_max_count,
+ time_t keep_alive_timeout_sec,
+ time_t read_timeout_sec, time_t read_timeout_usec,
+ time_t write_timeout_sec, time_t write_timeout_usec,
+ T callback) {
+ return process_server_socket_core(
+ sock, keep_alive_max_count, keep_alive_timeout_sec,
+ [&](bool close_connection, bool &connection_closed) {
+ SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
+ write_timeout_sec, write_timeout_usec);
+ return callback(strm, close_connection, connection_closed);
+ });
+}
+
+template <typename T>
+inline bool
+process_client_socket_ssl(SSL *ssl, socket_t sock, time_t read_timeout_sec,
+ time_t read_timeout_usec, time_t write_timeout_sec,
+ time_t write_timeout_usec, T callback) {
+ SSLSocketStream strm(sock, ssl, read_timeout_sec, read_timeout_usec,
+ write_timeout_sec, write_timeout_usec);
+ return callback(strm);
+}
+
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+static std::shared_ptr<std::vector<std::mutex>> openSSL_locks_;
+
+class SSLThreadLocks {
+public:
+ SSLThreadLocks() {
+ openSSL_locks_ =
+ std::make_shared<std::vector<std::mutex>>(CRYPTO_num_locks());
+ CRYPTO_set_locking_callback(locking_callback);
+ }
+
+ ~SSLThreadLocks() { CRYPTO_set_locking_callback(nullptr); }
+
+private:
+ static void locking_callback(int mode, int type, const char * /*file*/,
+ int /*line*/) {
+ auto &lk = (*openSSL_locks_)[static_cast<size_t>(type)];
+ if (mode & CRYPTO_LOCK) {
+ lk.lock();
+ } else {
+ lk.unlock();
+ }
+ }
+};
+
+#endif
+
+class SSLInit {
+public:
+ SSLInit() {
+#if OPENSSL_VERSION_NUMBER < 0x1010001fL
+ SSL_load_error_strings();
+ SSL_library_init();
+#else
+ OPENSSL_init_ssl(
+ OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL);
+#endif
+ }
+
+ ~SSLInit() {
+#if OPENSSL_VERSION_NUMBER < 0x1010001fL
+ ERR_free_strings();
+#endif
+ }
+
+private:
+#if OPENSSL_VERSION_NUMBER < 0x10100000L
+ SSLThreadLocks thread_init_;
+#endif
+};
+
+// SSL socket stream implementation
+inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl,
+ time_t read_timeout_sec,
+ time_t read_timeout_usec,
+ time_t write_timeout_sec,
+ time_t write_timeout_usec)
+ : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec),
+ read_timeout_usec_(read_timeout_usec),
+ write_timeout_sec_(write_timeout_sec),
+ write_timeout_usec_(write_timeout_usec) {
+ SSL_clear_mode(ssl, SSL_MODE_AUTO_RETRY);
+}
+
+inline SSLSocketStream::~SSLSocketStream() {}
+
+inline bool SSLSocketStream::is_readable() const {
+ return detail::select_read(sock_, read_timeout_sec_, read_timeout_usec_) > 0;
+}
+
+inline bool SSLSocketStream::is_writable() const {
+ return detail::select_write(sock_, write_timeout_sec_, write_timeout_usec_) >
+ 0;
+}
+
+inline ssize_t SSLSocketStream::read(char *ptr, size_t size) {
+ if (SSL_pending(ssl_) > 0) {
+ return SSL_read(ssl_, ptr, static_cast<int>(size));
+ } else if (is_readable()) {
+ auto ret = SSL_read(ssl_, ptr, static_cast<int>(size));
+ if (ret < 0) {
+ auto err = SSL_get_error(ssl_, ret);
+ int n = 1000;
+#ifdef _WIN32
+ while (--n >= 0 &&
+ (err == SSL_ERROR_WANT_READ ||
+ err == SSL_ERROR_SYSCALL && WSAGetLastError() == WSAETIMEDOUT)) {
+#else
+ while (--n >= 0 && err == SSL_ERROR_WANT_READ) {
+#endif
+ if (SSL_pending(ssl_) > 0) {
+ return SSL_read(ssl_, ptr, static_cast<int>(size));
+ } else if (is_readable()) {
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ ret = SSL_read(ssl_, ptr, static_cast<int>(size));
+ if (ret >= 0) { return ret; }
+ err = SSL_get_error(ssl_, ret);
+ } else {
+ return -1;
+ }
+ }
+ }
+ return ret;
+ }
+ return -1;
+}
+
+inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) {
+ if (is_writable()) { return SSL_write(ssl_, ptr, static_cast<int>(size)); }
+ return -1;
+}
+
+inline void SSLSocketStream::get_remote_ip_and_port(std::string &ip,
+ int &port) const {
+ detail::get_remote_ip_and_port(sock_, ip, port);
+}
+
+inline socket_t SSLSocketStream::socket() const { return sock_; }
+
+static SSLInit sslinit_;
+
+} // namespace detail
+
+// SSL HTTP server implementation
+inline SSLServer::SSLServer(const char *cert_path, const char *private_key_path,
+ const char *client_ca_cert_file_path,
+ const char *client_ca_cert_dir_path) {
+ ctx_ = SSL_CTX_new(TLS_method());
+
+ if (ctx_) {
+ SSL_CTX_set_options(ctx_,
+ SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
+ SSL_OP_NO_COMPRESSION |
+ SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
+
+ // auto ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
+ // SSL_CTX_set_tmp_ecdh(ctx_, ecdh);
+ // EC_KEY_free(ecdh);
+
+ if (SSL_CTX_use_certificate_chain_file(ctx_, cert_path) != 1 ||
+ SSL_CTX_use_PrivateKey_file(ctx_, private_key_path, SSL_FILETYPE_PEM) !=
+ 1) {
+ SSL_CTX_free(ctx_);
+ ctx_ = nullptr;
+ } else if (client_ca_cert_file_path || client_ca_cert_dir_path) {
+ // if (client_ca_cert_file_path) {
+ // auto list = SSL_load_client_CA_file(client_ca_cert_file_path);
+ // SSL_CTX_set_client_CA_list(ctx_, list);
+ // }
+
+ SSL_CTX_load_verify_locations(ctx_, client_ca_cert_file_path,
+ client_ca_cert_dir_path);
+
+ SSL_CTX_set_verify(
+ ctx_,
+ SSL_VERIFY_PEER |
+ SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
+ nullptr);
+ }
+ }
+}
+
+inline SSLServer::SSLServer(X509 *cert, EVP_PKEY *private_key,
+ X509_STORE *client_ca_cert_store) {
+ ctx_ = SSL_CTX_new(SSLv23_server_method());
+
+ if (ctx_) {
+ SSL_CTX_set_options(ctx_,
+ SSL_OP_ALL | SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
+ SSL_OP_NO_COMPRESSION |
+ SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION);
+
+ if (SSL_CTX_use_certificate(ctx_, cert) != 1 ||
+ SSL_CTX_use_PrivateKey(ctx_, private_key) != 1) {
+ SSL_CTX_free(ctx_);
+ ctx_ = nullptr;
+ } else if (client_ca_cert_store) {
+
+ SSL_CTX_set_cert_store(ctx_, client_ca_cert_store);
+
+ SSL_CTX_set_verify(
+ ctx_,
+ SSL_VERIFY_PEER |
+ SSL_VERIFY_FAIL_IF_NO_PEER_CERT, // SSL_VERIFY_CLIENT_ONCE,
+ nullptr);
+ }
+ }
+}
+
+inline SSLServer::~SSLServer() {
+ if (ctx_) { SSL_CTX_free(ctx_); }
+}
+
+inline bool SSLServer::is_valid() const { return ctx_; }
+
+inline bool SSLServer::process_and_close_socket(socket_t sock) {
+ auto ssl = detail::ssl_new(
+ sock, ctx_, ctx_mutex_,
+ [&](SSL *ssl) {
+ return detail::ssl_connect_or_accept_nonblocking(
+ sock, ssl, SSL_accept, read_timeout_sec_, read_timeout_usec_);
+ },
+ [](SSL * /*ssl*/) { return true; });
+
+ bool ret = false;
+ if (ssl) {
+ ret = detail::process_server_socket_ssl(
+ ssl, sock, keep_alive_max_count_, keep_alive_timeout_sec_,
+ read_timeout_sec_, read_timeout_usec_, write_timeout_sec_,
+ write_timeout_usec_,
+ [this, ssl](Stream &strm, bool close_connection,
+ bool &connection_closed) {
+ return process_request(strm, close_connection, connection_closed,
+ [&](Request &req) { req.ssl = ssl; });
+ });
+
+ // Shutdown gracefully if the result seemed successful, non-gracefully if
+ // the connection appeared to be closed.
+ const bool shutdown_gracefully = ret;
+ detail::ssl_delete(ctx_mutex_, ssl, shutdown_gracefully);
+ }
+
+ detail::shutdown_socket(sock);
+ detail::close_socket(sock);
+ return ret;
+}
+
+// SSL HTTP client implementation
+inline SSLClient::SSLClient(const std::string &host)
+ : SSLClient(host, 443, std::string(), std::string()) {}
+
+inline SSLClient::SSLClient(const std::string &host, int port)
+ : SSLClient(host, port, std::string(), std::string()) {}
+
+inline SSLClient::SSLClient(const std::string &host, int port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path)
+ : ClientImpl(host, port, client_cert_path, client_key_path) {
+ ctx_ = SSL_CTX_new(SSLv23_client_method());
+
+ detail::split(&host_[0], &host_[host_.size()], '.',
+ [&](const char *b, const char *e) {
+ host_components_.emplace_back(std::string(b, e));
+ });
+ if (!client_cert_path.empty() && !client_key_path.empty()) {
+ if (SSL_CTX_use_certificate_file(ctx_, client_cert_path.c_str(),
+ SSL_FILETYPE_PEM) != 1 ||
+ SSL_CTX_use_PrivateKey_file(ctx_, client_key_path.c_str(),
+ SSL_FILETYPE_PEM) != 1) {
+ SSL_CTX_free(ctx_);
+ ctx_ = nullptr;
+ }
+ }
+}
+
+inline SSLClient::SSLClient(const std::string &host, int port,
+ X509 *client_cert, EVP_PKEY *client_key)
+ : ClientImpl(host, port) {
+ ctx_ = SSL_CTX_new(SSLv23_client_method());
+
+ detail::split(&host_[0], &host_[host_.size()], '.',
+ [&](const char *b, const char *e) {
+ host_components_.emplace_back(std::string(b, e));
+ });
+ if (client_cert != nullptr && client_key != nullptr) {
+ if (SSL_CTX_use_certificate(ctx_, client_cert) != 1 ||
+ SSL_CTX_use_PrivateKey(ctx_, client_key) != 1) {
+ SSL_CTX_free(ctx_);
+ ctx_ = nullptr;
+ }
+ }
+}
+
+inline SSLClient::~SSLClient() {
+ if (ctx_) { SSL_CTX_free(ctx_); }
+ // Make sure to shut down SSL since shutdown_ssl will resolve to the
+ // base function rather than the derived function once we get to the
+ // base class destructor, and won't free the SSL (causing a leak).
+ shutdown_ssl_impl(socket_, true);
+}
+
+inline bool SSLClient::is_valid() const { return ctx_; }
+
+inline void SSLClient::set_ca_cert_store(X509_STORE *ca_cert_store) {
+ if (ca_cert_store) {
+ if (ctx_) {
+ if (SSL_CTX_get_cert_store(ctx_) != ca_cert_store) {
+ // Free memory allocated for old cert and use new store `ca_cert_store`
+ SSL_CTX_set_cert_store(ctx_, ca_cert_store);
+ }
+ } else {
+ X509_STORE_free(ca_cert_store);
+ }
+ }
+}
+
+inline long SSLClient::get_openssl_verify_result() const {
+ return verify_result_;
+}
+
+inline SSL_CTX *SSLClient::ssl_context() const { return ctx_; }
+
+inline bool SSLClient::create_and_connect_socket(Socket &socket, Error &error) {
+ return is_valid() && ClientImpl::create_and_connect_socket(socket, error);
+}
+
+// Assumes that socket_mutex_ is locked and that there are no requests in flight
+inline bool SSLClient::connect_with_proxy(Socket &socket, Response &res,
+ bool &success, Error &error) {
+ success = true;
+ Response res2;
+ if (!detail::process_client_socket(
+ socket.sock, read_timeout_sec_, read_timeout_usec_,
+ write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
+ Request req2;
+ req2.method = "CONNECT";
+ req2.path = host_and_port_;
+ return process_request(strm, req2, res2, false, error);
+ })) {
+ // Thread-safe to close everything because we are assuming there are no
+ // requests in flight
+ shutdown_ssl(socket, true);
+ shutdown_socket(socket);
+ close_socket(socket);
+ success = false;
+ return false;
+ }
+
+ if (res2.status == 407) {
+ if (!proxy_digest_auth_username_.empty() &&
+ !proxy_digest_auth_password_.empty()) {
+ std::map<std::string, std::string> auth;
+ if (detail::parse_www_authenticate(res2, auth, true)) {
+ Response res3;
+ if (!detail::process_client_socket(
+ socket.sock, read_timeout_sec_, read_timeout_usec_,
+ write_timeout_sec_, write_timeout_usec_, [&](Stream &strm) {
+ Request req3;
+ req3.method = "CONNECT";
+ req3.path = host_and_port_;
+ req3.headers.insert(detail::make_digest_authentication_header(
+ req3, auth, 1, detail::random_string(10),
+ proxy_digest_auth_username_, proxy_digest_auth_password_,
+ true));
+ return process_request(strm, req3, res3, false, error);
+ })) {
+ // Thread-safe to close everything because we are assuming there are
+ // no requests in flight
+ shutdown_ssl(socket, true);
+ shutdown_socket(socket);
+ close_socket(socket);
+ success = false;
+ return false;
+ }
+ }
+ } else {
+ res = res2;
+ return false;
+ }
+ }
+
+ return true;
+}
+
+inline bool SSLClient::load_certs() {
+ bool ret = true;
+
+ std::call_once(initialize_cert_, [&]() {
+ std::lock_guard<std::mutex> guard(ctx_mutex_);
+ if (!ca_cert_file_path_.empty()) {
+ if (!SSL_CTX_load_verify_locations(ctx_, ca_cert_file_path_.c_str(),
+ nullptr)) {
+ ret = false;
+ }
+ } else if (!ca_cert_dir_path_.empty()) {
+ if (!SSL_CTX_load_verify_locations(ctx_, nullptr,
+ ca_cert_dir_path_.c_str())) {
+ ret = false;
+ }
+ } else {
+#ifdef _WIN32
+ detail::load_system_certs_on_windows(SSL_CTX_get_cert_store(ctx_));
+#else
+ SSL_CTX_set_default_verify_paths(ctx_);
+#endif
+ }
+ });
+
+ return ret;
+}
+
+inline bool SSLClient::initialize_ssl(Socket &socket, Error &error) {
+ auto ssl = detail::ssl_new(
+ socket.sock, ctx_, ctx_mutex_,
+ [&](SSL *ssl) {
+ if (server_certificate_verification_) {
+ if (!load_certs()) {
+ error = Error::SSLLoadingCerts;
+ return false;
+ }
+ SSL_set_verify(ssl, SSL_VERIFY_NONE, nullptr);
+ }
+
+ if (!detail::ssl_connect_or_accept_nonblocking(
+ socket.sock, ssl, SSL_connect, connection_timeout_sec_,
+ connection_timeout_usec_)) {
+ error = Error::SSLConnection;
+ return false;
+ }
+
+ if (server_certificate_verification_) {
+ verify_result_ = SSL_get_verify_result(ssl);
+
+ if (verify_result_ != X509_V_OK) {
+ error = Error::SSLServerVerification;
+ return false;
+ }
+
+ auto server_cert = SSL_get_peer_certificate(ssl);
+
+ if (server_cert == nullptr) {
+ error = Error::SSLServerVerification;
+ return false;
+ }
+
+ if (!verify_host(server_cert)) {
+ X509_free(server_cert);
+ error = Error::SSLServerVerification;
+ return false;
+ }
+ X509_free(server_cert);
+ }
+
+ return true;
+ },
+ [&](SSL *ssl) {
+ SSL_set_tlsext_host_name(ssl, host_.c_str());
+ return true;
+ });
+
+ if (ssl) {
+ socket.ssl = ssl;
+ return true;
+ }
+
+ shutdown_socket(socket);
+ close_socket(socket);
+ return false;
+}
+
+inline void SSLClient::shutdown_ssl(Socket &socket, bool shutdown_gracefully) {
+ shutdown_ssl_impl(socket, shutdown_gracefully);
+}
+
+inline void SSLClient::shutdown_ssl_impl(Socket &socket,
+ bool shutdown_gracefully) {
+ if (socket.sock == INVALID_SOCKET) {
+ assert(socket.ssl == nullptr);
+ return;
+ }
+ if (socket.ssl) {
+ detail::ssl_delete(ctx_mutex_, socket.ssl, shutdown_gracefully);
+ socket.ssl = nullptr;
+ }
+ assert(socket.ssl == nullptr);
+}
+
+inline bool
+SSLClient::process_socket(const Socket &socket,
+ std::function<bool(Stream &strm)> callback) {
+ assert(socket.ssl);
+ return detail::process_client_socket_ssl(
+ socket.ssl, socket.sock, read_timeout_sec_, read_timeout_usec_,
+ write_timeout_sec_, write_timeout_usec_, std::move(callback));
+}
+
+inline bool SSLClient::is_ssl() const { return true; }
+
+inline bool SSLClient::verify_host(X509 *server_cert) const {
+ /* Quote from RFC2818 section 3.1 "Server Identity"
+
+ If a subjectAltName extension of type dNSName is present, that MUST
+ be used as the identity. Otherwise, the (most specific) Common Name
+ field in the Subject field of the certificate MUST be used. Although
+ the use of the Common Name is existing practice, it is deprecated and
+ Certification Authorities are encouraged to use the dNSName instead.
+
+ Matching is performed using the matching rules specified by
+ [RFC2459]. If more than one identity of a given type is present in
+ the certificate (e.g., more than one dNSName name, a match in any one
+ of the set is considered acceptable.) Names may contain the wildcard
+ character * which is considered to match any single domain name
+ component or component fragment. E.g., *.a.com matches foo.a.com but
+ not bar.foo.a.com. f*.com matches foo.com but not bar.com.
+
+ In some cases, the URI is specified as an IP address rather than a
+ hostname. In this case, the iPAddress subjectAltName must be present
+ in the certificate and must exactly match the IP in the URI.
+
+ */
+ return verify_host_with_subject_alt_name(server_cert) ||
+ verify_host_with_common_name(server_cert);
+}
+
+inline bool
+SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const {
+ auto ret = false;
+
+ auto type = GEN_DNS;
+
+ struct in6_addr addr6;
+ struct in_addr addr;
+ size_t addr_len = 0;
+
+#ifndef __MINGW32__
+ if (inet_pton(AF_INET6, host_.c_str(), &addr6)) {
+ type = GEN_IPADD;
+ addr_len = sizeof(struct in6_addr);
+ } else if (inet_pton(AF_INET, host_.c_str(), &addr)) {
+ type = GEN_IPADD;
+ addr_len = sizeof(struct in_addr);
+ }
+#endif
+
+ auto alt_names = static_cast<const struct stack_st_GENERAL_NAME *>(
+ X509_get_ext_d2i(server_cert, NID_subject_alt_name, nullptr, nullptr));
+
+ if (alt_names) {
+ auto dsn_matched = false;
+ auto ip_mached = false;
+
+ auto count = sk_GENERAL_NAME_num(alt_names);
+
+ for (decltype(count) i = 0; i < count && !dsn_matched; i++) {
+ auto val = sk_GENERAL_NAME_value(alt_names, i);
+ if (val->type == type) {
+ auto name = (const char *)ASN1_STRING_get0_data(val->d.ia5);
+ auto name_len = (size_t)ASN1_STRING_length(val->d.ia5);
+
+ switch (type) {
+ case GEN_DNS: dsn_matched = check_host_name(name, name_len); break;
+
+ case GEN_IPADD:
+ if (!memcmp(&addr6, name, addr_len) ||
+ !memcmp(&addr, name, addr_len)) {
+ ip_mached = true;
+ }
+ break;
+ }
+ }
+ }
+
+ if (dsn_matched || ip_mached) { ret = true; }
+ }
+
+ GENERAL_NAMES_free((STACK_OF(GENERAL_NAME) *)alt_names);
+ return ret;
+}
+
+inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const {
+ const auto subject_name = X509_get_subject_name(server_cert);
+
+ if (subject_name != nullptr) {
+ char name[BUFSIZ];
+ auto name_len = X509_NAME_get_text_by_NID(subject_name, NID_commonName,
+ name, sizeof(name));
+
+ if (name_len != -1) {
+ return check_host_name(name, static_cast<size_t>(name_len));
+ }
+ }
+
+ return false;
+}
+
+inline bool SSLClient::check_host_name(const char *pattern,
+ size_t pattern_len) const {
+ if (host_.size() == pattern_len && host_ == pattern) { return true; }
+
+ // Wildcard match
+ // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484
+ std::vector<std::string> pattern_components;
+ detail::split(&pattern[0], &pattern[pattern_len], '.',
+ [&](const char *b, const char *e) {
+ pattern_components.emplace_back(std::string(b, e));
+ });
+
+ if (host_components_.size() != pattern_components.size()) { return false; }
+
+ auto itr = pattern_components.begin();
+ for (const auto &h : host_components_) {
+ auto &p = *itr;
+ if (p != h && p != "*") {
+ auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' &&
+ !p.compare(0, p.size() - 1, h));
+ if (!partial_match) { return false; }
+ }
+ ++itr;
+ }
+
+ return true;
+}
+#endif
+
+// Universal client implementation
+inline Client::Client(const std::string &scheme_host_port)
+ : Client(scheme_host_port, std::string(), std::string()) {}
+
+inline Client::Client(const std::string &scheme_host_port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path) {
+ const static std::regex re(
+ R"((?:([a-z]+):\/\/)?(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)");
+
+ std::smatch m;
+ if (std::regex_match(scheme_host_port, m, re)) {
+ auto scheme = m[1].str();
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ if (!scheme.empty() && (scheme != "http" && scheme != "https")) {
+#else
+ if (!scheme.empty() && scheme != "http") {
+#endif
+ std::string msg = "'" + scheme + "' scheme is not supported.";
+ throw std::invalid_argument(msg);
+ return;
+ }
+
+ auto is_ssl = scheme == "https";
+
+ auto host = m[2].str();
+ if (host.empty()) { host = m[3].str(); }
+
+ auto port_str = m[4].str();
+ auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80);
+
+ if (is_ssl) {
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+ cli_ = detail::make_unique<SSLClient>(host.c_str(), port,
+ client_cert_path, client_key_path);
+ is_ssl_ = is_ssl;
+#endif
+ } else {
+ cli_ = detail::make_unique<ClientImpl>(host.c_str(), port,
+ client_cert_path, client_key_path);
+ }
+ } else {
+ cli_ = detail::make_unique<ClientImpl>(scheme_host_port, 80,
+ client_cert_path, client_key_path);
+ }
+}
+
+inline Client::Client(const std::string &host, int port)
+ : cli_(detail::make_unique<ClientImpl>(host, port)) {}
+
+inline Client::Client(const std::string &host, int port,
+ const std::string &client_cert_path,
+ const std::string &client_key_path)
+ : cli_(detail::make_unique<ClientImpl>(host, port, client_cert_path,
+ client_key_path)) {}
+
+inline Client::~Client() {}
+
+inline bool Client::is_valid() const {
+ return cli_ != nullptr && cli_->is_valid();
+}
+
+inline Result Client::Get(const char *path) { return cli_->Get(path); }
+inline Result Client::Get(const char *path, const Headers &headers) {
+ return cli_->Get(path, headers);
+}
+inline Result Client::Get(const char *path, Progress progress) {
+ return cli_->Get(path, std::move(progress));
+}
+inline Result Client::Get(const char *path, const Headers &headers,
+ Progress progress) {
+ return cli_->Get(path, headers, std::move(progress));
+}
+inline Result Client::Get(const char *path, ContentReceiver content_receiver) {
+ return cli_->Get(path, std::move(content_receiver));
+}
+inline Result Client::Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver) {
+ return cli_->Get(path, headers, std::move(content_receiver));
+}
+inline Result Client::Get(const char *path, ContentReceiver content_receiver,
+ Progress progress) {
+ return cli_->Get(path, std::move(content_receiver), std::move(progress));
+}
+inline Result Client::Get(const char *path, const Headers &headers,
+ ContentReceiver content_receiver, Progress progress) {
+ return cli_->Get(path, headers, std::move(content_receiver),
+ std::move(progress));
+}
+inline Result Client::Get(const char *path, ResponseHandler response_handler,
+ ContentReceiver content_receiver) {
+ return cli_->Get(path, std::move(response_handler),
+ std::move(content_receiver));
+}
+inline Result Client::Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver) {
+ return cli_->Get(path, headers, std::move(response_handler),
+ std::move(content_receiver));
+}
+inline Result Client::Get(const char *path, ResponseHandler response_handler,
+ ContentReceiver content_receiver, Progress progress) {
+ return cli_->Get(path, std::move(response_handler),
+ std::move(content_receiver), std::move(progress));
+}
+inline Result Client::Get(const char *path, const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver, Progress progress) {
+ return cli_->Get(path, headers, std::move(response_handler),
+ std::move(content_receiver), std::move(progress));
+}
+inline Result Client::Get(const char *path, const Params &params,
+ const Headers &headers, Progress progress) {
+ return cli_->Get(path, params, headers, progress);
+}
+inline Result Client::Get(const char *path, const Params &params,
+ const Headers &headers,
+ ContentReceiver content_receiver, Progress progress) {
+ return cli_->Get(path, params, headers, content_receiver, progress);
+}
+inline Result Client::Get(const char *path, const Params &params,
+ const Headers &headers,
+ ResponseHandler response_handler,
+ ContentReceiver content_receiver, Progress progress) {
+ return cli_->Get(path, params, headers, response_handler, content_receiver,
+ progress);
+}
+
+inline Result Client::Head(const char *path) { return cli_->Head(path); }
+inline Result Client::Head(const char *path, const Headers &headers) {
+ return cli_->Head(path, headers);
+}
+
+inline Result Client::Post(const char *path) { return cli_->Post(path); }
+inline Result Client::Post(const char *path, const char *body,
+ size_t content_length, const char *content_type) {
+ return cli_->Post(path, body, content_length, content_type);
+}
+inline Result Client::Post(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ return cli_->Post(path, headers, body, content_length, content_type);
+}
+inline Result Client::Post(const char *path, const std::string &body,
+ const char *content_type) {
+ return cli_->Post(path, body, content_type);
+}
+inline Result Client::Post(const char *path, const Headers &headers,
+ const std::string &body, const char *content_type) {
+ return cli_->Post(path, headers, body, content_type);
+}
+inline Result Client::Post(const char *path, size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return cli_->Post(path, content_length, std::move(content_provider),
+ content_type);
+}
+inline Result Client::Post(const char *path,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return cli_->Post(path, std::move(content_provider), content_type);
+}
+inline Result Client::Post(const char *path, const Headers &headers,
+ size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return cli_->Post(path, headers, content_length, std::move(content_provider),
+ content_type);
+}
+inline Result Client::Post(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return cli_->Post(path, headers, std::move(content_provider), content_type);
+}
+inline Result Client::Post(const char *path, const Params &params) {
+ return cli_->Post(path, params);
+}
+inline Result Client::Post(const char *path, const Headers &headers,
+ const Params &params) {
+ return cli_->Post(path, headers, params);
+}
+inline Result Client::Post(const char *path,
+ const MultipartFormDataItems &items) {
+ return cli_->Post(path, items);
+}
+inline Result Client::Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items) {
+ return cli_->Post(path, headers, items);
+}
+inline Result Client::Post(const char *path, const Headers &headers,
+ const MultipartFormDataItems &items,
+ const std::string &boundary) {
+ return cli_->Post(path, headers, items, boundary);
+}
+inline Result Client::Put(const char *path) { return cli_->Put(path); }
+inline Result Client::Put(const char *path, const char *body,
+ size_t content_length, const char *content_type) {
+ return cli_->Put(path, body, content_length, content_type);
+}
+inline Result Client::Put(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ return cli_->Put(path, headers, body, content_length, content_type);
+}
+inline Result Client::Put(const char *path, const std::string &body,
+ const char *content_type) {
+ return cli_->Put(path, body, content_type);
+}
+inline Result Client::Put(const char *path, const Headers &headers,
+ const std::string &body, const char *content_type) {
+ return cli_->Put(path, headers, body, content_type);
+}
+inline Result Client::Put(const char *path, size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return cli_->Put(path, content_length, std::move(content_provider),
+ content_type);
+}
+inline Result Client::Put(const char *path,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return cli_->Put(path, std::move(content_provider), content_type);
+}
+inline Result Client::Put(const char *path, const Headers &headers,
+ size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return cli_->Put(path, headers, content_length, std::move(content_provider),
+ content_type);
+}
+inline Result Client::Put(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return cli_->Put(path, headers, std::move(content_provider), content_type);
+}
+inline Result Client::Put(const char *path, const Params &params) {
+ return cli_->Put(path, params);
+}
+inline Result Client::Put(const char *path, const Headers &headers,
+ const Params &params) {
+ return cli_->Put(path, headers, params);
+}
+inline Result Client::Patch(const char *path) { return cli_->Patch(path); }
+inline Result Client::Patch(const char *path, const char *body,
+ size_t content_length, const char *content_type) {
+ return cli_->Patch(path, body, content_length, content_type);
+}
+inline Result Client::Patch(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ return cli_->Patch(path, headers, body, content_length, content_type);
+}
+inline Result Client::Patch(const char *path, const std::string &body,
+ const char *content_type) {
+ return cli_->Patch(path, body, content_type);
+}
+inline Result Client::Patch(const char *path, const Headers &headers,
+ const std::string &body, const char *content_type) {
+ return cli_->Patch(path, headers, body, content_type);
+}
+inline Result Client::Patch(const char *path, size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return cli_->Patch(path, content_length, std::move(content_provider),
+ content_type);
+}
+inline Result Client::Patch(const char *path,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return cli_->Patch(path, std::move(content_provider), content_type);
+}
+inline Result Client::Patch(const char *path, const Headers &headers,
+ size_t content_length,
+ ContentProvider content_provider,
+ const char *content_type) {
+ return cli_->Patch(path, headers, content_length, std::move(content_provider),
+ content_type);
+}
+inline Result Client::Patch(const char *path, const Headers &headers,
+ ContentProviderWithoutLength content_provider,
+ const char *content_type) {
+ return cli_->Patch(path, headers, std::move(content_provider), content_type);
+}
+inline Result Client::Delete(const char *path) { return cli_->Delete(path); }
+inline Result Client::Delete(const char *path, const Headers &headers) {
+ return cli_->Delete(path, headers);
+}
+inline Result Client::Delete(const char *path, const char *body,
+ size_t content_length, const char *content_type) {
+ return cli_->Delete(path, body, content_length, content_type);
+}
+inline Result Client::Delete(const char *path, const Headers &headers,
+ const char *body, size_t content_length,
+ const char *content_type) {
+ return cli_->Delete(path, headers, body, content_length, content_type);
+}
+inline Result Client::Delete(const char *path, const std::string &body,
+ const char *content_type) {
+ return cli_->Delete(path, body, content_type);
+}
+inline Result Client::Delete(const char *path, const Headers &headers,
+ const std::string &body,
+ const char *content_type) {
+ return cli_->Delete(path, headers, body, content_type);
+}
+inline Result Client::Options(const char *path) { return cli_->Options(path); }
+inline Result Client::Options(const char *path, const Headers &headers) {
+ return cli_->Options(path, headers);
+}
+
+inline bool Client::send(Request &req, Response &res, Error &error) {
+ return cli_->send(req, res, error);
+}
+
+inline Result Client::send(const Request &req) { return cli_->send(req); }
+
+inline size_t Client::is_socket_open() const { return cli_->is_socket_open(); }
+
+inline void Client::stop() { cli_->stop(); }
+
+inline void Client::set_default_headers(Headers headers) {
+ cli_->set_default_headers(std::move(headers));
+}
+
+inline void Client::set_address_family(int family) {
+ cli_->set_address_family(family);
+}
+
+inline void Client::set_tcp_nodelay(bool on) { cli_->set_tcp_nodelay(on); }
+
+inline void Client::set_socket_options(SocketOptions socket_options) {
+ cli_->set_socket_options(std::move(socket_options));
+}
+
+inline void Client::set_connection_timeout(time_t sec, time_t usec) {
+ cli_->set_connection_timeout(sec, usec);
+}
+
+inline void Client::set_read_timeout(time_t sec, time_t usec) {
+ cli_->set_read_timeout(sec, usec);
+}
+
+inline void Client::set_write_timeout(time_t sec, time_t usec) {
+ cli_->set_write_timeout(sec, usec);
+}
+
+inline void Client::set_basic_auth(const char *username, const char *password) {
+ cli_->set_basic_auth(username, password);
+}
+inline void Client::set_bearer_token_auth(const char *token) {
+ cli_->set_bearer_token_auth(token);
+}
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void Client::set_digest_auth(const char *username,
+ const char *password) {
+ cli_->set_digest_auth(username, password);
+}
+#endif
+
+inline void Client::set_keep_alive(bool on) { cli_->set_keep_alive(on); }
+inline void Client::set_follow_location(bool on) {
+ cli_->set_follow_location(on);
+}
+
+inline void Client::set_url_encode(bool on) { cli_->set_url_encode(on); }
+
+inline void Client::set_compress(bool on) { cli_->set_compress(on); }
+
+inline void Client::set_decompress(bool on) { cli_->set_decompress(on); }
+
+inline void Client::set_interface(const char *intf) {
+ cli_->set_interface(intf);
+}
+
+inline void Client::set_proxy(const char *host, int port) {
+ cli_->set_proxy(host, port);
+}
+inline void Client::set_proxy_basic_auth(const char *username,
+ const char *password) {
+ cli_->set_proxy_basic_auth(username, password);
+}
+inline void Client::set_proxy_bearer_token_auth(const char *token) {
+ cli_->set_proxy_bearer_token_auth(token);
+}
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void Client::set_proxy_digest_auth(const char *username,
+ const char *password) {
+ cli_->set_proxy_digest_auth(username, password);
+}
+#endif
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void Client::enable_server_certificate_verification(bool enabled) {
+ cli_->enable_server_certificate_verification(enabled);
+}
+#endif
+
+inline void Client::set_logger(Logger logger) { cli_->set_logger(logger); }
+
+#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
+inline void Client::set_ca_cert_path(const char *ca_cert_file_path,
+ const char *ca_cert_dir_path) {
+ cli_->set_ca_cert_path(ca_cert_file_path, ca_cert_dir_path);
+}
+
+inline void Client::set_ca_cert_store(X509_STORE *ca_cert_store) {
+ if (is_ssl_) {
+ static_cast<SSLClient &>(*cli_).set_ca_cert_store(ca_cert_store);
+ } else {
+ cli_->set_ca_cert_store(ca_cert_store);
+ }
+}
+
+inline long Client::get_openssl_verify_result() const {
+ if (is_ssl_) {
+ return static_cast<SSLClient &>(*cli_).get_openssl_verify_result();
+ }
+ return -1; // NOTE: -1 doesn't match any of X509_V_ERR_???
+}
+
+inline SSL_CTX *Client::ssl_context() const {
+ if (is_ssl_) { return static_cast<SSLClient &>(*cli_).ssl_context(); }
+ return nullptr;
+}
+#endif
+
+// ----------------------------------------------------------------------------
+
+} // namespace httplib
+
+#endif // CPPHTTPLIB_HTTPLIB_H
diff --git a/include/internal/__DECC_INCLUDE_EPILOGUE.H b/include/internal/__DECC_INCLUDE_EPILOGUE.H
new file mode 100644
index 00000000..e57c0eab
--- /dev/null
+++ b/include/internal/__DECC_INCLUDE_EPILOGUE.H
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This file is only used by HP C on VMS, and is included automatically
+ * after each header file from this directory
+ */
+
+/* restore state. Must correspond to the save in __decc_include_prologue.h */
+#pragma names restore
diff --git a/include/internal/__DECC_INCLUDE_PROLOGUE.H b/include/internal/__DECC_INCLUDE_PROLOGUE.H
new file mode 100644
index 00000000..a0139575
--- /dev/null
+++ b/include/internal/__DECC_INCLUDE_PROLOGUE.H
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This file is only used by HP C on VMS, and is included automatically
+ * after each header file from this directory
+ */
+
+/* save state */
+#pragma names save
+/* have the compiler shorten symbols larger than 31 chars to 23 chars
+ * followed by a 8 hex char CRC
+ */
+#pragma names as_is,shortened
diff --git a/include/internal/asn1.h b/include/internal/asn1.h
new file mode 100644
index 00000000..3143e340
--- /dev/null
+++ b/include/internal/asn1.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_ASN1_H
+# define OSSL_INTERNAL_ASN1_H
+# pragma once
+
+int asn1_d2i_read_bio(BIO *in, BUF_MEM **pb);
+
+#endif
diff --git a/include/internal/bio.h b/include/internal/bio.h
new file mode 100644
index 00000000..2d36a7b9
--- /dev/null
+++ b/include/internal/bio.h
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_BIO_H
+# define OSSL_INTERNAL_BIO_H
+# pragma once
+
+# include <openssl/core.h>
+# include <openssl/bio.h>
+
+struct bio_method_st {
+ int type;
+ char *name;
+ int (*bwrite) (BIO *, const char *, size_t, size_t *);
+ int (*bwrite_old) (BIO *, const char *, int);
+ int (*bread) (BIO *, char *, size_t, size_t *);
+ int (*bread_old) (BIO *, char *, int);
+ int (*bputs) (BIO *, const char *);
+ int (*bgets) (BIO *, char *, int);
+ long (*ctrl) (BIO *, int, long, void *);
+ int (*create) (BIO *);
+ int (*destroy) (BIO *);
+ long (*callback_ctrl) (BIO *, int, BIO_info_cb *);
+};
+
+void bio_free_ex_data(BIO *bio);
+void bio_cleanup(void);
+
+
+/* Old style to new style BIO_METHOD conversion functions */
+int bwrite_conv(BIO *bio, const char *data, size_t datal, size_t *written);
+int bread_conv(BIO *bio, char *data, size_t datal, size_t *read);
+
+/* Changes to these internal BIOs must also update include/openssl/bio.h */
+# define BIO_CTRL_SET_KTLS 72
+# define BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG 74
+# define BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG 75
+
+/*
+ * This is used with socket BIOs:
+ * BIO_FLAGS_KTLS_TX means we are using ktls with this BIO for sending.
+ * BIO_FLAGS_KTLS_TX_CTRL_MSG means we are about to send a ctrl message next.
+ * BIO_FLAGS_KTLS_RX means we are using ktls with this BIO for receiving.
+ */
+# define BIO_FLAGS_KTLS_TX 0x800
+# define BIO_FLAGS_KTLS_TX_CTRL_MSG 0x1000
+# define BIO_FLAGS_KTLS_RX 0x2000
+
+/* KTLS related controls and flags */
+# define BIO_set_ktls_flag(b, is_tx) \
+ BIO_set_flags(b, (is_tx) ? BIO_FLAGS_KTLS_TX : BIO_FLAGS_KTLS_RX)
+# define BIO_should_ktls_flag(b, is_tx) \
+ BIO_test_flags(b, (is_tx) ? BIO_FLAGS_KTLS_TX : BIO_FLAGS_KTLS_RX)
+# define BIO_set_ktls_ctrl_msg_flag(b) \
+ BIO_set_flags(b, BIO_FLAGS_KTLS_TX_CTRL_MSG)
+# define BIO_should_ktls_ctrl_msg_flag(b) \
+ BIO_test_flags(b, BIO_FLAGS_KTLS_TX_CTRL_MSG)
+# define BIO_clear_ktls_ctrl_msg_flag(b) \
+ BIO_clear_flags(b, BIO_FLAGS_KTLS_TX_CTRL_MSG)
+
+# define BIO_set_ktls(b, keyblob, is_tx) \
+ BIO_ctrl(b, BIO_CTRL_SET_KTLS, is_tx, keyblob)
+# define BIO_set_ktls_ctrl_msg(b, record_type) \
+ BIO_ctrl(b, BIO_CTRL_SET_KTLS_TX_SEND_CTRL_MSG, record_type, NULL)
+# define BIO_clear_ktls_ctrl_msg(b) \
+ BIO_ctrl(b, BIO_CTRL_CLEAR_KTLS_TX_CTRL_MSG, 0, NULL)
+
+/* Functions to allow the core to offer the CORE_BIO type to providers */
+OSSL_CORE_BIO *ossl_core_bio_new_from_bio(BIO *bio);
+OSSL_CORE_BIO *ossl_core_bio_new_file(const char *filename, const char *mode);
+OSSL_CORE_BIO *ossl_core_bio_new_mem_buf(const void *buf, int len);
+int ossl_core_bio_read_ex(OSSL_CORE_BIO *cb, void *data, size_t dlen,
+ size_t *readbytes);
+int ossl_core_bio_write_ex(OSSL_CORE_BIO *cb, const void *data, size_t dlen,
+ size_t *written);
+int ossl_core_bio_gets(OSSL_CORE_BIO *cb, char *buf, int size);
+int ossl_core_bio_puts(OSSL_CORE_BIO *cb, const char *buf);
+long ossl_core_bio_ctrl(OSSL_CORE_BIO *cb, int cmd, long larg, void *parg);
+int ossl_core_bio_up_ref(OSSL_CORE_BIO *cb);
+int ossl_core_bio_free(OSSL_CORE_BIO *cb);
+int ossl_core_bio_vprintf(OSSL_CORE_BIO *cb, const char *format, va_list args);
+
+int ossl_bio_init_core(OSSL_LIB_CTX *libctx, const OSSL_DISPATCH *fns);
+
+#endif
diff --git a/include/internal/comp.h b/include/internal/comp.h
new file mode 100644
index 00000000..3ad86fc7
--- /dev/null
+++ b/include/internal/comp.h
@@ -0,0 +1,12 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <openssl/comp.h>
+
+void ossl_comp_zlib_cleanup(void);
diff --git a/include/internal/conf.h b/include/internal/conf.h
new file mode 100644
index 00000000..8c6c29cd
--- /dev/null
+++ b/include/internal/conf.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_CONF_H
+# define OSSL_INTERNAL_CONF_H
+# pragma once
+
+# include <openssl/conf.h>
+
+# define DEFAULT_CONF_MFLAGS \
+ (CONF_MFLAGS_DEFAULT_SECTION | \
+ CONF_MFLAGS_IGNORE_MISSING_FILE | \
+ CONF_MFLAGS_IGNORE_RETURN_CODES)
+
+struct ossl_init_settings_st {
+ char *filename;
+ char *appname;
+ unsigned long flags;
+};
+
+int ossl_config_int(const OPENSSL_INIT_SETTINGS *);
+void ossl_no_config_int(void);
+void ossl_config_modules_free(void);
+
+#endif
diff --git a/include/internal/constant_time.h b/include/internal/constant_time.h
new file mode 100644
index 00000000..0ed6f823
--- /dev/null
+++ b/include/internal/constant_time.h
@@ -0,0 +1,421 @@
+/*
+ * Copyright 2014-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_CONSTANT_TIME_H
+# define OSSL_INTERNAL_CONSTANT_TIME_H
+# pragma once
+
+# include <stdlib.h>
+# include <string.h>
+# include <openssl/e_os2.h> /* For 'ossl_inline' */
+
+/*-
+ * The boolean methods return a bitmask of all ones (0xff...f) for true
+ * and 0 for false. This is useful for choosing a value based on the result
+ * of a conditional in constant time. For example,
+ * if (a < b) {
+ * c = a;
+ * } else {
+ * c = b;
+ * }
+ * can be written as
+ * unsigned int lt = constant_time_lt(a, b);
+ * c = constant_time_select(lt, a, b);
+ */
+
+/* Returns the given value with the MSB copied to all the other bits. */
+static ossl_inline unsigned int constant_time_msb(unsigned int a);
+/* Convenience method for uint32_t. */
+static ossl_inline uint32_t constant_time_msb_32(uint32_t a);
+/* Convenience method for uint64_t. */
+static ossl_inline uint64_t constant_time_msb_64(uint64_t a);
+
+/* Returns 0xff..f if a < b and 0 otherwise. */
+static ossl_inline unsigned int constant_time_lt(unsigned int a,
+ unsigned int b);
+/* Convenience method for getting an 8-bit mask. */
+static ossl_inline unsigned char constant_time_lt_8(unsigned int a,
+ unsigned int b);
+/* Convenience method for uint64_t. */
+static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b);
+
+/* Returns 0xff..f if a >= b and 0 otherwise. */
+static ossl_inline unsigned int constant_time_ge(unsigned int a,
+ unsigned int b);
+/* Convenience method for getting an 8-bit mask. */
+static ossl_inline unsigned char constant_time_ge_8(unsigned int a,
+ unsigned int b);
+
+/* Returns 0xff..f if a == 0 and 0 otherwise. */
+static ossl_inline unsigned int constant_time_is_zero(unsigned int a);
+/* Convenience method for getting an 8-bit mask. */
+static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a);
+/* Convenience method for getting a 32-bit mask. */
+static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a);
+
+/* Returns 0xff..f if a == b and 0 otherwise. */
+static ossl_inline unsigned int constant_time_eq(unsigned int a,
+ unsigned int b);
+/* Convenience method for getting an 8-bit mask. */
+static ossl_inline unsigned char constant_time_eq_8(unsigned int a,
+ unsigned int b);
+/* Signed integers. */
+static ossl_inline unsigned int constant_time_eq_int(int a, int b);
+/* Convenience method for getting an 8-bit mask. */
+static ossl_inline unsigned char constant_time_eq_int_8(int a, int b);
+
+/*-
+ * Returns (mask & a) | (~mask & b).
+ *
+ * When |mask| is all 1s or all 0s (as returned by the methods above),
+ * the select methods return either |a| (if |mask| is nonzero) or |b|
+ * (if |mask| is zero).
+ */
+static ossl_inline unsigned int constant_time_select(unsigned int mask,
+ unsigned int a,
+ unsigned int b);
+/* Convenience method for unsigned chars. */
+static ossl_inline unsigned char constant_time_select_8(unsigned char mask,
+ unsigned char a,
+ unsigned char b);
+
+/* Convenience method for uint32_t. */
+static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a,
+ uint32_t b);
+
+/* Convenience method for uint64_t. */
+static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a,
+ uint64_t b);
+/* Convenience method for signed integers. */
+static ossl_inline int constant_time_select_int(unsigned int mask, int a,
+ int b);
+
+
+static ossl_inline unsigned int constant_time_msb(unsigned int a)
+{
+ return 0 - (a >> (sizeof(a) * 8 - 1));
+}
+
+
+static ossl_inline uint32_t constant_time_msb_32(uint32_t a)
+{
+ return 0 - (a >> 31);
+}
+
+static ossl_inline uint64_t constant_time_msb_64(uint64_t a)
+{
+ return 0 - (a >> 63);
+}
+
+static ossl_inline size_t constant_time_msb_s(size_t a)
+{
+ return 0 - (a >> (sizeof(a) * 8 - 1));
+}
+
+static ossl_inline unsigned int constant_time_lt(unsigned int a,
+ unsigned int b)
+{
+ return constant_time_msb(a ^ ((a ^ b) | ((a - b) ^ b)));
+}
+
+static ossl_inline size_t constant_time_lt_s(size_t a, size_t b)
+{
+ return constant_time_msb_s(a ^ ((a ^ b) | ((a - b) ^ b)));
+}
+
+static ossl_inline unsigned char constant_time_lt_8(unsigned int a,
+ unsigned int b)
+{
+ return (unsigned char)constant_time_lt(a, b);
+}
+
+static ossl_inline uint64_t constant_time_lt_64(uint64_t a, uint64_t b)
+{
+ return constant_time_msb_64(a ^ ((a ^ b) | ((a - b) ^ b)));
+}
+
+static ossl_inline unsigned int constant_time_ge(unsigned int a,
+ unsigned int b)
+{
+ return ~constant_time_lt(a, b);
+}
+
+static ossl_inline size_t constant_time_ge_s(size_t a, size_t b)
+{
+ return ~constant_time_lt_s(a, b);
+}
+
+static ossl_inline unsigned char constant_time_ge_8(unsigned int a,
+ unsigned int b)
+{
+ return (unsigned char)constant_time_ge(a, b);
+}
+
+static ossl_inline unsigned char constant_time_ge_8_s(size_t a, size_t b)
+{
+ return (unsigned char)constant_time_ge_s(a, b);
+}
+
+static ossl_inline unsigned int constant_time_is_zero(unsigned int a)
+{
+ return constant_time_msb(~a & (a - 1));
+}
+
+static ossl_inline size_t constant_time_is_zero_s(size_t a)
+{
+ return constant_time_msb_s(~a & (a - 1));
+}
+
+static ossl_inline unsigned char constant_time_is_zero_8(unsigned int a)
+{
+ return (unsigned char)constant_time_is_zero(a);
+}
+
+static ossl_inline uint32_t constant_time_is_zero_32(uint32_t a)
+{
+ return constant_time_msb_32(~a & (a - 1));
+}
+
+static ossl_inline uint64_t constant_time_is_zero_64(uint64_t a)
+{
+ return constant_time_msb_64(~a & (a - 1));
+}
+
+static ossl_inline unsigned int constant_time_eq(unsigned int a,
+ unsigned int b)
+{
+ return constant_time_is_zero(a ^ b);
+}
+
+static ossl_inline size_t constant_time_eq_s(size_t a, size_t b)
+{
+ return constant_time_is_zero_s(a ^ b);
+}
+
+static ossl_inline unsigned char constant_time_eq_8(unsigned int a,
+ unsigned int b)
+{
+ return (unsigned char)constant_time_eq(a, b);
+}
+
+static ossl_inline unsigned char constant_time_eq_8_s(size_t a, size_t b)
+{
+ return (unsigned char)constant_time_eq_s(a, b);
+}
+
+static ossl_inline unsigned int constant_time_eq_int(int a, int b)
+{
+ return constant_time_eq((unsigned)(a), (unsigned)(b));
+}
+
+static ossl_inline unsigned char constant_time_eq_int_8(int a, int b)
+{
+ return constant_time_eq_8((unsigned)(a), (unsigned)(b));
+}
+
+/*
+ * Returns the value unmodified, but avoids optimizations.
+ * The barriers prevent the compiler from narrowing down the
+ * possible value range of the mask and ~mask in the select
+ * statements, which avoids the recognition of the select
+ * and turning it into a conditional load or branch.
+ */
+static ossl_inline unsigned int value_barrier(unsigned int a)
+{
+#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
+ unsigned int r;
+ __asm__("" : "=r"(r) : "0"(a));
+#else
+ volatile unsigned int r = a;
+#endif
+ return r;
+}
+
+/* Convenience method for uint32_t. */
+static ossl_inline uint32_t value_barrier_32(uint32_t a)
+{
+#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
+ uint32_t r;
+ __asm__("" : "=r"(r) : "0"(a));
+#else
+ volatile uint32_t r = a;
+#endif
+ return r;
+}
+
+/* Convenience method for uint64_t. */
+static ossl_inline uint64_t value_barrier_64(uint64_t a)
+{
+#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
+ uint64_t r;
+ __asm__("" : "=r"(r) : "0"(a));
+#else
+ volatile uint64_t r = a;
+#endif
+ return r;
+}
+
+/* Convenience method for size_t. */
+static ossl_inline size_t value_barrier_s(size_t a)
+{
+#if !defined(OPENSSL_NO_ASM) && defined(__GNUC__)
+ size_t r;
+ __asm__("" : "=r"(r) : "0"(a));
+#else
+ volatile size_t r = a;
+#endif
+ return r;
+}
+
+static ossl_inline unsigned int constant_time_select(unsigned int mask,
+ unsigned int a,
+ unsigned int b)
+{
+ return (value_barrier(mask) & a) | (value_barrier(~mask) & b);
+}
+
+static ossl_inline size_t constant_time_select_s(size_t mask,
+ size_t a,
+ size_t b)
+{
+ return (value_barrier_s(mask) & a) | (value_barrier_s(~mask) & b);
+}
+
+static ossl_inline unsigned char constant_time_select_8(unsigned char mask,
+ unsigned char a,
+ unsigned char b)
+{
+ return (unsigned char)constant_time_select(mask, a, b);
+}
+
+static ossl_inline int constant_time_select_int(unsigned int mask, int a,
+ int b)
+{
+ return (int)constant_time_select(mask, (unsigned)(a), (unsigned)(b));
+}
+
+static ossl_inline int constant_time_select_int_s(size_t mask, int a, int b)
+{
+ return (int)constant_time_select((unsigned)mask, (unsigned)(a),
+ (unsigned)(b));
+}
+
+static ossl_inline uint32_t constant_time_select_32(uint32_t mask, uint32_t a,
+ uint32_t b)
+{
+ return (value_barrier_32(mask) & a) | (value_barrier_32(~mask) & b);
+}
+
+static ossl_inline uint64_t constant_time_select_64(uint64_t mask, uint64_t a,
+ uint64_t b)
+{
+ return (value_barrier_64(mask) & a) | (value_barrier_64(~mask) & b);
+}
+
+/*
+ * mask must be 0xFFFFFFFF or 0x00000000.
+ *
+ * if (mask) {
+ * uint32_t tmp = *a;
+ *
+ * *a = *b;
+ * *b = tmp;
+ * }
+ */
+static ossl_inline void constant_time_cond_swap_32(uint32_t mask, uint32_t *a,
+ uint32_t *b)
+{
+ uint32_t xor = *a ^ *b;
+
+ xor &= mask;
+ *a ^= xor;
+ *b ^= xor;
+}
+
+/*
+ * mask must be 0xFFFFFFFF or 0x00000000.
+ *
+ * if (mask) {
+ * uint64_t tmp = *a;
+ *
+ * *a = *b;
+ * *b = tmp;
+ * }
+ */
+static ossl_inline void constant_time_cond_swap_64(uint64_t mask, uint64_t *a,
+ uint64_t *b)
+{
+ uint64_t xor = *a ^ *b;
+
+ xor &= mask;
+ *a ^= xor;
+ *b ^= xor;
+}
+
+/*
+ * mask must be 0xFF or 0x00.
+ * "constant time" is per len.
+ *
+ * if (mask) {
+ * unsigned char tmp[len];
+ *
+ * memcpy(tmp, a, len);
+ * memcpy(a, b);
+ * memcpy(b, tmp);
+ * }
+ */
+static ossl_inline void constant_time_cond_swap_buff(unsigned char mask,
+ unsigned char *a,
+ unsigned char *b,
+ size_t len)
+{
+ size_t i;
+ unsigned char tmp;
+
+ for (i = 0; i < len; i++) {
+ tmp = a[i] ^ b[i];
+ tmp &= mask;
+ a[i] ^= tmp;
+ b[i] ^= tmp;
+ }
+}
+
+/*
+ * table is a two dimensional array of bytes. Each row has rowsize elements.
+ * Copies row number idx into out. rowsize and numrows are not considered
+ * private.
+ */
+static ossl_inline void constant_time_lookup(void *out,
+ const void *table,
+ size_t rowsize,
+ size_t numrows,
+ size_t idx)
+{
+ size_t i, j;
+ const unsigned char *tablec = (const unsigned char *)table;
+ unsigned char *outc = (unsigned char *)out;
+ unsigned char mask;
+
+ memset(out, 0, rowsize);
+
+ /* Note idx may underflow - but that is well defined */
+ for (i = 0; i < numrows; i++, idx--) {
+ mask = (unsigned char)constant_time_is_zero_s(idx);
+ for (j = 0; j < rowsize; j++)
+ *(outc + j) |= constant_time_select_8(mask, *(tablec++), 0);
+ }
+}
+
+/*
+ * Expected usage pattern is to unconditionally set error and then
+ * wipe it if there was no actual error. |clear| is 1 or 0.
+ */
+void err_clear_last_constant_time(int clear);
+
+#endif /* OSSL_INTERNAL_CONSTANT_TIME_H */
diff --git a/include/internal/core.h b/include/internal/core.h
new file mode 100644
index 00000000..d9dc4241
--- /dev/null
+++ b/include/internal/core.h
@@ -0,0 +1,66 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_CORE_H
+# define OSSL_INTERNAL_CORE_H
+# pragma once
+
+/*
+ * namespaces:
+ *
+ * ossl_method_ Core Method API
+ */
+
+/*
+ * construct an arbitrary method from a dispatch table found by looking
+ * up a match for the < operation_id, name, property > combination.
+ * constructor and destructor are the constructor and destructor for that
+ * arbitrary object.
+ *
+ * These objects are normally cached, unless the provider says not to cache.
+ * However, force_cache can be used to force caching whatever the provider
+ * says (for example, because the application knows better).
+ */
+typedef struct ossl_method_construct_method_st {
+ /* Get a temporary store */
+ void *(*get_tmp_store)(void *data);
+ /* Get an already existing method from a store */
+ void *(*get)(void *store, const OSSL_PROVIDER **prov, void *data);
+ /* Store a method in a store */
+ int (*put)(void *store, void *method, const OSSL_PROVIDER *prov,
+ const char *name, const char *propdef, void *data);
+ /* Construct a new method */
+ void *(*construct)(const OSSL_ALGORITHM *algodef, OSSL_PROVIDER *prov,
+ void *data);
+ /* Destruct a method */
+ void (*destruct)(void *method, void *data);
+} OSSL_METHOD_CONSTRUCT_METHOD;
+
+void *ossl_method_construct(OSSL_LIB_CTX *ctx, int operation_id,
+ OSSL_PROVIDER **provider_rw, int force_cache,
+ OSSL_METHOD_CONSTRUCT_METHOD *mcm, void *mcm_data);
+
+void ossl_algorithm_do_all(OSSL_LIB_CTX *libctx, int operation_id,
+ OSSL_PROVIDER *provider,
+ int (*pre)(OSSL_PROVIDER *, int operation_id,
+ void *data, int *result),
+ void (*fn)(OSSL_PROVIDER *provider,
+ const OSSL_ALGORITHM *algo,
+ int no_store, void *data),
+ int (*post)(OSSL_PROVIDER *, int operation_id,
+ int no_store, void *data, int *result),
+ void *data);
+char *ossl_algorithm_get1_first_name(const OSSL_ALGORITHM *algo);
+
+__owur int ossl_lib_ctx_write_lock(OSSL_LIB_CTX *ctx);
+__owur int ossl_lib_ctx_read_lock(OSSL_LIB_CTX *ctx);
+int ossl_lib_ctx_unlock(OSSL_LIB_CTX *ctx);
+int ossl_lib_ctx_is_child(OSSL_LIB_CTX *ctx);
+
+#endif
diff --git a/include/internal/cryptlib.h b/include/internal/cryptlib.h
new file mode 100644
index 00000000..1291299b
--- /dev/null
+++ b/include/internal/cryptlib.h
@@ -0,0 +1,261 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_CRYPTLIB_H
+# define OSSL_INTERNAL_CRYPTLIB_H
+# pragma once
+
+# include <stdlib.h>
+# include <string.h>
+
+# ifdef OPENSSL_USE_APPLINK
+# define BIO_FLAGS_UPLINK_INTERNAL 0x8000
+# include "ms/uplink.h"
+# else
+# define BIO_FLAGS_UPLINK_INTERNAL 0
+# endif
+
+# include <openssl/crypto.h>
+# include <openssl/buffer.h>
+# include <openssl/bio.h>
+# include <openssl/asn1.h>
+# include <openssl/err.h>
+# include "internal/nelem.h"
+
+#ifdef NDEBUG
+# define ossl_assert(x) ((x) != 0)
+#else
+__owur static ossl_inline int ossl_assert_int(int expr, const char *exprstr,
+ const char *file, int line)
+{
+ if (!expr)
+ OPENSSL_die(exprstr, file, line);
+
+ return expr;
+}
+
+# define ossl_assert(x) ossl_assert_int((x) != 0, "Assertion failed: "#x, \
+ __FILE__, __LINE__)
+
+#endif
+
+/*
+ * Use this inside a union with the field that needs to be aligned to a
+ * reasonable boundary for the platform. The most pessimistic alignment
+ * of the listed types will be used by the compiler.
+ */
+# define OSSL_UNION_ALIGN \
+ double align; \
+ ossl_uintmax_t align_int; \
+ void *align_ptr
+
+typedef struct ex_callback_st EX_CALLBACK;
+DEFINE_STACK_OF(EX_CALLBACK)
+
+typedef struct mem_st MEM;
+DEFINE_LHASH_OF(MEM);
+
+# define OPENSSL_CONF "openssl.cnf"
+
+# ifndef OPENSSL_SYS_VMS
+# define X509_CERT_AREA OPENSSLDIR
+# define X509_CERT_DIR OPENSSLDIR "/certs"
+# define X509_CERT_FILE OPENSSLDIR "/cert.pem"
+# define X509_PRIVATE_DIR OPENSSLDIR "/private"
+# define CTLOG_FILE OPENSSLDIR "/ct_log_list.cnf"
+# else
+# define X509_CERT_AREA "OSSL$DATAROOT:[000000]"
+# define X509_CERT_DIR "OSSL$DATAROOT:[CERTS]"
+# define X509_CERT_FILE "OSSL$DATAROOT:[000000]cert.pem"
+# define X509_PRIVATE_DIR "OSSL$DATAROOT:[PRIVATE]"
+# define CTLOG_FILE "OSSL$DATAROOT:[000000]ct_log_list.cnf"
+# endif
+
+# define X509_CERT_DIR_EVP "SSL_CERT_DIR"
+# define X509_CERT_FILE_EVP "SSL_CERT_FILE"
+# define CTLOG_FILE_EVP "CTLOG_FILE"
+
+/* size of string representations */
+# define DECIMAL_SIZE(type) ((sizeof(type)*8+2)/3+1)
+# define HEX_SIZE(type) (sizeof(type)*2)
+
+void OPENSSL_cpuid_setup(void);
+#if defined(__i386) || defined(__i386__) || defined(_M_IX86) || \
+ defined(__x86_64) || defined(__x86_64__) || \
+ defined(_M_AMD64) || defined(_M_X64)
+extern unsigned int OPENSSL_ia32cap_P[];
+#endif
+void OPENSSL_showfatal(const char *fmta, ...);
+int ossl_do_ex_data_init(OSSL_LIB_CTX *ctx);
+void ossl_crypto_cleanup_all_ex_data_int(OSSL_LIB_CTX *ctx);
+int openssl_init_fork_handlers(void);
+int openssl_get_fork_id(void);
+
+char *ossl_safe_getenv(const char *name);
+
+extern CRYPTO_RWLOCK *memdbg_lock;
+int openssl_strerror_r(int errnum, char *buf, size_t buflen);
+# if !defined(OPENSSL_NO_STDIO)
+FILE *openssl_fopen(const char *filename, const char *mode);
+# else
+void *openssl_fopen(const char *filename, const char *mode);
+# endif
+
+uint32_t OPENSSL_rdtsc(void);
+size_t OPENSSL_instrument_bus(unsigned int *, size_t);
+size_t OPENSSL_instrument_bus2(unsigned int *, size_t, size_t);
+
+/* ex_data structures */
+
+/*
+ * Each structure type (sometimes called a class), that supports
+ * exdata has a stack of callbacks for each instance.
+ */
+struct ex_callback_st {
+ long argl; /* Arbitrary long */
+ void *argp; /* Arbitrary void * */
+ int priority; /* Priority ordering for freeing */
+ CRYPTO_EX_new *new_func;
+ CRYPTO_EX_free *free_func;
+ CRYPTO_EX_dup *dup_func;
+};
+
+/*
+ * The state for each class. This could just be a typedef, but
+ * a structure allows future changes.
+ */
+typedef struct ex_callbacks_st {
+ STACK_OF(EX_CALLBACK) *meth;
+} EX_CALLBACKS;
+
+typedef struct ossl_ex_data_global_st {
+ CRYPTO_RWLOCK *ex_data_lock;
+ EX_CALLBACKS ex_data[CRYPTO_EX_INDEX__COUNT];
+} OSSL_EX_DATA_GLOBAL;
+
+
+/* OSSL_LIB_CTX */
+
+# define OSSL_LIB_CTX_PROVIDER_STORE_RUN_ONCE_INDEX 0
+# define OSSL_LIB_CTX_DEFAULT_METHOD_STORE_RUN_ONCE_INDEX 1
+# define OSSL_LIB_CTX_METHOD_STORE_RUN_ONCE_INDEX 2
+# define OSSL_LIB_CTX_MAX_RUN_ONCE 3
+
+# define OSSL_LIB_CTX_EVP_METHOD_STORE_INDEX 0
+# define OSSL_LIB_CTX_PROVIDER_STORE_INDEX 1
+# define OSSL_LIB_CTX_PROPERTY_DEFN_INDEX 2
+# define OSSL_LIB_CTX_PROPERTY_STRING_INDEX 3
+# define OSSL_LIB_CTX_NAMEMAP_INDEX 4
+# define OSSL_LIB_CTX_DRBG_INDEX 5
+# define OSSL_LIB_CTX_DRBG_NONCE_INDEX 6
+# define OSSL_LIB_CTX_RAND_CRNGT_INDEX 7
+# ifdef FIPS_MODULE
+# define OSSL_LIB_CTX_THREAD_EVENT_HANDLER_INDEX 8
+# endif
+# define OSSL_LIB_CTX_FIPS_PROV_INDEX 9
+# define OSSL_LIB_CTX_ENCODER_STORE_INDEX 10
+# define OSSL_LIB_CTX_DECODER_STORE_INDEX 11
+# define OSSL_LIB_CTX_SELF_TEST_CB_INDEX 12
+# define OSSL_LIB_CTX_BIO_PROV_INDEX 13
+# define OSSL_LIB_CTX_GLOBAL_PROPERTIES 14
+# define OSSL_LIB_CTX_STORE_LOADER_STORE_INDEX 15
+# define OSSL_LIB_CTX_PROVIDER_CONF_INDEX 16
+# define OSSL_LIB_CTX_BIO_CORE_INDEX 17
+# define OSSL_LIB_CTX_CHILD_PROVIDER_INDEX 18
+# define OSSL_LIB_CTX_MAX_INDEXES 19
+
+# define OSSL_LIB_CTX_METHOD_LOW_PRIORITY -1
+# define OSSL_LIB_CTX_METHOD_DEFAULT_PRIORITY 0
+# define OSSL_LIB_CTX_METHOD_PRIORITY_1 1
+# define OSSL_LIB_CTX_METHOD_PRIORITY_2 2
+
+typedef struct ossl_lib_ctx_method {
+ int priority;
+ void *(*new_func)(OSSL_LIB_CTX *ctx);
+ void (*free_func)(void *);
+} OSSL_LIB_CTX_METHOD;
+
+OSSL_LIB_CTX *ossl_lib_ctx_get_concrete(OSSL_LIB_CTX *ctx);
+int ossl_lib_ctx_is_default(OSSL_LIB_CTX *ctx);
+int ossl_lib_ctx_is_global_default(OSSL_LIB_CTX *ctx);
+
+/* Functions to retrieve pointers to data by index */
+void *ossl_lib_ctx_get_data(OSSL_LIB_CTX *, int /* index */,
+ const OSSL_LIB_CTX_METHOD * ctx);
+
+void ossl_lib_ctx_default_deinit(void);
+OSSL_EX_DATA_GLOBAL *ossl_lib_ctx_get_ex_data_global(OSSL_LIB_CTX *ctx);
+typedef int (ossl_lib_ctx_run_once_fn)(OSSL_LIB_CTX *ctx);
+typedef void (ossl_lib_ctx_onfree_fn)(OSSL_LIB_CTX *ctx);
+
+int ossl_lib_ctx_run_once(OSSL_LIB_CTX *ctx, unsigned int idx,
+ ossl_lib_ctx_run_once_fn run_once_fn);
+int ossl_lib_ctx_onfree(OSSL_LIB_CTX *ctx, ossl_lib_ctx_onfree_fn onfreefn);
+const char *ossl_lib_ctx_get_descriptor(OSSL_LIB_CTX *libctx);
+
+OSSL_LIB_CTX *ossl_crypto_ex_data_get_ossl_lib_ctx(const CRYPTO_EX_DATA *ad);
+int ossl_crypto_new_ex_data_ex(OSSL_LIB_CTX *ctx, int class_index, void *obj,
+ CRYPTO_EX_DATA *ad);
+int ossl_crypto_get_ex_new_index_ex(OSSL_LIB_CTX *ctx, int class_index,
+ long argl, void *argp,
+ CRYPTO_EX_new *new_func,
+ CRYPTO_EX_dup *dup_func,
+ CRYPTO_EX_free *free_func,
+ int priority);
+int ossl_crypto_free_ex_index_ex(OSSL_LIB_CTX *ctx, int class_index, int idx);
+
+/* Function for simple binary search */
+
+/* Flags */
+# define OSSL_BSEARCH_VALUE_ON_NOMATCH 0x01
+# define OSSL_BSEARCH_FIRST_VALUE_ON_MATCH 0x02
+
+const void *ossl_bsearch(const void *key, const void *base, int num,
+ int size, int (*cmp) (const void *, const void *),
+ int flags);
+
+char *ossl_sk_ASN1_UTF8STRING2text(STACK_OF(ASN1_UTF8STRING) *text,
+ const char *sep, size_t max_len);
+char *ossl_ipaddr_to_asc(unsigned char *p, int len);
+
+char *ossl_buf2hexstr_sep(const unsigned char *buf, long buflen, char sep);
+unsigned char *ossl_hexstr2buf_sep(const char *str, long *buflen,
+ const char sep);
+
+static ossl_inline int ossl_ends_with_dirsep(const char *path)
+{
+ if (*path != '\0')
+ path += strlen(path) - 1;
+# if defined __VMS
+ if (*path == ']' || *path == '>' || *path == ':')
+ return 1;
+# elif defined _WIN32
+ if (*path == '\\')
+ return 1;
+# endif
+ return *path == '/';
+}
+
+static ossl_inline int ossl_is_absolute_path(const char *path)
+{
+# if defined __VMS
+ if (strchr(path, ':') != NULL
+ || ((path[0] == '[' || path[0] == '<')
+ && path[1] != '.' && path[1] != '-'
+ && path[1] != ']' && path[1] != '>'))
+ return 1;
+# elif defined _WIN32
+ if (path[0] == '\\'
+ || (path[0] != '\0' && path[1] == ':'))
+ return 1;
+# endif
+ return path[0] == '/';
+}
+
+#endif
diff --git a/include/internal/dane.h b/include/internal/dane.h
new file mode 100644
index 00000000..a3d78a7f
--- /dev/null
+++ b/include/internal/dane.h
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_DANE_H
+#define OSSL_INTERNAL_DANE_H
+# pragma once
+
+# include <openssl/safestack.h>
+
+/*-
+ * Certificate usages:
+ * https://tools.ietf.org/html/rfc6698#section-2.1.1
+ */
+#define DANETLS_USAGE_PKIX_TA 0
+#define DANETLS_USAGE_PKIX_EE 1
+#define DANETLS_USAGE_DANE_TA 2
+#define DANETLS_USAGE_DANE_EE 3
+#define DANETLS_USAGE_LAST DANETLS_USAGE_DANE_EE
+
+/*-
+ * Selectors:
+ * https://tools.ietf.org/html/rfc6698#section-2.1.2
+ */
+#define DANETLS_SELECTOR_CERT 0
+#define DANETLS_SELECTOR_SPKI 1
+#define DANETLS_SELECTOR_LAST DANETLS_SELECTOR_SPKI
+
+/*-
+ * Matching types:
+ * https://tools.ietf.org/html/rfc6698#section-2.1.3
+ */
+#define DANETLS_MATCHING_FULL 0
+#define DANETLS_MATCHING_2256 1
+#define DANETLS_MATCHING_2512 2
+#define DANETLS_MATCHING_LAST DANETLS_MATCHING_2512
+
+typedef struct danetls_record_st {
+ uint8_t usage;
+ uint8_t selector;
+ uint8_t mtype;
+ unsigned char *data;
+ size_t dlen;
+ EVP_PKEY *spki;
+} danetls_record;
+
+DEFINE_STACK_OF(danetls_record)
+
+/*
+ * Shared DANE context
+ */
+struct dane_ctx_st {
+ const EVP_MD **mdevp; /* mtype -> digest */
+ uint8_t *mdord; /* mtype -> preference */
+ uint8_t mdmax; /* highest supported mtype */
+ unsigned long flags; /* feature bitmask */
+};
+
+/*
+ * Per connection DANE state
+ */
+struct ssl_dane_st {
+ struct dane_ctx_st *dctx;
+ STACK_OF(danetls_record) *trecs;
+ STACK_OF(X509) *certs; /* DANE-TA(2) Cert(0) Full(0) certs */
+ danetls_record *mtlsa; /* Matching TLSA record */
+ X509 *mcert; /* DANE matched cert */
+ uint32_t umask; /* Usages present */
+ int mdpth; /* Depth of matched cert */
+ int pdpth; /* Depth of PKIX trust */
+ unsigned long flags; /* feature bitmask */
+};
+
+#define DANETLS_ENABLED(dane) \
+ ((dane) != NULL && sk_danetls_record_num((dane)->trecs) > 0)
+
+#define DANETLS_USAGE_BIT(u) (((uint32_t)1) << u)
+
+#define DANETLS_PKIX_TA_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_PKIX_TA))
+#define DANETLS_PKIX_EE_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_PKIX_EE))
+#define DANETLS_DANE_TA_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_DANE_TA))
+#define DANETLS_DANE_EE_MASK (DANETLS_USAGE_BIT(DANETLS_USAGE_DANE_EE))
+
+#define DANETLS_PKIX_MASK (DANETLS_PKIX_TA_MASK | DANETLS_PKIX_EE_MASK)
+#define DANETLS_DANE_MASK (DANETLS_DANE_TA_MASK | DANETLS_DANE_EE_MASK)
+#define DANETLS_TA_MASK (DANETLS_PKIX_TA_MASK | DANETLS_DANE_TA_MASK)
+#define DANETLS_EE_MASK (DANETLS_PKIX_EE_MASK | DANETLS_DANE_EE_MASK)
+
+#define DANETLS_HAS_PKIX(dane) ((dane) && ((dane)->umask & DANETLS_PKIX_MASK))
+#define DANETLS_HAS_DANE(dane) ((dane) && ((dane)->umask & DANETLS_DANE_MASK))
+#define DANETLS_HAS_TA(dane) ((dane) && ((dane)->umask & DANETLS_TA_MASK))
+#define DANETLS_HAS_EE(dane) ((dane) && ((dane)->umask & DANETLS_EE_MASK))
+
+#define DANETLS_HAS_PKIX_TA(dane) ((dane)&&((dane)->umask & DANETLS_PKIX_TA_MASK))
+#define DANETLS_HAS_PKIX_EE(dane) ((dane)&&((dane)->umask & DANETLS_PKIX_EE_MASK))
+#define DANETLS_HAS_DANE_TA(dane) ((dane)&&((dane)->umask & DANETLS_DANE_TA_MASK))
+#define DANETLS_HAS_DANE_EE(dane) ((dane)&&((dane)->umask & DANETLS_DANE_EE_MASK))
+
+#endif /* OSSL_INTERNAL_DANE_H */
diff --git a/include/internal/deprecated.h b/include/internal/deprecated.h
new file mode 100644
index 00000000..a313a015
--- /dev/null
+++ b/include/internal/deprecated.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This header file should be included by internal code that needs to use APIs
+ * that have been deprecated for public use, but where those symbols will still
+ * be available internally. For example the EVP and provider code needs to use
+ * low level APIs that are otherwise deprecated.
+ *
+ * This header *must* be the first OpenSSL header included by a source file.
+ */
+
+#ifndef OSSL_INTERNAL_DEPRECATED_H
+# define OSSL_INTERNAL_DEPRECATED_H
+# pragma once
+
+# include <openssl/configuration.h>
+
+# undef OPENSSL_NO_DEPRECATED
+# define OPENSSL_SUPPRESS_DEPRECATED
+
+# include <openssl/macros.h>
+
+#endif
diff --git a/include/internal/der.h b/include/internal/der.h
new file mode 100644
index 00000000..a3e56d0d
--- /dev/null
+++ b/include/internal/der.h
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <openssl/bn.h>
+#include "internal/packet.h"
+
+/*
+ * NOTE: X.690 numbers the identifier octet bits 1 to 8.
+ * We use the same numbering in comments here.
+ */
+
+/* Well known primitive tags */
+
+/*
+ * DER UNIVERSAL tags, occupying bits 1-5 in the DER identifier byte
+ * These are only valid for the UNIVERSAL class. With the other classes,
+ * these bits have a different meaning.
+ */
+#define DER_P_EOC 0 /* BER End Of Contents tag */
+#define DER_P_BOOLEAN 1
+#define DER_P_INTEGER 2
+#define DER_P_BIT_STRING 3
+#define DER_P_OCTET_STRING 4
+#define DER_P_NULL 5
+#define DER_P_OBJECT 6
+#define DER_P_OBJECT_DESCRIPTOR 7
+#define DER_P_EXTERNAL 8
+#define DER_P_REAL 9
+#define DER_P_ENUMERATED 10
+#define DER_P_UTF8STRING 12
+#define DER_P_SEQUENCE 16
+#define DER_P_SET 17
+#define DER_P_NUMERICSTRING 18
+#define DER_P_PRINTABLESTRING 19
+#define DER_P_T61STRING 20
+#define DER_P_VIDEOTEXSTRING 21
+#define DER_P_IA5STRING 22
+#define DER_P_UTCTIME 23
+#define DER_P_GENERALIZEDTIME 24
+#define DER_P_GRAPHICSTRING 25
+#define DER_P_ISO64STRING 26
+#define DER_P_GENERALSTRING 27
+#define DER_P_UNIVERSALSTRING 28
+#define DER_P_BMPSTRING 30
+
+/* DER Flags, occupying bit 6 in the DER identifier byte */
+#define DER_F_PRIMITIVE 0x00
+#define DER_F_CONSTRUCTED 0x20
+
+/* DER classes tags, occupying bits 7-8 in the DER identifier byte */
+#define DER_C_UNIVERSAL 0x00
+#define DER_C_APPLICATION 0x40
+#define DER_C_CONTEXT 0x80
+#define DER_C_PRIVATE 0xC0
+
+/*
+ * Run-time constructors.
+ *
+ * They all construct DER backwards, so care should be taken to use them
+ * that way.
+ */
+
+/* This can be used for all items that don't have a context */
+#define DER_NO_CONTEXT -1
+
+int ossl_DER_w_precompiled(WPACKET *pkt, int tag,
+ const unsigned char *precompiled,
+ size_t precompiled_n);
+
+int ossl_DER_w_boolean(WPACKET *pkt, int tag, int b);
+int ossl_DER_w_ulong(WPACKET *pkt, int tag, unsigned long v);
+int ossl_DER_w_bn(WPACKET *pkt, int tag, const BIGNUM *v);
+int ossl_DER_w_null(WPACKET *pkt, int tag);
+int ossl_DER_w_octet_string(WPACKET *pkt, int tag,
+ const unsigned char *data, size_t data_n);
+int ossl_DER_w_octet_string_uint32(WPACKET *pkt, int tag, uint32_t value);
+
+/*
+ * All constructors for constructed elements have a begin and a end function
+ */
+int ossl_DER_w_begin_sequence(WPACKET *pkt, int tag);
+int ossl_DER_w_end_sequence(WPACKET *pkt, int tag);
diff --git a/include/internal/dso.h b/include/internal/dso.h
new file mode 100644
index 00000000..160ddb98
--- /dev/null
+++ b/include/internal/dso.h
@@ -0,0 +1,164 @@
+/*
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_DSO_H
+# define OSSL_INTERNAL_DSO_H
+# pragma once
+
+# include <openssl/crypto.h>
+# include "internal/dsoerr.h"
+
+/* These values are used as commands to DSO_ctrl() */
+# define DSO_CTRL_GET_FLAGS 1
+# define DSO_CTRL_SET_FLAGS 2
+# define DSO_CTRL_OR_FLAGS 3
+
+/*
+ * By default, DSO_load() will translate the provided filename into a form
+ * typical for the platform using the dso_name_converter function of the
+ * method. Eg. win32 will transform "blah" into "blah.dll", and dlfcn will
+ * transform it into "libblah.so". This callback could even utilise the
+ * DSO_METHOD's converter too if it only wants to override behaviour for
+ * one or two possible DSO methods. However, the following flag can be
+ * set in a DSO to prevent *any* native name-translation at all - eg. if
+ * the caller has prompted the user for a path to a driver library so the
+ * filename should be interpreted as-is.
+ */
+# define DSO_FLAG_NO_NAME_TRANSLATION 0x01
+/*
+ * An extra flag to give if only the extension should be added as
+ * translation. This is obviously only of importance on Unix and other
+ * operating systems where the translation also may prefix the name with
+ * something, like 'lib', and ignored everywhere else. This flag is also
+ * ignored if DSO_FLAG_NO_NAME_TRANSLATION is used at the same time.
+ */
+# define DSO_FLAG_NAME_TRANSLATION_EXT_ONLY 0x02
+
+/*
+ * Don't unload the DSO when we call DSO_free()
+ */
+# define DSO_FLAG_NO_UNLOAD_ON_FREE 0x04
+
+/*
+ * This flag loads the library with public symbols. Meaning: The exported
+ * symbols of this library are public to all libraries loaded after this
+ * library. At the moment only implemented in unix.
+ */
+# define DSO_FLAG_GLOBAL_SYMBOLS 0x20
+
+typedef void (*DSO_FUNC_TYPE) (void);
+
+typedef struct dso_st DSO;
+typedef struct dso_meth_st DSO_METHOD;
+
+/*
+ * The function prototype used for method functions (or caller-provided
+ * callbacks) that transform filenames. They are passed a DSO structure
+ * pointer (or NULL if they are to be used independently of a DSO object) and
+ * a filename to transform. They should either return NULL (if there is an
+ * error condition) or a newly allocated string containing the transformed
+ * form that the caller will need to free with OPENSSL_free() when done.
+ */
+typedef char *(*DSO_NAME_CONVERTER_FUNC)(DSO *, const char *);
+/*
+ * The function prototype used for method functions (or caller-provided
+ * callbacks) that merge two file specifications. They are passed a DSO
+ * structure pointer (or NULL if they are to be used independently of a DSO
+ * object) and two file specifications to merge. They should either return
+ * NULL (if there is an error condition) or a newly allocated string
+ * containing the result of merging that the caller will need to free with
+ * OPENSSL_free() when done. Here, merging means that bits and pieces are
+ * taken from each of the file specifications and added together in whatever
+ * fashion that is sensible for the DSO method in question. The only rule
+ * that really applies is that if the two specification contain pieces of the
+ * same type, the copy from the first string takes priority. One could see
+ * it as the first specification is the one given by the user and the second
+ * being a bunch of defaults to add on if they're missing in the first.
+ */
+typedef char *(*DSO_MERGER_FUNC)(DSO *, const char *, const char *);
+
+DSO *DSO_new(void);
+int DSO_free(DSO *dso);
+int DSO_flags(DSO *dso);
+int DSO_up_ref(DSO *dso);
+long DSO_ctrl(DSO *dso, int cmd, long larg, void *parg);
+
+/*
+ * These functions can be used to get/set the platform-independent filename
+ * used for a DSO. NB: set will fail if the DSO is already loaded.
+ */
+const char *DSO_get_filename(DSO *dso);
+int DSO_set_filename(DSO *dso, const char *filename);
+/*
+ * This function will invoke the DSO's name_converter callback to translate a
+ * filename, or if the callback isn't set it will instead use the DSO_METHOD's
+ * converter. If "filename" is NULL, the "filename" in the DSO itself will be
+ * used. If the DSO_FLAG_NO_NAME_TRANSLATION flag is set, then the filename is
+ * simply duplicated. NB: This function is usually called from within a
+ * DSO_METHOD during the processing of a DSO_load() call, and is exposed so
+ * that caller-created DSO_METHODs can do the same thing. A non-NULL return
+ * value will need to be OPENSSL_free()'d.
+ */
+char *DSO_convert_filename(DSO *dso, const char *filename);
+/*
+ * This function will invoke the DSO's merger callback to merge two file
+ * specifications, or if the callback isn't set it will instead use the
+ * DSO_METHOD's merger. A non-NULL return value will need to be
+ * OPENSSL_free()'d.
+ */
+char *DSO_merge(DSO *dso, const char *filespec1, const char *filespec2);
+
+/*
+ * The all-singing all-dancing load function, you normally pass NULL for the
+ * first and third parameters. Use DSO_up_ref and DSO_free for subsequent
+ * reference count handling. Any flags passed in will be set in the
+ * constructed DSO after its init() function but before the load operation.
+ * If 'dso' is non-NULL, 'flags' is ignored.
+ */
+DSO *DSO_load(DSO *dso, const char *filename, DSO_METHOD *meth, int flags);
+
+/* This function binds to a function inside a shared library. */
+DSO_FUNC_TYPE DSO_bind_func(DSO *dso, const char *symname);
+
+/*
+ * This method is the default, but will beg, borrow, or steal whatever method
+ * should be the default on any particular platform (including
+ * DSO_METH_null() if necessary).
+ */
+DSO_METHOD *DSO_METHOD_openssl(void);
+
+/*
+ * This function writes null-terminated pathname of DSO module containing
+ * 'addr' into 'sz' large caller-provided 'path' and returns the number of
+ * characters [including trailing zero] written to it. If 'sz' is 0 or
+ * negative, 'path' is ignored and required amount of characters [including
+ * trailing zero] to accommodate pathname is returned. If 'addr' is NULL, then
+ * pathname of cryptolib itself is returned. Negative or zero return value
+ * denotes error.
+ */
+int DSO_pathbyaddr(void *addr, char *path, int sz);
+
+/*
+ * Like DSO_pathbyaddr() but instead returns a handle to the DSO for the symbol
+ * or NULL on error.
+ */
+DSO *DSO_dsobyaddr(void *addr, int flags);
+
+/*
+ * This function should be used with caution! It looks up symbols in *all*
+ * loaded modules and if module gets unloaded by somebody else attempt to
+ * dereference the pointer is doomed to have fatal consequences. Primary
+ * usage for this function is to probe *core* system functionality, e.g.
+ * check if getnameinfo(3) is available at run-time without bothering about
+ * OS-specific details such as libc.so.versioning or where does it actually
+ * reside: in libc itself or libsocket.
+ */
+void *DSO_global_lookup(const char *name);
+
+#endif
diff --git a/include/internal/dsoerr.h b/include/internal/dsoerr.h
new file mode 100644
index 00000000..b1719e83
--- /dev/null
+++ b/include/internal/dsoerr.h
@@ -0,0 +1,48 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_DSOERR_H
+# define OSSL_INTERNAL_DSOERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_DSO_strings(void);
+
+/*
+ * DSO reason codes.
+ */
+# define DSO_R_CTRL_FAILED 100
+# define DSO_R_DSO_ALREADY_LOADED 110
+# define DSO_R_EMPTY_FILE_STRUCTURE 113
+# define DSO_R_FAILURE 114
+# define DSO_R_FILENAME_TOO_BIG 101
+# define DSO_R_FINISH_FAILED 102
+# define DSO_R_INCORRECT_FILE_SYNTAX 115
+# define DSO_R_LOAD_FAILED 103
+# define DSO_R_NAME_TRANSLATION_FAILED 109
+# define DSO_R_NO_FILENAME 111
+# define DSO_R_NULL_HANDLE 104
+# define DSO_R_SET_FILENAME_FAILED 112
+# define DSO_R_STACK_ERROR 105
+# define DSO_R_SYM_FAILURE 106
+# define DSO_R_UNLOAD_FAILED 107
+# define DSO_R_UNSUPPORTED 108
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/internal/endian.h b/include/internal/endian.h
new file mode 100644
index 00000000..8b34e03e
--- /dev/null
+++ b/include/internal/endian.h
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_ENDIAN_H
+# define OSSL_INTERNAL_ENDIAN_H
+# pragma once
+
+/*
+ * IS_LITTLE_ENDIAN and IS_BIG_ENDIAN can be used to detect the endiannes
+ * at compile time. To use it, DECLARE_IS_ENDIAN must be used to declare
+ * a variable.
+ *
+ * L_ENDIAN and B_ENDIAN can be used at preprocessor time. They can be set
+ * in the configarion using the lib_cppflags variable. If neither is
+ * set, it will fall back to code works with either endianness.
+ */
+
+# if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
+# define DECLARE_IS_ENDIAN const int ossl_is_little_endian = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+# define IS_LITTLE_ENDIAN (ossl_is_little_endian)
+# define IS_BIG_ENDIAN (!ossl_is_little_endian)
+# if defined(L_ENDIAN) && (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__)
+# error "L_ENDIAN defined on a big endian machine"
+# endif
+# if defined(B_ENDIAN) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
+# error "B_ENDIAN defined on a little endian machine"
+# endif
+# if !defined(L_ENDIAN) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
+# define L_ENDIAN
+# endif
+# if !defined(B_ENDIAN) && (__BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__)
+# define B_ENDIAN
+# endif
+# else
+# define DECLARE_IS_ENDIAN \
+ const union { \
+ long one; \
+ char little; \
+ } ossl_is_endian = { 1 }
+
+# define IS_LITTLE_ENDIAN (ossl_is_endian.little != 0)
+# define IS_BIG_ENDIAN (ossl_is_endian.little == 0)
+# endif
+
+#endif
diff --git a/include/internal/err.h b/include/internal/err.h
new file mode 100644
index 00000000..d8a308f0
--- /dev/null
+++ b/include/internal/err.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_ERR_H
+# define OSSL_INTERNAL_ERR_H
+# pragma once
+
+void err_free_strings_int(void);
+
+#endif
diff --git a/include/internal/ffc.h b/include/internal/ffc.h
new file mode 100644
index 00000000..79cb06ab
--- /dev/null
+++ b/include/internal/ffc.h
@@ -0,0 +1,212 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_FFC_H
+# define OSSL_INTERNAL_FFC_H
+# pragma once
+
+# include <openssl/core.h>
+# include <openssl/bn.h>
+# include <openssl/evp.h>
+# include <openssl/dh.h> /* Uses Error codes from DH */
+# include <openssl/params.h>
+# include <openssl/param_build.h>
+# include "internal/sizes.h"
+
+/* Default value for gindex when canonical generation of g is not used */
+# define FFC_UNVERIFIABLE_GINDEX -1
+
+/* The different types of FFC keys */
+# define FFC_PARAM_TYPE_DSA 0
+# define FFC_PARAM_TYPE_DH 1
+
+/*
+ * The mode used by functions that share code for both generation and
+ * verification. See ossl_ffc_params_FIPS186_4_gen_verify().
+ */
+#define FFC_PARAM_MODE_VERIFY 0
+#define FFC_PARAM_MODE_GENERATE 1
+
+/* Return codes for generation and validation of FFC parameters */
+#define FFC_PARAM_RET_STATUS_FAILED 0
+#define FFC_PARAM_RET_STATUS_SUCCESS 1
+/* Returned if validating and g is only partially verifiable */
+#define FFC_PARAM_RET_STATUS_UNVERIFIABLE_G 2
+
+/* Validation flags */
+# define FFC_PARAM_FLAG_VALIDATE_PQ 0x01
+# define FFC_PARAM_FLAG_VALIDATE_G 0x02
+# define FFC_PARAM_FLAG_VALIDATE_PQG \
+ (FFC_PARAM_FLAG_VALIDATE_PQ | FFC_PARAM_FLAG_VALIDATE_G)
+#define FFC_PARAM_FLAG_VALIDATE_LEGACY 0x04
+
+/*
+ * NB: These values must align with the equivalently named macros in
+ * openssl/dh.h. We cannot use those macros here in case DH has been disabled.
+ */
+# define FFC_CHECK_P_NOT_PRIME 0x00001
+# define FFC_CHECK_P_NOT_SAFE_PRIME 0x00002
+# define FFC_CHECK_UNKNOWN_GENERATOR 0x00004
+# define FFC_CHECK_NOT_SUITABLE_GENERATOR 0x00008
+# define FFC_CHECK_Q_NOT_PRIME 0x00010
+# define FFC_CHECK_INVALID_Q_VALUE 0x00020
+# define FFC_CHECK_INVALID_J_VALUE 0x00040
+
+# define FFC_CHECK_BAD_LN_PAIR 0x00080
+# define FFC_CHECK_INVALID_SEED_SIZE 0x00100
+# define FFC_CHECK_MISSING_SEED_OR_COUNTER 0x00200
+# define FFC_CHECK_INVALID_G 0x00400
+# define FFC_CHECK_INVALID_PQ 0x00800
+# define FFC_CHECK_INVALID_COUNTER 0x01000
+# define FFC_CHECK_P_MISMATCH 0x02000
+# define FFC_CHECK_Q_MISMATCH 0x04000
+# define FFC_CHECK_G_MISMATCH 0x08000
+# define FFC_CHECK_COUNTER_MISMATCH 0x10000
+
+/* Validation Return codes */
+# define FFC_ERROR_PUBKEY_TOO_SMALL 0x01
+# define FFC_ERROR_PUBKEY_TOO_LARGE 0x02
+# define FFC_ERROR_PUBKEY_INVALID 0x04
+# define FFC_ERROR_NOT_SUITABLE_GENERATOR 0x08
+# define FFC_ERROR_PRIVKEY_TOO_SMALL 0x10
+# define FFC_ERROR_PRIVKEY_TOO_LARGE 0x20
+
+/*
+ * Finite field cryptography (FFC) domain parameters are used by DH and DSA.
+ * Refer to FIPS186_4 Appendix A & B.
+ */
+typedef struct ffc_params_st {
+ /* Primes */
+ BIGNUM *p;
+ BIGNUM *q;
+ /* Generator */
+ BIGNUM *g;
+ /* DH X9.42 Optional Subgroup factor j >= 2 where p = j * q + 1 */
+ BIGNUM *j;
+
+ /* Required for FIPS186_4 validation of p, q and optionally canonical g */
+ unsigned char *seed;
+ /* If this value is zero the hash size is used as the seed length */
+ size_t seedlen;
+ /* Required for FIPS186_4 validation of p and q */
+ int pcounter;
+ int nid; /* The identity of a named group */
+
+ /*
+ * Required for FIPS186_4 generation & validation of canonical g.
+ * It uses unverifiable g if this value is -1.
+ */
+ int gindex;
+ int h; /* loop counter for unverifiable g */
+
+ unsigned int flags;
+ /*
+ * The digest to use for generation or validation. If this value is NULL,
+ * then the digest is chosen using the value of N.
+ */
+ const char *mdname;
+ const char *mdprops;
+} FFC_PARAMS;
+
+void ossl_ffc_params_init(FFC_PARAMS *params);
+void ossl_ffc_params_cleanup(FFC_PARAMS *params);
+void ossl_ffc_params_set0_pqg(FFC_PARAMS *params, BIGNUM *p, BIGNUM *q,
+ BIGNUM *g);
+void ossl_ffc_params_get0_pqg(const FFC_PARAMS *params, const BIGNUM **p,
+ const BIGNUM **q, const BIGNUM **g);
+void ossl_ffc_params_set0_j(FFC_PARAMS *d, BIGNUM *j);
+int ossl_ffc_params_set_seed(FFC_PARAMS *params,
+ const unsigned char *seed, size_t seedlen);
+void ossl_ffc_params_set_gindex(FFC_PARAMS *params, int index);
+void ossl_ffc_params_set_pcounter(FFC_PARAMS *params, int index);
+void ossl_ffc_params_set_h(FFC_PARAMS *params, int index);
+void ossl_ffc_params_set_flags(FFC_PARAMS *params, unsigned int flags);
+void ossl_ffc_params_enable_flags(FFC_PARAMS *params, unsigned int flags,
+ int enable);
+int ossl_ffc_set_digest(FFC_PARAMS *params, const char *alg, const char *props);
+
+int ossl_ffc_params_set_validate_params(FFC_PARAMS *params,
+ const unsigned char *seed,
+ size_t seedlen, int counter);
+void ossl_ffc_params_get_validate_params(const FFC_PARAMS *params,
+ unsigned char **seed, size_t *seedlen,
+ int *pcounter);
+
+int ossl_ffc_params_copy(FFC_PARAMS *dst, const FFC_PARAMS *src);
+int ossl_ffc_params_cmp(const FFC_PARAMS *a, const FFC_PARAMS *b, int ignore_q);
+
+#ifndef FIPS_MODULE
+int ossl_ffc_params_print(BIO *bp, const FFC_PARAMS *ffc, int indent);
+#endif /* FIPS_MODULE */
+
+
+int ossl_ffc_params_FIPS186_4_generate(OSSL_LIB_CTX *libctx, FFC_PARAMS *params,
+ int type, size_t L, size_t N,
+ int *res, BN_GENCB *cb);
+int ossl_ffc_params_FIPS186_2_generate(OSSL_LIB_CTX *libctx, FFC_PARAMS *params,
+ int type, size_t L, size_t N,
+ int *res, BN_GENCB *cb);
+
+int ossl_ffc_params_FIPS186_4_gen_verify(OSSL_LIB_CTX *libctx,
+ FFC_PARAMS *params, int mode, int type,
+ size_t L, size_t N, int *res,
+ BN_GENCB *cb);
+int ossl_ffc_params_FIPS186_2_gen_verify(OSSL_LIB_CTX *libctx,
+ FFC_PARAMS *params, int mode, int type,
+ size_t L, size_t N, int *res,
+ BN_GENCB *cb);
+
+int ossl_ffc_params_simple_validate(OSSL_LIB_CTX *libctx,
+ const FFC_PARAMS *params,
+ int paramstype, int *res);
+int ossl_ffc_params_full_validate(OSSL_LIB_CTX *libctx,
+ const FFC_PARAMS *params,
+ int paramstype, int *res);
+int ossl_ffc_params_FIPS186_4_validate(OSSL_LIB_CTX *libctx,
+ const FFC_PARAMS *params,
+ int type, int *res, BN_GENCB *cb);
+int ossl_ffc_params_FIPS186_2_validate(OSSL_LIB_CTX *libctx,
+ const FFC_PARAMS *params,
+ int type, int *res, BN_GENCB *cb);
+
+int ossl_ffc_generate_private_key(BN_CTX *ctx, const FFC_PARAMS *params,
+ int N, int s, BIGNUM *priv);
+
+int ossl_ffc_params_validate_unverifiable_g(BN_CTX *ctx, BN_MONT_CTX *mont,
+ const BIGNUM *p, const BIGNUM *q,
+ const BIGNUM *g, BIGNUM *tmp,
+ int *ret);
+
+int ossl_ffc_validate_public_key(const FFC_PARAMS *params,
+ const BIGNUM *pub_key, int *ret);
+int ossl_ffc_validate_public_key_partial(const FFC_PARAMS *params,
+ const BIGNUM *pub_key, int *ret);
+int ossl_ffc_validate_private_key(const BIGNUM *upper, const BIGNUM *priv_key,
+ int *ret);
+
+int ossl_ffc_params_todata(const FFC_PARAMS *ffc, OSSL_PARAM_BLD *tmpl,
+ OSSL_PARAM params[]);
+int ossl_ffc_params_fromdata(FFC_PARAMS *ffc, const OSSL_PARAM params[]);
+
+typedef struct dh_named_group_st DH_NAMED_GROUP;
+const DH_NAMED_GROUP *ossl_ffc_name_to_dh_named_group(const char *name);
+const DH_NAMED_GROUP *ossl_ffc_uid_to_dh_named_group(int uid);
+#ifndef OPENSSL_NO_DH
+const DH_NAMED_GROUP *ossl_ffc_numbers_to_dh_named_group(const BIGNUM *p,
+ const BIGNUM *q,
+ const BIGNUM *g);
+#endif
+int ossl_ffc_named_group_get_uid(const DH_NAMED_GROUP *group);
+const char *ossl_ffc_named_group_get_name(const DH_NAMED_GROUP *);
+#ifndef OPENSSL_NO_DH
+const BIGNUM *ossl_ffc_named_group_get_q(const DH_NAMED_GROUP *group);
+int ossl_ffc_named_group_set_pqg(FFC_PARAMS *ffc, const DH_NAMED_GROUP *group);
+#endif
+
+#endif /* OSSL_INTERNAL_FFC_H */
diff --git a/include/internal/ktls.h b/include/internal/ktls.h
new file mode 100644
index 00000000..95492fd0
--- /dev/null
+++ b/include/internal/ktls.h
@@ -0,0 +1,404 @@
+/*
+ * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#if defined(OPENSSL_SYS_LINUX)
+# ifndef OPENSSL_NO_KTLS
+# include <linux/version.h>
+# if LINUX_VERSION_CODE < KERNEL_VERSION(4, 13, 0)
+# define OPENSSL_NO_KTLS
+# ifndef PEDANTIC
+# warning "KTLS requires Kernel Headers >= 4.13.0"
+# warning "Skipping Compilation of KTLS"
+# endif
+# endif
+# endif
+#endif
+
+#ifndef HEADER_INTERNAL_KTLS
+# define HEADER_INTERNAL_KTLS
+# pragma once
+
+# ifndef OPENSSL_NO_KTLS
+
+# if defined(__FreeBSD__)
+# include <sys/types.h>
+# include <sys/socket.h>
+# include <sys/ktls.h>
+# include <netinet/in.h>
+# include <netinet/tcp.h>
+# include <openssl/ssl3.h>
+
+# ifndef TCP_RXTLS_ENABLE
+# define OPENSSL_NO_KTLS_RX
+# endif
+# define OPENSSL_KTLS_AES_GCM_128
+# define OPENSSL_KTLS_AES_GCM_256
+# define OPENSSL_KTLS_TLS13
+
+typedef struct tls_enable ktls_crypto_info_t;
+
+/*
+ * FreeBSD does not require any additional steps to enable KTLS before
+ * setting keys.
+ */
+static ossl_inline int ktls_enable(int fd)
+{
+ return 1;
+}
+
+/*
+ * The TCP_TXTLS_ENABLE socket option marks the outgoing socket buffer
+ * as using TLS. If successful, then data sent using this socket will
+ * be encrypted and encapsulated in TLS records using the tls_en
+ * provided here.
+ *
+ * The TCP_RXTLS_ENABLE socket option marks the incoming socket buffer
+ * as using TLS. If successful, then data received for this socket will
+ * be authenticated and decrypted using the tls_en provided here.
+ */
+static ossl_inline int ktls_start(int fd, ktls_crypto_info_t *tls_en, int is_tx)
+{
+ if (is_tx)
+ return setsockopt(fd, IPPROTO_TCP, TCP_TXTLS_ENABLE,
+ tls_en, sizeof(*tls_en)) ? 0 : 1;
+# ifndef OPENSSL_NO_KTLS_RX
+ return setsockopt(fd, IPPROTO_TCP, TCP_RXTLS_ENABLE, tls_en,
+ sizeof(*tls_en)) ? 0 : 1;
+# else
+ return 0;
+# endif
+}
+
+/*
+ * Send a TLS record using the tls_en provided in ktls_start and use
+ * record_type instead of the default SSL3_RT_APPLICATION_DATA.
+ * When the socket is non-blocking, then this call either returns EAGAIN or
+ * the entire record is pushed to TCP. It is impossible to send a partial
+ * record using this control message.
+ */
+static ossl_inline int ktls_send_ctrl_message(int fd, unsigned char record_type,
+ const void *data, size_t length)
+{
+ struct msghdr msg = { 0 };
+ int cmsg_len = sizeof(record_type);
+ struct cmsghdr *cmsg;
+ char buf[CMSG_SPACE(cmsg_len)];
+ struct iovec msg_iov; /* Vector of data to send/receive into */
+
+ msg.msg_control = buf;
+ msg.msg_controllen = sizeof(buf);
+ cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_level = IPPROTO_TCP;
+ cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
+ cmsg->cmsg_len = CMSG_LEN(cmsg_len);
+ *((unsigned char *)CMSG_DATA(cmsg)) = record_type;
+ msg.msg_controllen = cmsg->cmsg_len;
+
+ msg_iov.iov_base = (void *)data;
+ msg_iov.iov_len = length;
+ msg.msg_iov = &msg_iov;
+ msg.msg_iovlen = 1;
+
+ return sendmsg(fd, &msg, 0);
+}
+
+# ifdef OPENSSL_NO_KTLS_RX
+
+static ossl_inline int ktls_read_record(int fd, void *data, size_t length)
+{
+ return -1;
+}
+
+# else /* !defined(OPENSSL_NO_KTLS_RX) */
+
+/*
+ * Receive a TLS record using the tls_en provided in ktls_start. The
+ * kernel strips any explicit IV and authentication tag, but provides
+ * the TLS record header via a control message. If there is an error
+ * with the TLS record such as an invalid header, invalid padding, or
+ * authentication failure recvmsg() will fail with an error.
+ */
+static ossl_inline int ktls_read_record(int fd, void *data, size_t length)
+{
+ struct msghdr msg = { 0 };
+ int cmsg_len = sizeof(struct tls_get_record);
+ struct tls_get_record *tgr;
+ struct cmsghdr *cmsg;
+ char buf[CMSG_SPACE(cmsg_len)];
+ struct iovec msg_iov; /* Vector of data to send/receive into */
+ int ret;
+ unsigned char *p = data;
+ const size_t prepend_length = SSL3_RT_HEADER_LENGTH;
+
+ if (length <= prepend_length) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ msg.msg_control = buf;
+ msg.msg_controllen = sizeof(buf);
+
+ msg_iov.iov_base = p + prepend_length;
+ msg_iov.iov_len = length - prepend_length;
+ msg.msg_iov = &msg_iov;
+ msg.msg_iovlen = 1;
+
+ ret = recvmsg(fd, &msg, 0);
+ if (ret <= 0)
+ return ret;
+
+ if ((msg.msg_flags & (MSG_EOR | MSG_CTRUNC)) != MSG_EOR) {
+ errno = EMSGSIZE;
+ return -1;
+ }
+
+ if (msg.msg_controllen == 0) {
+ errno = EBADMSG;
+ return -1;
+ }
+
+ cmsg = CMSG_FIRSTHDR(&msg);
+ if (cmsg->cmsg_level != IPPROTO_TCP || cmsg->cmsg_type != TLS_GET_RECORD
+ || cmsg->cmsg_len != CMSG_LEN(cmsg_len)) {
+ errno = EBADMSG;
+ return -1;
+ }
+
+ tgr = (struct tls_get_record *)CMSG_DATA(cmsg);
+ p[0] = tgr->tls_type;
+ p[1] = tgr->tls_vmajor;
+ p[2] = tgr->tls_vminor;
+ *(uint16_t *)(p + 3) = htons(ret);
+
+ return ret + prepend_length;
+}
+
+# endif /* OPENSSL_NO_KTLS_RX */
+
+/*
+ * KTLS enables the sendfile system call to send data from a file over
+ * TLS.
+ */
+static ossl_inline ossl_ssize_t ktls_sendfile(int s, int fd, off_t off,
+ size_t size, int flags)
+{
+ off_t sbytes = 0;
+ int ret;
+
+ ret = sendfile(fd, s, off, size, NULL, &sbytes, flags);
+ if (ret == -1 && sbytes == 0)
+ return -1;
+ return sbytes;
+}
+
+# endif /* __FreeBSD__ */
+
+# if defined(OPENSSL_SYS_LINUX)
+
+# include <linux/tls.h>
+# if LINUX_VERSION_CODE < KERNEL_VERSION(4, 17, 0)
+# define OPENSSL_NO_KTLS_RX
+# ifndef PEDANTIC
+# warning "KTLS requires Kernel Headers >= 4.17.0 for receiving"
+# warning "Skipping Compilation of KTLS receive data path"
+# endif
+# endif
+# define OPENSSL_KTLS_AES_GCM_128
+# if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 1, 0)
+# define OPENSSL_KTLS_AES_GCM_256
+# define OPENSSL_KTLS_TLS13
+# if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 2, 0)
+# define OPENSSL_KTLS_AES_CCM_128
+# if LINUX_VERSION_CODE >= KERNEL_VERSION(5, 11, 0)
+# ifndef OPENSSL_NO_CHACHA
+# define OPENSSL_KTLS_CHACHA20_POLY1305
+# endif
+# endif
+# endif
+# endif
+
+# include <sys/sendfile.h>
+# include <netinet/tcp.h>
+# include <linux/socket.h>
+# include <openssl/ssl3.h>
+# include <openssl/tls1.h>
+# include <openssl/evp.h>
+
+# ifndef SOL_TLS
+# define SOL_TLS 282
+# endif
+
+# ifndef TCP_ULP
+# define TCP_ULP 31
+# endif
+
+# ifndef TLS_RX
+# define TLS_RX 2
+# endif
+
+struct tls_crypto_info_all {
+ union {
+# ifdef OPENSSL_KTLS_AES_GCM_128
+ struct tls12_crypto_info_aes_gcm_128 gcm128;
+# endif
+# ifdef OPENSSL_KTLS_AES_GCM_256
+ struct tls12_crypto_info_aes_gcm_256 gcm256;
+# endif
+# ifdef OPENSSL_KTLS_AES_CCM_128
+ struct tls12_crypto_info_aes_ccm_128 ccm128;
+# endif
+# ifdef OPENSSL_KTLS_CHACHA20_POLY1305
+ struct tls12_crypto_info_chacha20_poly1305 chacha20poly1305;
+# endif
+ };
+ size_t tls_crypto_info_len;
+};
+
+typedef struct tls_crypto_info_all ktls_crypto_info_t;
+
+/*
+ * When successful, this socket option doesn't change the behaviour of the
+ * TCP socket, except changing the TCP setsockopt handler to enable the
+ * processing of SOL_TLS socket options. All other functionality remains the
+ * same.
+ */
+static ossl_inline int ktls_enable(int fd)
+{
+ return setsockopt(fd, SOL_TCP, TCP_ULP, "tls", sizeof("tls")) ? 0 : 1;
+}
+
+/*
+ * The TLS_TX socket option changes the send/sendmsg handlers of the TCP socket.
+ * If successful, then data sent using this socket will be encrypted and
+ * encapsulated in TLS records using the crypto_info provided here.
+ * The TLS_RX socket option changes the recv/recvmsg handlers of the TCP socket.
+ * If successful, then data received using this socket will be decrypted,
+ * authenticated and decapsulated using the crypto_info provided here.
+ */
+static ossl_inline int ktls_start(int fd, ktls_crypto_info_t *crypto_info,
+ int is_tx)
+{
+ return setsockopt(fd, SOL_TLS, is_tx ? TLS_TX : TLS_RX,
+ crypto_info, crypto_info->tls_crypto_info_len) ? 0 : 1;
+}
+
+/*
+ * Send a TLS record using the crypto_info provided in ktls_start and use
+ * record_type instead of the default SSL3_RT_APPLICATION_DATA.
+ * When the socket is non-blocking, then this call either returns EAGAIN or
+ * the entire record is pushed to TCP. It is impossible to send a partial
+ * record using this control message.
+ */
+static ossl_inline int ktls_send_ctrl_message(int fd, unsigned char record_type,
+ const void *data, size_t length)
+{
+ struct msghdr msg;
+ int cmsg_len = sizeof(record_type);
+ struct cmsghdr *cmsg;
+ union {
+ struct cmsghdr hdr;
+ char buf[CMSG_SPACE(sizeof(unsigned char))];
+ } cmsgbuf;
+ struct iovec msg_iov; /* Vector of data to send/receive into */
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_control = cmsgbuf.buf;
+ msg.msg_controllen = sizeof(cmsgbuf.buf);
+ cmsg = CMSG_FIRSTHDR(&msg);
+ cmsg->cmsg_level = SOL_TLS;
+ cmsg->cmsg_type = TLS_SET_RECORD_TYPE;
+ cmsg->cmsg_len = CMSG_LEN(cmsg_len);
+ *((unsigned char *)CMSG_DATA(cmsg)) = record_type;
+ msg.msg_controllen = cmsg->cmsg_len;
+
+ msg_iov.iov_base = (void *)data;
+ msg_iov.iov_len = length;
+ msg.msg_iov = &msg_iov;
+ msg.msg_iovlen = 1;
+
+ return sendmsg(fd, &msg, 0);
+}
+
+/*
+ * KTLS enables the sendfile system call to send data from a file over TLS.
+ * @flags are ignored on Linux. (placeholder for FreeBSD sendfile)
+ * */
+static ossl_inline ossl_ssize_t ktls_sendfile(int s, int fd, off_t off, size_t size, int flags)
+{
+ return sendfile(s, fd, &off, size);
+}
+
+# ifdef OPENSSL_NO_KTLS_RX
+
+
+static ossl_inline int ktls_read_record(int fd, void *data, size_t length)
+{
+ return -1;
+}
+
+# else /* !defined(OPENSSL_NO_KTLS_RX) */
+
+/*
+ * Receive a TLS record using the crypto_info provided in ktls_start.
+ * The kernel strips the TLS record header, IV and authentication tag,
+ * returning only the plaintext data or an error on failure.
+ * We add the TLS record header here to satisfy routines in rec_layer_s3.c
+ */
+static ossl_inline int ktls_read_record(int fd, void *data, size_t length)
+{
+ struct msghdr msg;
+ struct cmsghdr *cmsg;
+ union {
+ struct cmsghdr hdr;
+ char buf[CMSG_SPACE(sizeof(unsigned char))];
+ } cmsgbuf;
+ struct iovec msg_iov;
+ int ret;
+ unsigned char *p = data;
+ const size_t prepend_length = SSL3_RT_HEADER_LENGTH;
+
+ if (length < prepend_length + EVP_GCM_TLS_TAG_LEN) {
+ errno = EINVAL;
+ return -1;
+ }
+
+ memset(&msg, 0, sizeof(msg));
+ msg.msg_control = cmsgbuf.buf;
+ msg.msg_controllen = sizeof(cmsgbuf.buf);
+
+ msg_iov.iov_base = p + prepend_length;
+ msg_iov.iov_len = length - prepend_length - EVP_GCM_TLS_TAG_LEN;
+ msg.msg_iov = &msg_iov;
+ msg.msg_iovlen = 1;
+
+ ret = recvmsg(fd, &msg, 0);
+ if (ret < 0)
+ return ret;
+
+ if (msg.msg_controllen > 0) {
+ cmsg = CMSG_FIRSTHDR(&msg);
+ if (cmsg->cmsg_type == TLS_GET_RECORD_TYPE) {
+ p[0] = *((unsigned char *)CMSG_DATA(cmsg));
+ p[1] = TLS1_2_VERSION_MAJOR;
+ p[2] = TLS1_2_VERSION_MINOR;
+ /* returned length is limited to msg_iov.iov_len above */
+ p[3] = (ret >> 8) & 0xff;
+ p[4] = ret & 0xff;
+ ret += prepend_length;
+ }
+ }
+
+ return ret;
+}
+
+# endif /* OPENSSL_NO_KTLS_RX */
+
+# endif /* OPENSSL_SYS_LINUX */
+# endif /* OPENSSL_NO_KTLS */
+#endif /* HEADER_INTERNAL_KTLS */
diff --git a/include/internal/namemap.h b/include/internal/namemap.h
new file mode 100644
index 00000000..a4c60ae6
--- /dev/null
+++ b/include/internal/namemap.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include "internal/cryptlib.h"
+
+typedef struct ossl_namemap_st OSSL_NAMEMAP;
+
+OSSL_NAMEMAP *ossl_namemap_stored(OSSL_LIB_CTX *libctx);
+
+OSSL_NAMEMAP *ossl_namemap_new(void);
+void ossl_namemap_free(OSSL_NAMEMAP *namemap);
+int ossl_namemap_empty(OSSL_NAMEMAP *namemap);
+
+int ossl_namemap_add_name(OSSL_NAMEMAP *namemap, int number, const char *name);
+int ossl_namemap_add_name_n(OSSL_NAMEMAP *namemap, int number,
+ const char *name, size_t name_len);
+
+/*
+ * The number<->name relationship is 1<->many
+ * Therefore, the name->number mapping is a simple function, while the
+ * number->name mapping is an iterator.
+ */
+int ossl_namemap_name2num(const OSSL_NAMEMAP *namemap, const char *name);
+int ossl_namemap_name2num_n(const OSSL_NAMEMAP *namemap,
+ const char *name, size_t name_len);
+const char *ossl_namemap_num2name(const OSSL_NAMEMAP *namemap, int number,
+ size_t idx);
+int ossl_namemap_doall_names(const OSSL_NAMEMAP *namemap, int number,
+ void (*fn)(const char *name, void *data),
+ void *data);
+
+/*
+ * A utility that handles several names in a string, divided by a given
+ * separator.
+ */
+int ossl_namemap_add_names(OSSL_NAMEMAP *namemap, int number,
+ const char *names, const char separator);
diff --git a/include/internal/nelem.h b/include/internal/nelem.h
new file mode 100644
index 00000000..b758513b
--- /dev/null
+++ b/include/internal/nelem.h
@@ -0,0 +1,15 @@
+/*
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_NELEM_H
+# define OSSL_INTERNAL_NELEM_H
+# pragma once
+
+# define OSSL_NELEM(x) (sizeof(x)/sizeof((x)[0]))
+#endif
diff --git a/include/internal/numbers.h b/include/internal/numbers.h
new file mode 100644
index 00000000..4f4d3306
--- /dev/null
+++ b/include/internal/numbers.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_NUMBERS_H
+# define OSSL_INTERNAL_NUMBERS_H
+# pragma once
+
+# include <limits.h>
+
+# if (-1 & 3) == 0x03 /* Two's complement */
+
+# define __MAXUINT__(T) ((T) -1)
+# define __MAXINT__(T) ((T) ((((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)) ^ __MAXUINT__(T)))
+# define __MININT__(T) (-__MAXINT__(T) - 1)
+
+# elif (-1 & 3) == 0x02 /* One's complement */
+
+# define __MAXUINT__(T) (((T) -1) + 1)
+# define __MAXINT__(T) ((T) ((((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)) ^ __MAXUINT__(T)))
+# define __MININT__(T) (-__MAXINT__(T))
+
+# elif (-1 & 3) == 0x01 /* Sign/magnitude */
+
+# define __MAXINT__(T) ((T) (((((T) 1) << ((sizeof(T) * CHAR_BIT) - 2)) - 1) | (((T) 1) << ((sizeof(T) * CHAR_BIT) - 2))))
+# define __MAXUINT__(T) ((T) (__MAXINT__(T) | (((T) 1) << ((sizeof(T) * CHAR_BIT) - 1))))
+# define __MININT__(T) (-__MAXINT__(T))
+
+# else
+
+# error "do not know the integer encoding on this architecture"
+
+# endif
+
+# ifndef INT8_MAX
+# define INT8_MIN __MININT__(int8_t)
+# define INT8_MAX __MAXINT__(int8_t)
+# define UINT8_MAX __MAXUINT__(uint8_t)
+# endif
+
+# ifndef INT16_MAX
+# define INT16_MIN __MININT__(int16_t)
+# define INT16_MAX __MAXINT__(int16_t)
+# define UINT16_MAX __MAXUINT__(uint16_t)
+# endif
+
+# ifndef INT32_MAX
+# define INT32_MIN __MININT__(int32_t)
+# define INT32_MAX __MAXINT__(int32_t)
+# define UINT32_MAX __MAXUINT__(uint32_t)
+# endif
+
+# ifndef INT64_MAX
+# define INT64_MIN __MININT__(int64_t)
+# define INT64_MAX __MAXINT__(int64_t)
+# define UINT64_MAX __MAXUINT__(uint64_t)
+# endif
+
+# ifndef INT128_MAX
+# if defined(__SIZEOF_INT128__) && __SIZEOF_INT128__ == 16
+typedef __int128_t int128_t;
+typedef __uint128_t uint128_t;
+# define INT128_MIN __MININT__(int128_t)
+# define INT128_MAX __MAXINT__(int128_t)
+# define UINT128_MAX __MAXUINT__(uint128_t)
+# endif
+# endif
+
+# ifndef SIZE_MAX
+# define SIZE_MAX __MAXUINT__(size_t)
+# endif
+
+# ifndef OSSL_INTMAX_MAX
+# define OSSL_INTMAX_MIN __MININT__(ossl_intmax_t)
+# define OSSL_INTMAX_MAX __MAXINT__(ossl_intmax_t)
+# define OSSL_UINTMAX_MAX __MAXUINT__(ossl_uintmax_t)
+# endif
+
+#endif
+
diff --git a/include/internal/o_dir.h b/include/internal/o_dir.h
new file mode 100644
index 00000000..add34d14
--- /dev/null
+++ b/include/internal/o_dir.h
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This file is dual-licensed and is also available under the following
+ * terms:
+ *
+ * Copyright (c) 2004, Richard Levitte <richard@levitte.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.
+ *
+ * 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.
+ */
+
+#ifndef OSSL_INTERNAL_O_DIR_H
+# define OSSL_INTERNAL_O_DIR_H
+# pragma once
+
+typedef struct OPENSSL_dir_context_st OPENSSL_DIR_CTX;
+
+/*
+ * returns NULL on error or end-of-directory. If it is end-of-directory,
+ * errno will be zero
+ */
+const char *OPENSSL_DIR_read(OPENSSL_DIR_CTX **ctx, const char *directory);
+/* returns 1 on success, 0 on error */
+int OPENSSL_DIR_end(OPENSSL_DIR_CTX **ctx);
+
+#endif /* LPDIR_H */
diff --git a/include/internal/packet.h b/include/internal/packet.h
new file mode 100644
index 00000000..170997db
--- /dev/null
+++ b/include/internal/packet.h
@@ -0,0 +1,902 @@
+/*
+ * Copyright 2015-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_PACKET_H
+# define OSSL_INTERNAL_PACKET_H
+# pragma once
+
+# include <string.h>
+# include <openssl/bn.h>
+# include <openssl/buffer.h>
+# include <openssl/crypto.h>
+# include <openssl/e_os2.h>
+
+# include "internal/numbers.h"
+
+typedef struct {
+ /* Pointer to where we are currently reading from */
+ const unsigned char *curr;
+ /* Number of bytes remaining */
+ size_t remaining;
+} PACKET;
+
+/* Internal unchecked shorthand; don't use outside this file. */
+static ossl_inline void packet_forward(PACKET *pkt, size_t len)
+{
+ pkt->curr += len;
+ pkt->remaining -= len;
+}
+
+/*
+ * Returns the number of bytes remaining to be read in the PACKET
+ */
+static ossl_inline size_t PACKET_remaining(const PACKET *pkt)
+{
+ return pkt->remaining;
+}
+
+/*
+ * Returns a pointer to the first byte after the packet data.
+ * Useful for integrating with non-PACKET parsing code.
+ * Specifically, we use PACKET_end() to verify that a d2i_... call
+ * has consumed the entire packet contents.
+ */
+static ossl_inline const unsigned char *PACKET_end(const PACKET *pkt)
+{
+ return pkt->curr + pkt->remaining;
+}
+
+/*
+ * Returns a pointer to the PACKET's current position.
+ * For use in non-PACKETized APIs.
+ */
+static ossl_inline const unsigned char *PACKET_data(const PACKET *pkt)
+{
+ return pkt->curr;
+}
+
+/*
+ * Initialise a PACKET with |len| bytes held in |buf|. This does not make a
+ * copy of the data so |buf| must be present for the whole time that the PACKET
+ * is being used.
+ */
+__owur static ossl_inline int PACKET_buf_init(PACKET *pkt,
+ const unsigned char *buf,
+ size_t len)
+{
+ /* Sanity check for negative values. */
+ if (len > (size_t)(SIZE_MAX / 2))
+ return 0;
+
+ pkt->curr = buf;
+ pkt->remaining = len;
+ return 1;
+}
+
+/* Initialize a PACKET to hold zero bytes. */
+static ossl_inline void PACKET_null_init(PACKET *pkt)
+{
+ pkt->curr = NULL;
+ pkt->remaining = 0;
+}
+
+/*
+ * Returns 1 if the packet has length |num| and its contents equal the |num|
+ * bytes read from |ptr|. Returns 0 otherwise (lengths or contents not equal).
+ * If lengths are equal, performs the comparison in constant time.
+ */
+__owur static ossl_inline int PACKET_equal(const PACKET *pkt, const void *ptr,
+ size_t num)
+{
+ if (PACKET_remaining(pkt) != num)
+ return 0;
+ return CRYPTO_memcmp(pkt->curr, ptr, num) == 0;
+}
+
+/*
+ * Peek ahead and initialize |subpkt| with the next |len| bytes read from |pkt|.
+ * Data is not copied: the |subpkt| packet will share its underlying buffer with
+ * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|.
+ */
+__owur static ossl_inline int PACKET_peek_sub_packet(const PACKET *pkt,
+ PACKET *subpkt, size_t len)
+{
+ if (PACKET_remaining(pkt) < len)
+ return 0;
+
+ return PACKET_buf_init(subpkt, pkt->curr, len);
+}
+
+/*
+ * Initialize |subpkt| with the next |len| bytes read from |pkt|. Data is not
+ * copied: the |subpkt| packet will share its underlying buffer with the
+ * original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|.
+ */
+__owur static ossl_inline int PACKET_get_sub_packet(PACKET *pkt,
+ PACKET *subpkt, size_t len)
+{
+ if (!PACKET_peek_sub_packet(pkt, subpkt, len))
+ return 0;
+
+ packet_forward(pkt, len);
+
+ return 1;
+}
+
+/*
+ * Peek ahead at 2 bytes in network order from |pkt| and store the value in
+ * |*data|
+ */
+__owur static ossl_inline int PACKET_peek_net_2(const PACKET *pkt,
+ unsigned int *data)
+{
+ if (PACKET_remaining(pkt) < 2)
+ return 0;
+
+ *data = ((unsigned int)(*pkt->curr)) << 8;
+ *data |= *(pkt->curr + 1);
+
+ return 1;
+}
+
+/* Equivalent of n2s */
+/* Get 2 bytes in network order from |pkt| and store the value in |*data| */
+__owur static ossl_inline int PACKET_get_net_2(PACKET *pkt, unsigned int *data)
+{
+ if (!PACKET_peek_net_2(pkt, data))
+ return 0;
+
+ packet_forward(pkt, 2);
+
+ return 1;
+}
+
+/* Same as PACKET_get_net_2() but for a size_t */
+__owur static ossl_inline int PACKET_get_net_2_len(PACKET *pkt, size_t *data)
+{
+ unsigned int i;
+ int ret = PACKET_get_net_2(pkt, &i);
+
+ if (ret)
+ *data = (size_t)i;
+
+ return ret;
+}
+
+/*
+ * Peek ahead at 3 bytes in network order from |pkt| and store the value in
+ * |*data|
+ */
+__owur static ossl_inline int PACKET_peek_net_3(const PACKET *pkt,
+ unsigned long *data)
+{
+ if (PACKET_remaining(pkt) < 3)
+ return 0;
+
+ *data = ((unsigned long)(*pkt->curr)) << 16;
+ *data |= ((unsigned long)(*(pkt->curr + 1))) << 8;
+ *data |= *(pkt->curr + 2);
+
+ return 1;
+}
+
+/* Equivalent of n2l3 */
+/* Get 3 bytes in network order from |pkt| and store the value in |*data| */
+__owur static ossl_inline int PACKET_get_net_3(PACKET *pkt, unsigned long *data)
+{
+ if (!PACKET_peek_net_3(pkt, data))
+ return 0;
+
+ packet_forward(pkt, 3);
+
+ return 1;
+}
+
+/* Same as PACKET_get_net_3() but for a size_t */
+__owur static ossl_inline int PACKET_get_net_3_len(PACKET *pkt, size_t *data)
+{
+ unsigned long i;
+ int ret = PACKET_get_net_3(pkt, &i);
+
+ if (ret)
+ *data = (size_t)i;
+
+ return ret;
+}
+
+/*
+ * Peek ahead at 4 bytes in network order from |pkt| and store the value in
+ * |*data|
+ */
+__owur static ossl_inline int PACKET_peek_net_4(const PACKET *pkt,
+ unsigned long *data)
+{
+ if (PACKET_remaining(pkt) < 4)
+ return 0;
+
+ *data = ((unsigned long)(*pkt->curr)) << 24;
+ *data |= ((unsigned long)(*(pkt->curr + 1))) << 16;
+ *data |= ((unsigned long)(*(pkt->curr + 2))) << 8;
+ *data |= *(pkt->curr + 3);
+
+ return 1;
+}
+
+/* Equivalent of n2l */
+/* Get 4 bytes in network order from |pkt| and store the value in |*data| */
+__owur static ossl_inline int PACKET_get_net_4(PACKET *pkt, unsigned long *data)
+{
+ if (!PACKET_peek_net_4(pkt, data))
+ return 0;
+
+ packet_forward(pkt, 4);
+
+ return 1;
+}
+
+/* Same as PACKET_get_net_4() but for a size_t */
+__owur static ossl_inline int PACKET_get_net_4_len(PACKET *pkt, size_t *data)
+{
+ unsigned long i;
+ int ret = PACKET_get_net_4(pkt, &i);
+
+ if (ret)
+ *data = (size_t)i;
+
+ return ret;
+}
+
+/* Peek ahead at 1 byte from |pkt| and store the value in |*data| */
+__owur static ossl_inline int PACKET_peek_1(const PACKET *pkt,
+ unsigned int *data)
+{
+ if (!PACKET_remaining(pkt))
+ return 0;
+
+ *data = *pkt->curr;
+
+ return 1;
+}
+
+/* Get 1 byte from |pkt| and store the value in |*data| */
+__owur static ossl_inline int PACKET_get_1(PACKET *pkt, unsigned int *data)
+{
+ if (!PACKET_peek_1(pkt, data))
+ return 0;
+
+ packet_forward(pkt, 1);
+
+ return 1;
+}
+
+/* Same as PACKET_get_1() but for a size_t */
+__owur static ossl_inline int PACKET_get_1_len(PACKET *pkt, size_t *data)
+{
+ unsigned int i;
+ int ret = PACKET_get_1(pkt, &i);
+
+ if (ret)
+ *data = (size_t)i;
+
+ return ret;
+}
+
+/*
+ * Peek ahead at 4 bytes in reverse network order from |pkt| and store the value
+ * in |*data|
+ */
+__owur static ossl_inline int PACKET_peek_4(const PACKET *pkt,
+ unsigned long *data)
+{
+ if (PACKET_remaining(pkt) < 4)
+ return 0;
+
+ *data = *pkt->curr;
+ *data |= ((unsigned long)(*(pkt->curr + 1))) << 8;
+ *data |= ((unsigned long)(*(pkt->curr + 2))) << 16;
+ *data |= ((unsigned long)(*(pkt->curr + 3))) << 24;
+
+ return 1;
+}
+
+/* Equivalent of c2l */
+/*
+ * Get 4 bytes in reverse network order from |pkt| and store the value in
+ * |*data|
+ */
+__owur static ossl_inline int PACKET_get_4(PACKET *pkt, unsigned long *data)
+{
+ if (!PACKET_peek_4(pkt, data))
+ return 0;
+
+ packet_forward(pkt, 4);
+
+ return 1;
+}
+
+/*
+ * Peek ahead at |len| bytes from the |pkt| and store a pointer to them in
+ * |*data|. This just points at the underlying buffer that |pkt| is using. The
+ * caller should not free this data directly (it will be freed when the
+ * underlying buffer gets freed
+ */
+__owur static ossl_inline int PACKET_peek_bytes(const PACKET *pkt,
+ const unsigned char **data,
+ size_t len)
+{
+ if (PACKET_remaining(pkt) < len)
+ return 0;
+
+ *data = pkt->curr;
+
+ return 1;
+}
+
+/*
+ * Read |len| bytes from the |pkt| and store a pointer to them in |*data|. This
+ * just points at the underlying buffer that |pkt| is using. The caller should
+ * not free this data directly (it will be freed when the underlying buffer gets
+ * freed
+ */
+__owur static ossl_inline int PACKET_get_bytes(PACKET *pkt,
+ const unsigned char **data,
+ size_t len)
+{
+ if (!PACKET_peek_bytes(pkt, data, len))
+ return 0;
+
+ packet_forward(pkt, len);
+
+ return 1;
+}
+
+/* Peek ahead at |len| bytes from |pkt| and copy them to |data| */
+__owur static ossl_inline int PACKET_peek_copy_bytes(const PACKET *pkt,
+ unsigned char *data,
+ size_t len)
+{
+ if (PACKET_remaining(pkt) < len)
+ return 0;
+
+ memcpy(data, pkt->curr, len);
+
+ return 1;
+}
+
+/*
+ * Read |len| bytes from |pkt| and copy them to |data|.
+ * The caller is responsible for ensuring that |data| can hold |len| bytes.
+ */
+__owur static ossl_inline int PACKET_copy_bytes(PACKET *pkt,
+ unsigned char *data, size_t len)
+{
+ if (!PACKET_peek_copy_bytes(pkt, data, len))
+ return 0;
+
+ packet_forward(pkt, len);
+
+ return 1;
+}
+
+/*
+ * Copy packet data to |dest|, and set |len| to the number of copied bytes.
+ * If the packet has more than |dest_len| bytes, nothing is copied.
+ * Returns 1 if the packet data fits in |dest_len| bytes, 0 otherwise.
+ * Does not forward PACKET position (because it is typically the last thing
+ * done with a given PACKET).
+ */
+__owur static ossl_inline int PACKET_copy_all(const PACKET *pkt,
+ unsigned char *dest,
+ size_t dest_len, size_t *len)
+{
+ if (PACKET_remaining(pkt) > dest_len) {
+ *len = 0;
+ return 0;
+ }
+ *len = pkt->remaining;
+ memcpy(dest, pkt->curr, pkt->remaining);
+ return 1;
+}
+
+/*
+ * Copy |pkt| bytes to a newly allocated buffer and store a pointer to the
+ * result in |*data|, and the length in |len|.
+ * If |*data| is not NULL, the old data is OPENSSL_free'd.
+ * If the packet is empty, or malloc fails, |*data| will be set to NULL.
+ * Returns 1 if the malloc succeeds and 0 otherwise.
+ * Does not forward PACKET position (because it is typically the last thing
+ * done with a given PACKET).
+ */
+__owur static ossl_inline int PACKET_memdup(const PACKET *pkt,
+ unsigned char **data, size_t *len)
+{
+ size_t length;
+
+ OPENSSL_free(*data);
+ *data = NULL;
+ *len = 0;
+
+ length = PACKET_remaining(pkt);
+
+ if (length == 0)
+ return 1;
+
+ *data = OPENSSL_memdup(pkt->curr, length);
+ if (*data == NULL)
+ return 0;
+
+ *len = length;
+ return 1;
+}
+
+/*
+ * Read a C string from |pkt| and copy to a newly allocated, NUL-terminated
+ * buffer. Store a pointer to the result in |*data|.
+ * If |*data| is not NULL, the old data is OPENSSL_free'd.
+ * If the data in |pkt| does not contain a NUL-byte, the entire data is
+ * copied and NUL-terminated.
+ * Returns 1 if the malloc succeeds and 0 otherwise.
+ * Does not forward PACKET position (because it is typically the last thing done
+ * with a given PACKET).
+ */
+__owur static ossl_inline int PACKET_strndup(const PACKET *pkt, char **data)
+{
+ OPENSSL_free(*data);
+
+ /* This will succeed on an empty packet, unless pkt->curr == NULL. */
+ *data = OPENSSL_strndup((const char *)pkt->curr, PACKET_remaining(pkt));
+ return (*data != NULL);
+}
+
+/* Returns 1 if |pkt| contains at least one 0-byte, 0 otherwise. */
+static ossl_inline int PACKET_contains_zero_byte(const PACKET *pkt)
+{
+ return memchr(pkt->curr, 0, pkt->remaining) != NULL;
+}
+
+/* Move the current reading position forward |len| bytes */
+__owur static ossl_inline int PACKET_forward(PACKET *pkt, size_t len)
+{
+ if (PACKET_remaining(pkt) < len)
+ return 0;
+
+ packet_forward(pkt, len);
+
+ return 1;
+}
+
+/*
+ * Reads a variable-length vector prefixed with a one-byte length, and stores
+ * the contents in |subpkt|. |pkt| can equal |subpkt|.
+ * Data is not copied: the |subpkt| packet will share its underlying buffer with
+ * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|.
+ * Upon failure, the original |pkt| and |subpkt| are not modified.
+ */
+__owur static ossl_inline int PACKET_get_length_prefixed_1(PACKET *pkt,
+ PACKET *subpkt)
+{
+ unsigned int length;
+ const unsigned char *data;
+ PACKET tmp = *pkt;
+ if (!PACKET_get_1(&tmp, &length) ||
+ !PACKET_get_bytes(&tmp, &data, (size_t)length)) {
+ return 0;
+ }
+
+ *pkt = tmp;
+ subpkt->curr = data;
+ subpkt->remaining = length;
+
+ return 1;
+}
+
+/*
+ * Like PACKET_get_length_prefixed_1, but additionally, fails when there are
+ * leftover bytes in |pkt|.
+ */
+__owur static ossl_inline int PACKET_as_length_prefixed_1(PACKET *pkt,
+ PACKET *subpkt)
+{
+ unsigned int length;
+ const unsigned char *data;
+ PACKET tmp = *pkt;
+ if (!PACKET_get_1(&tmp, &length) ||
+ !PACKET_get_bytes(&tmp, &data, (size_t)length) ||
+ PACKET_remaining(&tmp) != 0) {
+ return 0;
+ }
+
+ *pkt = tmp;
+ subpkt->curr = data;
+ subpkt->remaining = length;
+
+ return 1;
+}
+
+/*
+ * Reads a variable-length vector prefixed with a two-byte length, and stores
+ * the contents in |subpkt|. |pkt| can equal |subpkt|.
+ * Data is not copied: the |subpkt| packet will share its underlying buffer with
+ * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|.
+ * Upon failure, the original |pkt| and |subpkt| are not modified.
+ */
+__owur static ossl_inline int PACKET_get_length_prefixed_2(PACKET *pkt,
+ PACKET *subpkt)
+{
+ unsigned int length;
+ const unsigned char *data;
+ PACKET tmp = *pkt;
+
+ if (!PACKET_get_net_2(&tmp, &length) ||
+ !PACKET_get_bytes(&tmp, &data, (size_t)length)) {
+ return 0;
+ }
+
+ *pkt = tmp;
+ subpkt->curr = data;
+ subpkt->remaining = length;
+
+ return 1;
+}
+
+/*
+ * Like PACKET_get_length_prefixed_2, but additionally, fails when there are
+ * leftover bytes in |pkt|.
+ */
+__owur static ossl_inline int PACKET_as_length_prefixed_2(PACKET *pkt,
+ PACKET *subpkt)
+{
+ unsigned int length;
+ const unsigned char *data;
+ PACKET tmp = *pkt;
+
+ if (!PACKET_get_net_2(&tmp, &length) ||
+ !PACKET_get_bytes(&tmp, &data, (size_t)length) ||
+ PACKET_remaining(&tmp) != 0) {
+ return 0;
+ }
+
+ *pkt = tmp;
+ subpkt->curr = data;
+ subpkt->remaining = length;
+
+ return 1;
+}
+
+/*
+ * Reads a variable-length vector prefixed with a three-byte length, and stores
+ * the contents in |subpkt|. |pkt| can equal |subpkt|.
+ * Data is not copied: the |subpkt| packet will share its underlying buffer with
+ * the original |pkt|, so data wrapped by |pkt| must outlive the |subpkt|.
+ * Upon failure, the original |pkt| and |subpkt| are not modified.
+ */
+__owur static ossl_inline int PACKET_get_length_prefixed_3(PACKET *pkt,
+ PACKET *subpkt)
+{
+ unsigned long length;
+ const unsigned char *data;
+ PACKET tmp = *pkt;
+ if (!PACKET_get_net_3(&tmp, &length) ||
+ !PACKET_get_bytes(&tmp, &data, (size_t)length)) {
+ return 0;
+ }
+
+ *pkt = tmp;
+ subpkt->curr = data;
+ subpkt->remaining = length;
+
+ return 1;
+}
+
+/* Writeable packets */
+
+typedef struct wpacket_sub WPACKET_SUB;
+struct wpacket_sub {
+ /* The parent WPACKET_SUB if we have one or NULL otherwise */
+ WPACKET_SUB *parent;
+
+ /*
+ * Offset into the buffer where the length of this WPACKET goes. We use an
+ * offset in case the buffer grows and gets reallocated.
+ */
+ size_t packet_len;
+
+ /* Number of bytes in the packet_len or 0 if we don't write the length */
+ size_t lenbytes;
+
+ /* Number of bytes written to the buf prior to this packet starting */
+ size_t pwritten;
+
+ /* Flags for this sub-packet */
+ unsigned int flags;
+};
+
+typedef struct wpacket_st WPACKET;
+struct wpacket_st {
+ /* The buffer where we store the output data */
+ BUF_MEM *buf;
+
+ /* Fixed sized buffer which can be used as an alternative to buf */
+ unsigned char *staticbuf;
+
+ /*
+ * Offset into the buffer where we are currently writing. We use an offset
+ * in case the buffer grows and gets reallocated.
+ */
+ size_t curr;
+
+ /* Number of bytes written so far */
+ size_t written;
+
+ /* Maximum number of bytes we will allow to be written to this WPACKET */
+ size_t maxsize;
+
+ /* Our sub-packets (always at least one if not finished) */
+ WPACKET_SUB *subs;
+
+ /* Writing from the end first? */
+ unsigned int endfirst : 1;
+};
+
+/* Flags */
+
+/* Default */
+#define WPACKET_FLAGS_NONE 0
+
+/* Error on WPACKET_close() if no data written to the WPACKET */
+#define WPACKET_FLAGS_NON_ZERO_LENGTH 1
+
+/*
+ * Abandon all changes on WPACKET_close() if no data written to the WPACKET,
+ * i.e. this does not write out a zero packet length
+ */
+#define WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH 2
+
+
+/*
+ * Initialise a WPACKET with the buffer in |buf|. The buffer must exist
+ * for the whole time that the WPACKET is being used. Additionally |lenbytes| of
+ * data is preallocated at the start of the buffer to store the length of the
+ * WPACKET once we know it.
+ */
+int WPACKET_init_len(WPACKET *pkt, BUF_MEM *buf, size_t lenbytes);
+
+/*
+ * Same as WPACKET_init_len except there is no preallocation of the WPACKET
+ * length.
+ */
+int WPACKET_init(WPACKET *pkt, BUF_MEM *buf);
+
+/*
+ * Same as WPACKET_init_len except there is no underlying buffer. No data is
+ * ever actually written. We just keep track of how much data would have been
+ * written if a buffer was there.
+ */
+int WPACKET_init_null(WPACKET *pkt, size_t lenbytes);
+
+/*
+ * Same as WPACKET_init_null except we set the WPACKET to assume DER length
+ * encoding for sub-packets.
+ */
+int WPACKET_init_null_der(WPACKET *pkt);
+
+/*
+ * Same as WPACKET_init_len except we do not use a growable BUF_MEM structure.
+ * A fixed buffer of memory |buf| of size |len| is used instead. A failure will
+ * occur if you attempt to write beyond the end of the buffer
+ */
+int WPACKET_init_static_len(WPACKET *pkt, unsigned char *buf, size_t len,
+ size_t lenbytes);
+
+/*
+ * Same as WPACKET_init_static_len except lenbytes is always 0, and we set the
+ * WPACKET to write to the end of the buffer moving towards the start and use
+ * DER length encoding for sub-packets.
+ */
+int WPACKET_init_der(WPACKET *pkt, unsigned char *buf, size_t len);
+
+/*
+ * Set the flags to be applied to the current sub-packet
+ */
+int WPACKET_set_flags(WPACKET *pkt, unsigned int flags);
+
+/*
+ * Closes the most recent sub-packet. It also writes out the length of the
+ * packet to the required location (normally the start of the WPACKET) if
+ * appropriate. The top level WPACKET should be closed using WPACKET_finish()
+ * instead of this function.
+ */
+int WPACKET_close(WPACKET *pkt);
+
+/*
+ * The same as WPACKET_close() but only for the top most WPACKET. Additionally
+ * frees memory resources for this WPACKET.
+ */
+int WPACKET_finish(WPACKET *pkt);
+
+/*
+ * Iterate through all the sub-packets and write out their lengths as if they
+ * were being closed. The lengths will be overwritten with the final lengths
+ * when the sub-packets are eventually closed (which may be different if more
+ * data is added to the WPACKET). This function fails if a sub-packet is of 0
+ * length and WPACKET_FLAGS_ABANDON_ON_ZERO_LENGTH is set.
+ */
+int WPACKET_fill_lengths(WPACKET *pkt);
+
+/*
+ * Initialise a new sub-packet. Additionally |lenbytes| of data is preallocated
+ * at the start of the sub-packet to store its length once we know it. Don't
+ * call this directly. Use the convenience macros below instead.
+ */
+int WPACKET_start_sub_packet_len__(WPACKET *pkt, size_t lenbytes);
+
+/*
+ * Convenience macros for calling WPACKET_start_sub_packet_len with different
+ * lengths
+ */
+#define WPACKET_start_sub_packet_u8(pkt) \
+ WPACKET_start_sub_packet_len__((pkt), 1)
+#define WPACKET_start_sub_packet_u16(pkt) \
+ WPACKET_start_sub_packet_len__((pkt), 2)
+#define WPACKET_start_sub_packet_u24(pkt) \
+ WPACKET_start_sub_packet_len__((pkt), 3)
+#define WPACKET_start_sub_packet_u32(pkt) \
+ WPACKET_start_sub_packet_len__((pkt), 4)
+
+/*
+ * Same as WPACKET_start_sub_packet_len__() except no bytes are pre-allocated
+ * for the sub-packet length.
+ */
+int WPACKET_start_sub_packet(WPACKET *pkt);
+
+/*
+ * Allocate bytes in the WPACKET for the output. This reserves the bytes
+ * and counts them as "written", but doesn't actually do the writing. A pointer
+ * to the allocated bytes is stored in |*allocbytes|. |allocbytes| may be NULL.
+ * WARNING: the allocated bytes must be filled in immediately, without further
+ * WPACKET_* calls. If not then the underlying buffer may be realloc'd and
+ * change its location.
+ */
+int WPACKET_allocate_bytes(WPACKET *pkt, size_t len,
+ unsigned char **allocbytes);
+
+/*
+ * The same as WPACKET_allocate_bytes() except additionally a new sub-packet is
+ * started for the allocated bytes, and then closed immediately afterwards. The
+ * number of length bytes for the sub-packet is in |lenbytes|. Don't call this
+ * directly. Use the convenience macros below instead.
+ */
+int WPACKET_sub_allocate_bytes__(WPACKET *pkt, size_t len,
+ unsigned char **allocbytes, size_t lenbytes);
+
+/*
+ * Convenience macros for calling WPACKET_sub_allocate_bytes with different
+ * lengths
+ */
+#define WPACKET_sub_allocate_bytes_u8(pkt, len, bytes) \
+ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 1)
+#define WPACKET_sub_allocate_bytes_u16(pkt, len, bytes) \
+ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 2)
+#define WPACKET_sub_allocate_bytes_u24(pkt, len, bytes) \
+ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 3)
+#define WPACKET_sub_allocate_bytes_u32(pkt, len, bytes) \
+ WPACKET_sub_allocate_bytes__((pkt), (len), (bytes), 4)
+
+/*
+ * The same as WPACKET_allocate_bytes() except the reserved bytes are not
+ * actually counted as written. Typically this will be for when we don't know
+ * how big arbitrary data is going to be up front, but we do know what the
+ * maximum size will be. If this function is used, then it should be immediately
+ * followed by a WPACKET_allocate_bytes() call before any other WPACKET
+ * functions are called (unless the write to the allocated bytes is abandoned).
+ *
+ * For example: If we are generating a signature, then the size of that
+ * signature may not be known in advance. We can use WPACKET_reserve_bytes() to
+ * handle this:
+ *
+ * if (!WPACKET_sub_reserve_bytes_u16(&pkt, EVP_PKEY_get_size(pkey), &sigbytes1)
+ * || EVP_SignFinal(md_ctx, sigbytes1, &siglen, pkey) <= 0
+ * || !WPACKET_sub_allocate_bytes_u16(&pkt, siglen, &sigbytes2)
+ * || sigbytes1 != sigbytes2)
+ * goto err;
+ */
+int WPACKET_reserve_bytes(WPACKET *pkt, size_t len, unsigned char **allocbytes);
+
+/*
+ * The "reserve_bytes" equivalent of WPACKET_sub_allocate_bytes__()
+ */
+int WPACKET_sub_reserve_bytes__(WPACKET *pkt, size_t len,
+ unsigned char **allocbytes, size_t lenbytes);
+
+/*
+ * Convenience macros for WPACKET_sub_reserve_bytes with different lengths
+ */
+#define WPACKET_sub_reserve_bytes_u8(pkt, len, bytes) \
+ WPACKET_reserve_bytes__((pkt), (len), (bytes), 1)
+#define WPACKET_sub_reserve_bytes_u16(pkt, len, bytes) \
+ WPACKET_sub_reserve_bytes__((pkt), (len), (bytes), 2)
+#define WPACKET_sub_reserve_bytes_u24(pkt, len, bytes) \
+ WPACKET_sub_reserve_bytes__((pkt), (len), (bytes), 3)
+#define WPACKET_sub_reserve_bytes_u32(pkt, len, bytes) \
+ WPACKET_sub_reserve_bytes__((pkt), (len), (bytes), 4)
+
+/*
+ * Write the value stored in |val| into the WPACKET. The value will consume
+ * |bytes| amount of storage. An error will occur if |val| cannot be
+ * accommodated in |bytes| storage, e.g. attempting to write the value 256 into
+ * 1 byte will fail. Don't call this directly. Use the convenience macros below
+ * instead.
+ */
+int WPACKET_put_bytes__(WPACKET *pkt, unsigned int val, size_t bytes);
+
+/*
+ * Convenience macros for calling WPACKET_put_bytes with different
+ * lengths
+ */
+#define WPACKET_put_bytes_u8(pkt, val) \
+ WPACKET_put_bytes__((pkt), (val), 1)
+#define WPACKET_put_bytes_u16(pkt, val) \
+ WPACKET_put_bytes__((pkt), (val), 2)
+#define WPACKET_put_bytes_u24(pkt, val) \
+ WPACKET_put_bytes__((pkt), (val), 3)
+#define WPACKET_put_bytes_u32(pkt, val) \
+ WPACKET_put_bytes__((pkt), (val), 4)
+
+/* Set a maximum size that we will not allow the WPACKET to grow beyond */
+int WPACKET_set_max_size(WPACKET *pkt, size_t maxsize);
+
+/* Copy |len| bytes of data from |*src| into the WPACKET. */
+int WPACKET_memcpy(WPACKET *pkt, const void *src, size_t len);
+
+/* Set |len| bytes of data to |ch| into the WPACKET. */
+int WPACKET_memset(WPACKET *pkt, int ch, size_t len);
+
+/*
+ * Copy |len| bytes of data from |*src| into the WPACKET and prefix with its
+ * length (consuming |lenbytes| of data for the length). Don't call this
+ * directly. Use the convenience macros below instead.
+ */
+int WPACKET_sub_memcpy__(WPACKET *pkt, const void *src, size_t len,
+ size_t lenbytes);
+
+/* Convenience macros for calling WPACKET_sub_memcpy with different lengths */
+#define WPACKET_sub_memcpy_u8(pkt, src, len) \
+ WPACKET_sub_memcpy__((pkt), (src), (len), 1)
+#define WPACKET_sub_memcpy_u16(pkt, src, len) \
+ WPACKET_sub_memcpy__((pkt), (src), (len), 2)
+#define WPACKET_sub_memcpy_u24(pkt, src, len) \
+ WPACKET_sub_memcpy__((pkt), (src), (len), 3)
+#define WPACKET_sub_memcpy_u32(pkt, src, len) \
+ WPACKET_sub_memcpy__((pkt), (src), (len), 4)
+
+/*
+ * Return the total number of bytes written so far to the underlying buffer
+ * including any storage allocated for length bytes
+ */
+int WPACKET_get_total_written(WPACKET *pkt, size_t *written);
+
+/*
+ * Returns the length of the current sub-packet. This excludes any bytes
+ * allocated for the length itself.
+ */
+int WPACKET_get_length(WPACKET *pkt, size_t *len);
+
+/*
+ * Returns a pointer to the current write location, but does not allocate any
+ * bytes.
+ */
+unsigned char *WPACKET_get_curr(WPACKET *pkt);
+
+/* Returns true if the underlying buffer is actually NULL */
+int WPACKET_is_null_buf(WPACKET *pkt);
+
+/* Release resources in a WPACKET if a failure has occurred. */
+void WPACKET_cleanup(WPACKET *pkt);
+
+#endif /* OSSL_INTERNAL_PACKET_H */
diff --git a/include/internal/param_build_set.h b/include/internal/param_build_set.h
new file mode 100644
index 00000000..126211b7
--- /dev/null
+++ b/include/internal/param_build_set.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_PARAM_BUILD_SET_H
+# define OSSL_INTERNAL_PARAM_BUILD_SET_H
+# pragma once
+
+# include <openssl/safestack.h>
+# include <openssl/param_build.h>
+# include "internal/cryptlib.h"
+
+typedef union {
+ OSSL_UNION_ALIGN;
+} OSSL_PARAM_ALIGNED_BLOCK;
+
+# define OSSL_PARAM_ALIGN_SIZE sizeof(OSSL_PARAM_ALIGNED_BLOCK)
+
+size_t ossl_param_bytes_to_blocks(size_t bytes);
+void ossl_param_set_secure_block(OSSL_PARAM *last, void *secure_buffer,
+ size_t secure_buffer_sz);
+
+int ossl_param_build_set_int(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
+ const char *key, int num);
+int ossl_param_build_set_long(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
+ const char *key, long num);
+int ossl_param_build_set_utf8_string(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
+ const char *key, const char *buf);
+int ossl_param_build_set_octet_string(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
+ const char *key,
+ const unsigned char *data,
+ size_t data_len);
+int ossl_param_build_set_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
+ const char *key, const BIGNUM *bn);
+int ossl_param_build_set_bn_pad(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
+ const char *key, const BIGNUM *bn, size_t sz);
+int ossl_param_build_set_multi_key_bn(OSSL_PARAM_BLD *bld, OSSL_PARAM *p,
+ const char *names[],
+ STACK_OF(BIGNUM_const) *stk);
+
+#endif /* OSSL_INTERNAL_PARAM_BUILD_SET_H */
diff --git a/include/internal/passphrase.h b/include/internal/passphrase.h
new file mode 100644
index 00000000..54d997b0
--- /dev/null
+++ b/include/internal/passphrase.h
@@ -0,0 +1,122 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_PASSPHRASE_H
+# define OSSL_INTERNAL_PASSPHRASE_H
+# pragma once
+
+/*
+ * This is a passphrase reader bridge with bells and whistles.
+ *
+ * On one hand, an API may wish to offer all sorts of passphrase callback
+ * possibilities to users, or may have to do so for historical reasons.
+ * On the other hand, that same API may have demands from other interfaces,
+ * notably from the libcrypto <-> provider interface, which uses
+ * OSSL_PASSPHRASE_CALLBACK consistently.
+ *
+ * The structure and functions below are the fundaments for bridging one
+ * passphrase callback form to another.
+ *
+ * In addition, extra features are included (this may be a growing list):
+ *
+ * - password caching. This is to be used by APIs where it's likely
+ * that the same passphrase may be asked for more than once, but the
+ * user shouldn't get prompted more than once. For example, this is
+ * useful for OSSL_DECODER, which may have to use a passphrase while
+ * trying to find out what input it has.
+ */
+
+/*
+ * Structure to hold whatever the calling user may specify. This structure
+ * is intended to be integrated into API specific structures or to be used
+ * as a local on-stack variable type. Therefore, no functions to allocate
+ * or freed it on the heap is offered.
+ */
+struct ossl_passphrase_data_st {
+ enum {
+ is_expl_passphrase = 1, /* Explicit passphrase given by user */
+ is_pem_password, /* pem_password_cb given by user */
+ is_ossl_passphrase, /* OSSL_PASSPHRASE_CALLBACK given by user */
+ is_ui_method /* UI_METHOD given by user */
+ } type;
+ union {
+ struct {
+ char *passphrase_copy;
+ size_t passphrase_len;
+ } expl_passphrase;
+
+ struct {
+ pem_password_cb *password_cb;
+ void *password_cbarg;
+ } pem_password;
+
+ struct {
+ OSSL_PASSPHRASE_CALLBACK *passphrase_cb;
+ void *passphrase_cbarg;
+ } ossl_passphrase;
+
+ struct {
+ const UI_METHOD *ui_method;
+ void *ui_method_data;
+ } ui_method;
+ } _;
+
+ /*-
+ * Flags section
+ */
+
+ /* Set to indicate that caching should be done */
+ unsigned int flag_cache_passphrase:1;
+
+ /*-
+ * Misc section: caches and other
+ */
+
+ char *cached_passphrase;
+ size_t cached_passphrase_len;
+};
+
+/* Structure manipulation */
+
+void ossl_pw_clear_passphrase_data(struct ossl_passphrase_data_st *data);
+void ossl_pw_clear_passphrase_cache(struct ossl_passphrase_data_st *data);
+
+int ossl_pw_set_passphrase(struct ossl_passphrase_data_st *data,
+ const unsigned char *passphrase,
+ size_t passphrase_len);
+int ossl_pw_set_pem_password_cb(struct ossl_passphrase_data_st *data,
+ pem_password_cb *cb, void *cbarg);
+int ossl_pw_set_ossl_passphrase_cb(struct ossl_passphrase_data_st *data,
+ OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg);
+int ossl_pw_set_ui_method(struct ossl_passphrase_data_st *data,
+ const UI_METHOD *ui_method, void *ui_data);
+
+int ossl_pw_enable_passphrase_caching(struct ossl_passphrase_data_st *data);
+int ossl_pw_disable_passphrase_caching(struct ossl_passphrase_data_st *data);
+
+/* Central function for direct calls */
+
+int ossl_pw_get_passphrase(char *pass, size_t pass_size, size_t *pass_len,
+ const OSSL_PARAM params[], int verify,
+ struct ossl_passphrase_data_st *data);
+
+/* Callback functions */
+
+/*
+ * All of these callback expect that the callback argument is a
+ * struct ossl_passphrase_data_st
+ */
+
+pem_password_cb ossl_pw_pem_password;
+pem_password_cb ossl_pw_pvk_password;
+/* One callback for encoding (verification prompt) and one for decoding */
+OSSL_PASSPHRASE_CALLBACK ossl_pw_passphrase_callback_enc;
+OSSL_PASSPHRASE_CALLBACK ossl_pw_passphrase_callback_dec;
+
+#endif
diff --git a/include/internal/property.h b/include/internal/property.h
new file mode 100644
index 00000000..82119745
--- /dev/null
+++ b/include/internal/property.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_PROPERTY_H
+# define OSSL_INTERNAL_PROPERTY_H
+# pragma once
+
+# include "internal/cryptlib.h"
+
+typedef struct ossl_method_store_st OSSL_METHOD_STORE;
+typedef struct ossl_property_list_st OSSL_PROPERTY_LIST;
+
+typedef enum {
+ OSSL_PROPERTY_TYPE_STRING, OSSL_PROPERTY_TYPE_NUMBER,
+ OSSL_PROPERTY_TYPE_VALUE_UNDEFINED
+} OSSL_PROPERTY_TYPE;
+typedef struct ossl_property_definition_st OSSL_PROPERTY_DEFINITION;
+
+/* Initialisation */
+int ossl_property_parse_init(OSSL_LIB_CTX *ctx);
+
+/* Property definition parser */
+OSSL_PROPERTY_LIST *ossl_parse_property(OSSL_LIB_CTX *ctx, const char *defn);
+/* Property query parser */
+OSSL_PROPERTY_LIST *ossl_parse_query(OSSL_LIB_CTX *ctx, const char *s,
+ int create_values);
+/* Property checker of query vs definition */
+int ossl_property_match_count(const OSSL_PROPERTY_LIST *query,
+ const OSSL_PROPERTY_LIST *defn);
+int ossl_property_is_enabled(OSSL_LIB_CTX *ctx, const char *property_name,
+ const OSSL_PROPERTY_LIST *prop_list);
+/* Free a parsed property list */
+void ossl_property_free(OSSL_PROPERTY_LIST *p);
+
+/* Get a property from a property list */
+const OSSL_PROPERTY_DEFINITION *
+ossl_property_find_property(const OSSL_PROPERTY_LIST *list,
+ OSSL_LIB_CTX *libctx, const char *name);
+OSSL_PROPERTY_TYPE ossl_property_get_type(const OSSL_PROPERTY_DEFINITION *prop);
+const char *ossl_property_get_string_value(OSSL_LIB_CTX *libctx,
+ const OSSL_PROPERTY_DEFINITION *prop);
+int64_t ossl_property_get_number_value(const OSSL_PROPERTY_DEFINITION *prop);
+
+
+/* Implementation store functions */
+OSSL_METHOD_STORE *ossl_method_store_new(OSSL_LIB_CTX *ctx);
+void ossl_method_store_free(OSSL_METHOD_STORE *store);
+int ossl_method_store_add(OSSL_METHOD_STORE *store, const OSSL_PROVIDER *prov,
+ int nid, const char *properties, void *method,
+ int (*method_up_ref)(void *),
+ void (*method_destruct)(void *));
+int ossl_method_store_remove(OSSL_METHOD_STORE *store, int nid,
+ const void *method);
+void ossl_method_store_do_all(OSSL_METHOD_STORE *store,
+ void (*fn)(int id, void *method, void *fnarg),
+ void *fnarg);
+int ossl_method_store_fetch(OSSL_METHOD_STORE *store,
+ int nid, const char *prop_query,
+ const OSSL_PROVIDER **prov, void **method);
+
+/* Get the global properties associate with the specified library context */
+OSSL_PROPERTY_LIST **ossl_ctx_global_properties(OSSL_LIB_CTX *ctx,
+ int loadconfig);
+
+/* property query cache functions */
+int ossl_method_store_cache_get(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
+ int nid, const char *prop_query, void **result);
+int ossl_method_store_cache_set(OSSL_METHOD_STORE *store, OSSL_PROVIDER *prov,
+ int nid, const char *prop_query, void *result,
+ int (*method_up_ref)(void *),
+ void (*method_destruct)(void *));
+
+__owur int ossl_method_store_flush_cache(OSSL_METHOD_STORE *store, int all);
+
+/* Merge two property queries together */
+OSSL_PROPERTY_LIST *ossl_property_merge(const OSSL_PROPERTY_LIST *a,
+ const OSSL_PROPERTY_LIST *b);
+
+size_t ossl_property_list_to_string(OSSL_LIB_CTX *ctx,
+ const OSSL_PROPERTY_LIST *list, char *buf,
+ size_t bufsize);
+
+int ossl_global_properties_no_mirrored(OSSL_LIB_CTX *libctx);
+void ossl_global_properties_stop_mirroring(OSSL_LIB_CTX *libctx);
+
+#endif
diff --git a/include/internal/propertyerr.h b/include/internal/propertyerr.h
new file mode 100644
index 00000000..fbee53f1
--- /dev/null
+++ b/include/internal/propertyerr.h
@@ -0,0 +1,43 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_PROPERTYERR_H
+# define OSSL_INTERNAL_PROPERTYERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int ossl_err_load_PROP_strings(void);
+
+/*
+ * PROP reason codes.
+ */
+# define PROP_R_NAME_TOO_LONG 100
+# define PROP_R_NOT_AN_ASCII_CHARACTER 101
+# define PROP_R_NOT_AN_HEXADECIMAL_DIGIT 102
+# define PROP_R_NOT_AN_IDENTIFIER 103
+# define PROP_R_NOT_AN_OCTAL_DIGIT 104
+# define PROP_R_NOT_A_DECIMAL_DIGIT 105
+# define PROP_R_NO_MATCHING_STRING_DELIMITER 106
+# define PROP_R_NO_VALUE 107
+# define PROP_R_PARSE_FAILED 108
+# define PROP_R_STRING_TOO_LONG 109
+# define PROP_R_TRAILING_CHARACTERS 110
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/internal/provider.h b/include/internal/provider.h
new file mode 100644
index 00000000..d09829d0
--- /dev/null
+++ b/include/internal/provider.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_PROVIDER_H
+# define OSSL_INTERNAL_PROVIDER_H
+# pragma once
+
+# include <openssl/core.h>
+# include <openssl/core_dispatch.h>
+# include "internal/dso.h"
+# include "internal/symhacks.h"
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * namespaces:
+ *
+ * ossl_provider_ Provider Object internal API
+ * OSSL_PROVIDER Provider Object
+ */
+
+/* Provider Object finder, constructor and destructor */
+OSSL_PROVIDER *ossl_provider_find(OSSL_LIB_CTX *libctx, const char *name,
+ int noconfig);
+OSSL_PROVIDER *ossl_provider_new(OSSL_LIB_CTX *libctx, const char *name,
+ OSSL_provider_init_fn *init_function,
+ int noconfig);
+int ossl_provider_up_ref(OSSL_PROVIDER *prov);
+void ossl_provider_free(OSSL_PROVIDER *prov);
+
+/* Setters */
+int ossl_provider_set_fallback(OSSL_PROVIDER *prov);
+int ossl_provider_set_module_path(OSSL_PROVIDER *prov, const char *module_path);
+int ossl_provider_add_parameter(OSSL_PROVIDER *prov, const char *name,
+ const char *value);
+
+int ossl_provider_is_child(const OSSL_PROVIDER *prov);
+int ossl_provider_set_child(OSSL_PROVIDER *prov, const OSSL_CORE_HANDLE *handle);
+const OSSL_CORE_HANDLE *ossl_provider_get_parent(OSSL_PROVIDER *prov);
+int ossl_provider_up_ref_parent(OSSL_PROVIDER *prov, int activate);
+int ossl_provider_free_parent(OSSL_PROVIDER *prov, int deactivate);
+int ossl_provider_default_props_update(OSSL_LIB_CTX *libctx, const char *props);
+
+/* Disable fallback loading */
+int ossl_provider_disable_fallback_loading(OSSL_LIB_CTX *libctx);
+
+/*
+ * Activate the Provider
+ * If the Provider is a module, the module will be loaded
+ */
+int ossl_provider_activate(OSSL_PROVIDER *prov, int upcalls, int aschild);
+int ossl_provider_deactivate(OSSL_PROVIDER *prov, int removechildren);
+int ossl_provider_add_to_store(OSSL_PROVIDER *prov, OSSL_PROVIDER **actualprov,
+ int retain_fallbacks);
+
+/* Return pointer to the provider's context */
+void *ossl_provider_ctx(const OSSL_PROVIDER *prov);
+
+/* Iterate over all loaded providers */
+int ossl_provider_doall_activated(OSSL_LIB_CTX *,
+ int (*cb)(OSSL_PROVIDER *provider,
+ void *cbdata),
+ void *cbdata);
+
+/* Getters for other library functions */
+const char *ossl_provider_name(const OSSL_PROVIDER *prov);
+const DSO *ossl_provider_dso(const OSSL_PROVIDER *prov);
+const char *ossl_provider_module_name(const OSSL_PROVIDER *prov);
+const char *ossl_provider_module_path(const OSSL_PROVIDER *prov);
+void *ossl_provider_prov_ctx(const OSSL_PROVIDER *prov);
+const OSSL_DISPATCH *ossl_provider_get0_dispatch(const OSSL_PROVIDER *prov);
+OSSL_LIB_CTX *ossl_provider_libctx(const OSSL_PROVIDER *prov);
+
+/* Thin wrappers around calls to the provider */
+void ossl_provider_teardown(const OSSL_PROVIDER *prov);
+const OSSL_PARAM *ossl_provider_gettable_params(const OSSL_PROVIDER *prov);
+int ossl_provider_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[]);
+int ossl_provider_get_capabilities(const OSSL_PROVIDER *prov,
+ const char *capability,
+ OSSL_CALLBACK *cb,
+ void *arg);
+int ossl_provider_self_test(const OSSL_PROVIDER *prov);
+const OSSL_ALGORITHM *ossl_provider_query_operation(const OSSL_PROVIDER *prov,
+ int operation_id,
+ int *no_cache);
+void ossl_provider_unquery_operation(const OSSL_PROVIDER *prov,
+ int operation_id,
+ const OSSL_ALGORITHM *algs);
+
+/* Cache of bits to see if we already queried an operation */
+int ossl_provider_set_operation_bit(OSSL_PROVIDER *provider, size_t bitnum);
+int ossl_provider_test_operation_bit(OSSL_PROVIDER *provider, size_t bitnum,
+ int *result);
+int ossl_provider_clear_all_operation_bits(OSSL_LIB_CTX *libctx);
+
+/* Configuration */
+void ossl_provider_add_conf_module(void);
+
+/* Child providers */
+int ossl_provider_init_as_child(OSSL_LIB_CTX *ctx,
+ const OSSL_CORE_HANDLE *handle,
+ const OSSL_DISPATCH *in);
+void ossl_provider_deinit_child(OSSL_LIB_CTX *ctx);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/internal/refcount.h b/include/internal/refcount.h
new file mode 100644
index 00000000..7412d62f
--- /dev/null
+++ b/include/internal/refcount.h
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+#ifndef OSSL_INTERNAL_REFCOUNT_H
+# define OSSL_INTERNAL_REFCOUNT_H
+# pragma once
+
+# include <openssl/e_os2.h>
+# include <openssl/trace.h>
+
+# ifndef OPENSSL_DEV_NO_ATOMICS
+# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
+ && !defined(__STDC_NO_ATOMICS__)
+# include <stdatomic.h>
+# define HAVE_C11_ATOMICS
+# endif
+
+# if defined(HAVE_C11_ATOMICS) && defined(ATOMIC_INT_LOCK_FREE) \
+ && ATOMIC_INT_LOCK_FREE > 0
+
+# define HAVE_ATOMICS 1
+
+typedef _Atomic int CRYPTO_REF_COUNT;
+
+static inline int CRYPTO_UP_REF(_Atomic int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = atomic_fetch_add_explicit(val, 1, memory_order_relaxed) + 1;
+ return 1;
+}
+
+/*
+ * Changes to shared structure other than reference counter have to be
+ * serialized. And any kind of serialization implies a release fence. This
+ * means that by the time reference counter is decremented all other
+ * changes are visible on all processors. Hence decrement itself can be
+ * relaxed. In case it hits zero, object will be destructed. Since it's
+ * last use of the object, destructor programmer might reason that access
+ * to mutable members doesn't have to be serialized anymore, which would
+ * otherwise imply an acquire fence. Hence conditional acquire fence...
+ */
+static inline int CRYPTO_DOWN_REF(_Atomic int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = atomic_fetch_sub_explicit(val, 1, memory_order_relaxed) - 1;
+ if (*ret == 0)
+ atomic_thread_fence(memory_order_acquire);
+ return 1;
+}
+
+# elif defined(__GNUC__) && defined(__ATOMIC_RELAXED) && __GCC_ATOMIC_INT_LOCK_FREE > 0
+
+# define HAVE_ATOMICS 1
+
+typedef int CRYPTO_REF_COUNT;
+
+static __inline__ int CRYPTO_UP_REF(int *val, int *ret, ossl_unused void *lock)
+{
+ *ret = __atomic_fetch_add(val, 1, __ATOMIC_RELAXED) + 1;
+ return 1;
+}
+
+static __inline__ int CRYPTO_DOWN_REF(int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = __atomic_fetch_sub(val, 1, __ATOMIC_RELAXED) - 1;
+ if (*ret == 0)
+ __atomic_thread_fence(__ATOMIC_ACQUIRE);
+ return 1;
+}
+# elif defined(__ICL) && defined(_WIN32)
+# define HAVE_ATOMICS 1
+typedef volatile int CRYPTO_REF_COUNT;
+
+static __inline int CRYPTO_UP_REF(volatile int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = _InterlockedExchangeAdd((void *)val, 1) + 1;
+ return 1;
+}
+
+static __inline int CRYPTO_DOWN_REF(volatile int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = _InterlockedExchangeAdd((void *)val, -1) - 1;
+ return 1;
+}
+
+# elif defined(_MSC_VER) && _MSC_VER>=1200
+
+# define HAVE_ATOMICS 1
+
+typedef volatile int CRYPTO_REF_COUNT;
+
+# if (defined(_M_ARM) && _M_ARM>=7 && !defined(_WIN32_WCE)) || defined(_M_ARM64)
+# include <intrin.h>
+# if defined(_M_ARM64) && !defined(_ARM_BARRIER_ISH)
+# define _ARM_BARRIER_ISH _ARM64_BARRIER_ISH
+# endif
+
+static __inline int CRYPTO_UP_REF(volatile int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = _InterlockedExchangeAdd_nf(val, 1) + 1;
+ return 1;
+}
+
+static __inline int CRYPTO_DOWN_REF(volatile int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = _InterlockedExchangeAdd_nf(val, -1) - 1;
+ if (*ret == 0)
+ __dmb(_ARM_BARRIER_ISH);
+ return 1;
+}
+# else
+# if !defined(_WIN32_WCE)
+# pragma intrinsic(_InterlockedExchangeAdd)
+# else
+# if _WIN32_WCE >= 0x600
+ extern long __cdecl _InterlockedExchangeAdd(long volatile*, long);
+# else
+ /* under Windows CE we still have old-style Interlocked* functions */
+ extern long __cdecl InterlockedExchangeAdd(long volatile*, long);
+# define _InterlockedExchangeAdd InterlockedExchangeAdd
+# endif
+# endif
+
+static __inline int CRYPTO_UP_REF(volatile int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = _InterlockedExchangeAdd(val, 1) + 1;
+ return 1;
+}
+
+static __inline int CRYPTO_DOWN_REF(volatile int *val, int *ret,
+ ossl_unused void *lock)
+{
+ *ret = _InterlockedExchangeAdd(val, -1) - 1;
+ return 1;
+}
+# endif
+
+# endif
+# endif /* !OPENSSL_DEV_NO_ATOMICS */
+
+/*
+ * All the refcounting implementations above define HAVE_ATOMICS, so if it's
+ * still undefined here (such as when OPENSSL_DEV_NO_ATOMICS is defined), it
+ * means we need to implement a fallback. This fallback uses locks.
+ */
+# ifndef HAVE_ATOMICS
+
+typedef int CRYPTO_REF_COUNT;
+
+# define CRYPTO_UP_REF(val, ret, lock) CRYPTO_atomic_add(val, 1, ret, lock)
+# define CRYPTO_DOWN_REF(val, ret, lock) CRYPTO_atomic_add(val, -1, ret, lock)
+
+# endif
+
+# if !defined(NDEBUG) && !defined(OPENSSL_NO_STDIO)
+# define REF_ASSERT_ISNT(test) \
+ (void)((test) ? (OPENSSL_die("refcount error", __FILE__, __LINE__), 1) : 0)
+# else
+# define REF_ASSERT_ISNT(i)
+# endif
+
+# define REF_PRINT_EX(text, count, object) \
+ OSSL_TRACE3(REF_COUNT, "%p:%4d:%s\n", (object), (count), (text));
+# define REF_PRINT_COUNT(text, object) \
+ REF_PRINT_EX(text, object->references, (void *)object)
+
+#endif
diff --git a/include/internal/sha3.h b/include/internal/sha3.h
new file mode 100644
index 00000000..80ad86e5
--- /dev/null
+++ b/include/internal/sha3.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/* This header can move into provider when legacy support is removed */
+#ifndef OSSL_INTERNAL_SHA3_H
+# define OSSL_INTERNAL_SHA3_H
+# pragma once
+
+# include <openssl/e_os2.h>
+# include <stddef.h>
+
+# define KECCAK1600_WIDTH 1600
+# define SHA3_MDSIZE(bitlen) (bitlen / 8)
+# define KMAC_MDSIZE(bitlen) 2 * (bitlen / 8)
+# define SHA3_BLOCKSIZE(bitlen) (KECCAK1600_WIDTH - bitlen * 2) / 8
+
+typedef struct keccak_st KECCAK1600_CTX;
+
+typedef size_t (sha3_absorb_fn)(void *vctx, const void *inp, size_t len);
+typedef int (sha3_final_fn)(unsigned char *md, void *vctx);
+
+typedef struct prov_sha3_meth_st
+{
+ sha3_absorb_fn *absorb;
+ sha3_final_fn *final;
+} PROV_SHA3_METHOD;
+
+struct keccak_st {
+ uint64_t A[5][5];
+ size_t block_size; /* cached ctx->digest->block_size */
+ size_t md_size; /* output length, variable in XOF */
+ size_t bufsz; /* used bytes in below buffer */
+ unsigned char buf[KECCAK1600_WIDTH / 8 - 32];
+ unsigned char pad;
+ PROV_SHA3_METHOD meth;
+};
+
+void ossl_sha3_reset(KECCAK1600_CTX *ctx);
+int ossl_sha3_init(KECCAK1600_CTX *ctx, unsigned char pad, size_t bitlen);
+int ossl_keccak_kmac_init(KECCAK1600_CTX *ctx, unsigned char pad,
+ size_t bitlen);
+int ossl_sha3_update(KECCAK1600_CTX *ctx, const void *_inp, size_t len);
+int ossl_sha3_final(unsigned char *md, KECCAK1600_CTX *ctx);
+
+size_t SHA3_absorb(uint64_t A[5][5], const unsigned char *inp, size_t len,
+ size_t r);
+
+#endif /* OSSL_INTERNAL_SHA3_H */
diff --git a/include/internal/sizes.h b/include/internal/sizes.h
new file mode 100644
index 00000000..f6496c81
--- /dev/null
+++ b/include/internal/sizes.h
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_SIZES_H
+# define OSSL_INTERNAL_SIZES_H
+# pragma once
+
+/*
+ * Max sizes used to allocate buffers with a fixed sizes, for example for
+ * stack allocations, structure fields, ...
+ */
+# define OSSL_MAX_NAME_SIZE 50 /* Algorithm name */
+# define OSSL_MAX_PROPQUERY_SIZE 256 /* Property query strings */
+# define OSSL_MAX_ALGORITHM_ID_SIZE 256 /* AlgorithmIdentifier DER */
+
+#endif
diff --git a/include/internal/sm3.h b/include/internal/sm3.h
new file mode 100644
index 00000000..db1d61f0
--- /dev/null
+++ b/include/internal/sm3.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright 2017 Ribose Inc. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/* This header can move into provider when legacy support is removed */
+#ifndef OSSL_INTERNAL_SM3_H
+# define OSSL_INTERNAL_SM3_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# ifdef OPENSSL_NO_SM3
+# error SM3 is disabled.
+# endif
+
+# define SM3_DIGEST_LENGTH 32
+# define SM3_WORD unsigned int
+
+# define SM3_CBLOCK 64
+# define SM3_LBLOCK (SM3_CBLOCK/4)
+
+typedef struct SM3state_st {
+ SM3_WORD A, B, C, D, E, F, G, H;
+ SM3_WORD Nl, Nh;
+ SM3_WORD data[SM3_LBLOCK];
+ unsigned int num;
+} SM3_CTX;
+
+int ossl_sm3_init(SM3_CTX *c);
+int ossl_sm3_update(SM3_CTX *c, const void *data, size_t len);
+int ossl_sm3_final(unsigned char *md, SM3_CTX *c);
+
+#endif /* OSSL_INTERNAL_SM3_H */
diff --git a/include/internal/sockets.h b/include/internal/sockets.h
new file mode 100644
index 00000000..6e882fa6
--- /dev/null
+++ b/include/internal/sockets.h
@@ -0,0 +1,175 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_SOCKETS_H
+# define OSSL_INTERNAL_SOCKETS_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# if defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI)
+# define NO_SYS_PARAM_H
+# endif
+# ifdef WIN32
+# define NO_SYS_UN_H
+# endif
+# ifdef OPENSSL_SYS_VMS
+# define NO_SYS_PARAM_H
+# define NO_SYS_UN_H
+# endif
+
+# ifdef OPENSSL_NO_SOCK
+
+# elif defined(OPENSSL_SYS_WINDOWS) || defined(OPENSSL_SYS_MSDOS)
+# if defined(__DJGPP__)
+# include <sys/socket.h>
+# include <sys/un.h>
+# include <tcp.h>
+# include <netdb.h>
+# elif defined(_WIN32_WCE) && _WIN32_WCE<410
+# define getservbyname _masked_declaration_getservbyname
+# endif
+# if !defined(IPPROTO_IP)
+ /* winsock[2].h was included already? */
+# include <winsock.h>
+# endif
+# ifdef getservbyname
+ /* this is used to be wcecompat/include/winsock_extras.h */
+# undef getservbyname
+struct servent *PASCAL getservbyname(const char *, const char *);
+# endif
+
+# ifdef _WIN64
+/*
+ * Even though sizeof(SOCKET) is 8, it's safe to cast it to int, because
+ * the value constitutes an index in per-process table of limited size
+ * and not a real pointer. And we also depend on fact that all processors
+ * Windows run on happen to be two's-complement, which allows to
+ * interchange INVALID_SOCKET and -1.
+ */
+# define socket(d,t,p) ((int)socket(d,t,p))
+# define accept(s,f,l) ((int)accept(s,f,l))
+# endif
+
+# else
+
+# ifndef NO_SYS_PARAM_H
+# include <sys/param.h>
+# endif
+# ifdef OPENSSL_SYS_VXWORKS
+# include <time.h>
+# endif
+
+# include <netdb.h>
+# if defined(OPENSSL_SYS_VMS_NODECC)
+# include <socket.h>
+# include <in.h>
+# include <inet.h>
+# else
+# include <sys/socket.h>
+# ifndef NO_SYS_UN_H
+# include <sys/un.h>
+# ifndef UNIX_PATH_MAX
+# define UNIX_PATH_MAX sizeof(((struct sockaddr_un *)NULL)->sun_path)
+# endif
+# endif
+# ifdef FILIO_H
+# include <sys/filio.h> /* FIONBIO in some SVR4, e.g. unixware, solaris */
+# endif
+# include <netinet/in.h>
+# include <arpa/inet.h>
+# include <netinet/tcp.h>
+# endif
+
+# ifdef OPENSSL_SYS_AIX
+# include <sys/select.h>
+# endif
+
+# ifndef VMS
+# include <sys/ioctl.h>
+# else
+# if !defined(TCPIP_TYPE_SOCKETSHR) && defined(__VMS_VER) && (__VMS_VER > 70000000)
+ /* ioctl is only in VMS > 7.0 and when socketshr is not used */
+# include <sys/ioctl.h>
+# endif
+# include <unixio.h>
+# if defined(TCPIP_TYPE_SOCKETSHR)
+# include <socketshr.h>
+# endif
+# endif
+
+# ifndef INVALID_SOCKET
+# define INVALID_SOCKET (-1)
+# endif
+# endif
+
+/*
+ * Some IPv6 implementations are broken, you can disable them in known
+ * bad versions.
+ */
+# if !defined(OPENSSL_USE_IPV6)
+# if defined(AF_INET6)
+# define OPENSSL_USE_IPV6 1
+# else
+# define OPENSSL_USE_IPV6 0
+# endif
+# endif
+
+# define get_last_socket_error() errno
+# define clear_socket_error() errno=0
+
+# if defined(OPENSSL_SYS_WINDOWS)
+# undef get_last_socket_error
+# undef clear_socket_error
+# define get_last_socket_error() WSAGetLastError()
+# define clear_socket_error() WSASetLastError(0)
+# define readsocket(s,b,n) recv((s),(b),(n),0)
+# define writesocket(s,b,n) send((s),(b),(n),0)
+# elif defined(__DJGPP__)
+# define WATT32
+# define WATT32_NO_OLDIES
+# define closesocket(s) close_s(s)
+# define readsocket(s,b,n) read_s(s,b,n)
+# define writesocket(s,b,n) send(s,b,n,0)
+# elif defined(OPENSSL_SYS_VMS)
+# define ioctlsocket(a,b,c) ioctl(a,b,c)
+# define closesocket(s) close(s)
+# define readsocket(s,b,n) recv((s),(b),(n),0)
+# define writesocket(s,b,n) send((s),(b),(n),0)
+# elif defined(OPENSSL_SYS_VXWORKS)
+# define ioctlsocket(a,b,c) ioctl((a),(b),(int)(c))
+# define closesocket(s) close(s)
+# define readsocket(s,b,n) read((s),(b),(n))
+# define writesocket(s,b,n) write((s),(char *)(b),(n))
+# elif defined(OPENSSL_SYS_TANDEM)
+# if defined(OPENSSL_TANDEM_FLOSS)
+# include <floss.h(floss_read, floss_write)>
+# define readsocket(s,b,n) floss_read((s),(b),(n))
+# define writesocket(s,b,n) floss_write((s),(b),(n))
+# else
+# define readsocket(s,b,n) read((s),(b),(n))
+# define writesocket(s,b,n) write((s),(b),(n))
+# endif
+# define ioctlsocket(a,b,c) ioctl(a,b,c)
+# define closesocket(s) close(s)
+# else
+# define ioctlsocket(a,b,c) ioctl(a,b,c)
+# define closesocket(s) close(s)
+# define readsocket(s,b,n) read((s),(b),(n))
+# define writesocket(s,b,n) write((s),(b),(n))
+# endif
+
+/* also in apps/include/apps.h */
+# if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WINCE)
+# define openssl_fdset(a, b) FD_SET((unsigned int)(a), b)
+# else
+# define openssl_fdset(a, b) FD_SET(a, b)
+# endif
+
+#endif
diff --git a/include/internal/sslconf.h b/include/internal/sslconf.h
new file mode 100644
index 00000000..fd7f7e33
--- /dev/null
+++ b/include/internal/sslconf.h
@@ -0,0 +1,21 @@
+/*
+ * Copyright 2018-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_SSLCONF_H
+# define OSSL_INTERNAL_SSLCONF_H
+# pragma once
+
+typedef struct ssl_conf_cmd_st SSL_CONF_CMD;
+
+const SSL_CONF_CMD *conf_ssl_get(size_t idx, const char **name, size_t *cnt);
+int conf_ssl_name_find(const char *name, size_t *idx);
+void conf_ssl_get_cmd(const SSL_CONF_CMD *cmd, size_t idx, char **cmdstr,
+ char **arg);
+
+#endif
diff --git a/include/internal/symhacks.h b/include/internal/symhacks.h
new file mode 100644
index 00000000..33bae51e
--- /dev/null
+++ b/include/internal/symhacks.h
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_SYMHACKS_H
+# define OSSL_INTERNAL_SYMHACKS_H
+# pragma once
+
+# include <openssl/e_os2.h>
+
+# if defined(OPENSSL_SYS_VMS)
+
+/* ossl_provider_gettable_params vs OSSL_PROVIDER_gettable_params */
+# undef ossl_provider_gettable_params
+# define ossl_provider_gettable_params ossl_int_prov_gettable_params
+/* ossl_provider_get_params vs OSSL_PROVIDER_get_params */
+# undef ossl_provider_get_params
+# define ossl_provider_get_params ossl_int_prov_get_params
+
+# endif
+
+#endif /* ! defined HEADER_VMS_IDHACKS_H */
diff --git a/include/internal/thread_once.h b/include/internal/thread_once.h
new file mode 100644
index 00000000..d6cb2eee
--- /dev/null
+++ b/include/internal/thread_once.h
@@ -0,0 +1,151 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_THREAD_ONCE_H
+# define OSSL_INTERNAL_THREAD_ONCE_H
+# pragma once
+
+# include <openssl/crypto.h>
+
+/*
+ * Initialisation of global data should never happen via "RUN_ONCE" inside the
+ * FIPS module. Global data should instead always be associated with a specific
+ * OSSL_LIB_CTX object. In this way data will get cleaned up correctly when the
+ * module gets unloaded.
+ */
+# if !defined(FIPS_MODULE) || defined(ALLOW_RUN_ONCE_IN_FIPS)
+/*
+ * DEFINE_RUN_ONCE: Define an initialiser function that should be run exactly
+ * once. It takes no arguments and returns an int result (1 for success or
+ * 0 for failure). Typical usage might be:
+ *
+ * DEFINE_RUN_ONCE(myinitfunc)
+ * {
+ * do_some_initialisation();
+ * if (init_is_successful())
+ * return 1;
+ *
+ * return 0;
+ * }
+ */
+# define DEFINE_RUN_ONCE(init) \
+ static int init(void); \
+ int init##_ossl_ret_ = 0; \
+ void init##_ossl_(void) \
+ { \
+ init##_ossl_ret_ = init(); \
+ } \
+ static int init(void)
+
+/*
+ * DECLARE_RUN_ONCE: Declare an initialiser function that should be run exactly
+ * once that has been defined in another file via DEFINE_RUN_ONCE().
+ */
+# define DECLARE_RUN_ONCE(init) \
+ extern int init##_ossl_ret_; \
+ void init##_ossl_(void);
+
+/*
+ * DEFINE_RUN_ONCE_STATIC: Define an initialiser function that should be run
+ * exactly once. This function will be declared as static within the file. It
+ * takes no arguments and returns an int result (1 for success or 0 for
+ * failure). Typical usage might be:
+ *
+ * DEFINE_RUN_ONCE_STATIC(myinitfunc)
+ * {
+ * do_some_initialisation();
+ * if (init_is_successful())
+ * return 1;
+ *
+ * return 0;
+ * }
+ */
+# define DEFINE_RUN_ONCE_STATIC(init) \
+ static int init(void); \
+ static int init##_ossl_ret_ = 0; \
+ static void init##_ossl_(void) \
+ { \
+ init##_ossl_ret_ = init(); \
+ } \
+ static int init(void)
+
+/*
+ * DEFINE_RUN_ONCE_STATIC_ALT: Define an alternative initialiser function. This
+ * function will be declared as static within the file. It takes no arguments
+ * and returns an int result (1 for success or 0 for failure). An alternative
+ * initialiser function is expected to be associated with a primary initialiser
+ * function defined via DEFINE_ONCE_STATIC where both functions use the same
+ * CRYPTO_ONCE object to synchronise. Where an alternative initialiser function
+ * is used only one of the primary or the alternative initialiser function will
+ * ever be called - and that function will be called exactly once. Definition
+ * of an alternative initialiser function MUST occur AFTER the definition of the
+ * primary initialiser function.
+ *
+ * Typical usage might be:
+ *
+ * DEFINE_RUN_ONCE_STATIC(myinitfunc)
+ * {
+ * do_some_initialisation();
+ * if (init_is_successful())
+ * return 1;
+ *
+ * return 0;
+ * }
+ *
+ * DEFINE_RUN_ONCE_STATIC_ALT(myaltinitfunc, myinitfunc)
+ * {
+ * do_some_alternative_initialisation();
+ * if (init_is_successful())
+ * return 1;
+ *
+ * return 0;
+ * }
+ */
+# define DEFINE_RUN_ONCE_STATIC_ALT(initalt, init) \
+ static int initalt(void); \
+ static void initalt##_ossl_(void) \
+ { \
+ init##_ossl_ret_ = initalt(); \
+ } \
+ static int initalt(void)
+
+/*
+ * RUN_ONCE - use CRYPTO_THREAD_run_once, and check if the init succeeded
+ * @once: pointer to static object of type CRYPTO_ONCE
+ * @init: function name that was previously given to DEFINE_RUN_ONCE,
+ * DEFINE_RUN_ONCE_STATIC or DECLARE_RUN_ONCE. This function
+ * must return 1 for success or 0 for failure.
+ *
+ * The return value is 1 on success (*) or 0 in case of error.
+ *
+ * (*) by convention, since the init function must return 1 on success.
+ */
+# define RUN_ONCE(once, init) \
+ (CRYPTO_THREAD_run_once(once, init##_ossl_) ? init##_ossl_ret_ : 0)
+
+/*
+ * RUN_ONCE_ALT - use CRYPTO_THREAD_run_once, to run an alternative initialiser
+ * function and check if that initialisation succeeded
+ * @once: pointer to static object of type CRYPTO_ONCE
+ * @initalt: alternative initialiser function name that was previously given to
+ * DEFINE_RUN_ONCE_STATIC_ALT. This function must return 1 for
+ * success or 0 for failure.
+ * @init: primary initialiser function name that was previously given to
+ * DEFINE_RUN_ONCE_STATIC. This function must return 1 for success or
+ * 0 for failure.
+ *
+ * The return value is 1 on success (*) or 0 in case of error.
+ *
+ * (*) by convention, since the init function must return 1 on success.
+ */
+# define RUN_ONCE_ALT(once, initalt, init) \
+ (CRYPTO_THREAD_run_once(once, initalt##_ossl_) ? init##_ossl_ret_ : 0)
+
+# endif /* FIPS_MODULE */
+#endif /* OSSL_INTERNAL_THREAD_ONCE_H */
diff --git a/include/internal/tlsgroups.h b/include/internal/tlsgroups.h
new file mode 100644
index 00000000..8a35ced1
--- /dev/null
+++ b/include/internal/tlsgroups.h
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2017-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_TLSGROUPS_H
+# define OSSL_INTERNAL_TLSGROUPS_H
+# pragma once
+
+# define OSSL_TLS_GROUP_ID_sect163k1 0x0001
+# define OSSL_TLS_GROUP_ID_sect163r1 0x0002
+# define OSSL_TLS_GROUP_ID_sect163r2 0x0003
+# define OSSL_TLS_GROUP_ID_sect193r1 0x0004
+# define OSSL_TLS_GROUP_ID_sect193r2 0x0005
+# define OSSL_TLS_GROUP_ID_sect233k1 0x0006
+# define OSSL_TLS_GROUP_ID_sect233r1 0x0007
+# define OSSL_TLS_GROUP_ID_sect239k1 0x0008
+# define OSSL_TLS_GROUP_ID_sect283k1 0x0009
+# define OSSL_TLS_GROUP_ID_sect283r1 0x000A
+# define OSSL_TLS_GROUP_ID_sect409k1 0x000B
+# define OSSL_TLS_GROUP_ID_sect409r1 0x000C
+# define OSSL_TLS_GROUP_ID_sect571k1 0x000D
+# define OSSL_TLS_GROUP_ID_sect571r1 0x000E
+# define OSSL_TLS_GROUP_ID_secp160k1 0x000F
+# define OSSL_TLS_GROUP_ID_secp160r1 0x0010
+# define OSSL_TLS_GROUP_ID_secp160r2 0x0011
+# define OSSL_TLS_GROUP_ID_secp192k1 0x0012
+# define OSSL_TLS_GROUP_ID_secp192r1 0x0013
+# define OSSL_TLS_GROUP_ID_secp224k1 0x0014
+# define OSSL_TLS_GROUP_ID_secp224r1 0x0015
+# define OSSL_TLS_GROUP_ID_secp256k1 0x0016
+# define OSSL_TLS_GROUP_ID_secp256r1 0x0017
+# define OSSL_TLS_GROUP_ID_secp384r1 0x0018
+# define OSSL_TLS_GROUP_ID_secp521r1 0x0019
+# define OSSL_TLS_GROUP_ID_brainpoolP256r1 0x001A
+# define OSSL_TLS_GROUP_ID_brainpoolP384r1 0x001B
+# define OSSL_TLS_GROUP_ID_brainpoolP512r1 0x001C
+# define OSSL_TLS_GROUP_ID_x25519 0x001D
+# define OSSL_TLS_GROUP_ID_x448 0x001E
+# define OSSL_TLS_GROUP_ID_ffdhe2048 0x0100
+# define OSSL_TLS_GROUP_ID_ffdhe3072 0x0101
+# define OSSL_TLS_GROUP_ID_ffdhe4096 0x0102
+# define OSSL_TLS_GROUP_ID_ffdhe6144 0x0103
+# define OSSL_TLS_GROUP_ID_ffdhe8192 0x0104
+
+#endif
diff --git a/include/internal/tsan_assist.h b/include/internal/tsan_assist.h
new file mode 100644
index 00000000..f8285b1d
--- /dev/null
+++ b/include/internal/tsan_assist.h
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * Contemporary compilers implement lock-free atomic memory access
+ * primitives that facilitate writing "thread-opportunistic" or even real
+ * multi-threading low-overhead code. "Thread-opportunistic" is when
+ * exact result is not required, e.g. some statistics, or execution flow
+ * doesn't have to be unambiguous. Simplest example is lazy "constant"
+ * initialization when one can synchronize on variable itself, e.g.
+ *
+ * if (var == NOT_YET_INITIALIZED)
+ * var = function_returning_same_value();
+ *
+ * This does work provided that loads and stores are single-instruction
+ * operations (and integer ones are on *all* supported platforms), but
+ * it upsets Thread Sanitizer. Suggested solution is
+ *
+ * if (tsan_load(&var) == NOT_YET_INITIALIZED)
+ * tsan_store(&var, function_returning_same_value());
+ *
+ * Production machine code would be the same, so one can wonder why
+ * bother. Having Thread Sanitizer accept "thread-opportunistic" code
+ * allows to move on trouble-shooting real bugs.
+ *
+ * Resolving Thread Sanitizer nits was the initial purpose for this module,
+ * but it was later extended with more nuanced primitives that are useful
+ * even in "non-opportunistic" scenarios. Most notably verifying if a shared
+ * structure is fully initialized and bypassing the initialization lock.
+ * It's suggested to view macros defined in this module as "annotations" for
+ * thread-safe lock-free code, "Thread-Safe ANnotations"...
+ *
+ * It's assumed that ATOMIC_{LONG|INT}_LOCK_FREE are assigned same value as
+ * ATOMIC_POINTER_LOCK_FREE. And check for >= 2 ensures that corresponding
+ * code is inlined. It should be noted that statistics counters become
+ * accurate in such case.
+ *
+ * Special note about TSAN_QUALIFIER. It might be undesired to use it in
+ * a shared header. Because whether operation on specific variable or member
+ * is atomic or not might be irrelevant in other modules. In such case one
+ * can use TSAN_QUALIFIER in cast specifically when it has to count.
+ */
+
+#if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L \
+ && !defined(__STDC_NO_ATOMICS__)
+# include <stdatomic.h>
+
+# if defined(ATOMIC_POINTER_LOCK_FREE) \
+ && ATOMIC_POINTER_LOCK_FREE >= 2
+# define TSAN_QUALIFIER _Atomic
+# define tsan_load(ptr) atomic_load_explicit((ptr), memory_order_relaxed)
+# define tsan_store(ptr, val) atomic_store_explicit((ptr), (val), memory_order_relaxed)
+# define tsan_counter(ptr) atomic_fetch_add_explicit((ptr), 1, memory_order_relaxed)
+# define tsan_decr(ptr) atomic_fetch_add_explicit((ptr), -1, memory_order_relaxed)
+# define tsan_ld_acq(ptr) atomic_load_explicit((ptr), memory_order_acquire)
+# define tsan_st_rel(ptr, val) atomic_store_explicit((ptr), (val), memory_order_release)
+# endif
+
+#elif defined(__GNUC__) && defined(__ATOMIC_RELAXED)
+
+# if defined(__GCC_ATOMIC_POINTER_LOCK_FREE) \
+ && __GCC_ATOMIC_POINTER_LOCK_FREE >= 2
+# define TSAN_QUALIFIER volatile
+# define tsan_load(ptr) __atomic_load_n((ptr), __ATOMIC_RELAXED)
+# define tsan_store(ptr, val) __atomic_store_n((ptr), (val), __ATOMIC_RELAXED)
+# define tsan_counter(ptr) __atomic_fetch_add((ptr), 1, __ATOMIC_RELAXED)
+# define tsan_decr(ptr) __atomic_fetch_add((ptr), -1, __ATOMIC_RELAXED)
+# define tsan_ld_acq(ptr) __atomic_load_n((ptr), __ATOMIC_ACQUIRE)
+# define tsan_st_rel(ptr, val) __atomic_store_n((ptr), (val), __ATOMIC_RELEASE)
+# endif
+
+#elif defined(_MSC_VER) && _MSC_VER>=1200 \
+ && (defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64) || \
+ defined(_M_ARM64) || (defined(_M_ARM) && _M_ARM >= 7 && !defined(_WIN32_WCE)))
+/*
+ * There is subtle dependency on /volatile:<iso|ms> command-line option.
+ * "ms" implies same semantic as memory_order_acquire for loads and
+ * memory_order_release for stores, while "iso" - memory_order_relaxed for
+ * either. Real complication is that defaults are different on x86 and ARM.
+ * There is explanation for that, "ms" is backward compatible with earlier
+ * compiler versions, while multi-processor ARM can be viewed as brand new
+ * platform to MSC and its users, and with non-relaxed semantic taking toll
+ * with additional instructions and penalties, it kind of makes sense to
+ * default to "iso"...
+ */
+# define TSAN_QUALIFIER volatile
+# if defined(_M_ARM) || defined(_M_ARM64)
+# define _InterlockedExchangeAdd _InterlockedExchangeAdd_nf
+# pragma intrinsic(_InterlockedExchangeAdd_nf)
+# pragma intrinsic(__iso_volatile_load32, __iso_volatile_store32)
+# ifdef _WIN64
+# define _InterlockedExchangeAdd64 _InterlockedExchangeAdd64_nf
+# pragma intrinsic(_InterlockedExchangeAdd64_nf)
+# pragma intrinsic(__iso_volatile_load64, __iso_volatile_store64)
+# define tsan_load(ptr) (sizeof(*(ptr)) == 8 ? __iso_volatile_load64(ptr) \
+ : __iso_volatile_load32(ptr))
+# define tsan_store(ptr, val) (sizeof(*(ptr)) == 8 ? __iso_volatile_store64((ptr), (val)) \
+ : __iso_volatile_store32((ptr), (val)))
+# else
+# define tsan_load(ptr) __iso_volatile_load32(ptr)
+# define tsan_store(ptr, val) __iso_volatile_store32((ptr), (val))
+# endif
+# else
+# define tsan_load(ptr) (*(ptr))
+# define tsan_store(ptr, val) (*(ptr) = (val))
+# endif
+# pragma intrinsic(_InterlockedExchangeAdd)
+# ifdef _WIN64
+# pragma intrinsic(_InterlockedExchangeAdd64)
+# define tsan_counter(ptr) (sizeof(*(ptr)) == 8 ? _InterlockedExchangeAdd64((ptr), 1) \
+ : _InterlockedExchangeAdd((ptr), 1))
+# define tsan_decr(ptr) (sizeof(*(ptr)) == 8 ? _InterlockedExchangeAdd64((ptr), -1) \
+ : _InterlockedExchangeAdd((ptr), -1))
+# else
+# define tsan_counter(ptr) _InterlockedExchangeAdd((ptr), 1)
+# define tsan_decr(ptr) _InterlockedExchangeAdd((ptr), -1)
+# endif
+# if !defined(_ISO_VOLATILE)
+# define tsan_ld_acq(ptr) (*(ptr))
+# define tsan_st_rel(ptr, val) (*(ptr) = (val))
+# endif
+
+#endif
+
+#ifndef TSAN_QUALIFIER
+
+# define TSAN_QUALIFIER volatile
+# define tsan_load(ptr) (*(ptr))
+# define tsan_store(ptr, val) (*(ptr) = (val))
+# define tsan_counter(ptr) ((*(ptr))++)
+# define tsan_decr(ptr) ((*(ptr))--)
+/*
+ * Lack of tsan_ld_acq and tsan_ld_rel means that compiler support is not
+ * sophisticated enough to support them. Code that relies on them should be
+ * protected with #ifdef tsan_ld_acq with locked fallback.
+ */
+
+#endif
diff --git a/include/internal/unicode.h b/include/internal/unicode.h
new file mode 100644
index 00000000..a6de8352
--- /dev/null
+++ b/include/internal/unicode.h
@@ -0,0 +1,31 @@
+/*
+ * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OSSL_INTERNAL_UNICODE_H
+# define OSSL_INTERNAL_UNICODE_H
+# pragma once
+
+typedef enum {
+ SURROGATE_MIN = 0xd800UL,
+ SURROGATE_MAX = 0xdfffUL,
+ UNICODE_MAX = 0x10ffffUL,
+ UNICODE_LIMIT
+} UNICODE_CONSTANTS;
+
+static ossl_unused ossl_inline int is_unicode_surrogate(unsigned long value)
+{
+ return value >= SURROGATE_MIN && value <= SURROGATE_MAX;
+}
+
+static ossl_unused ossl_inline int is_unicode_valid(unsigned long value)
+{
+ return value <= UNICODE_MAX && !is_unicode_surrogate(value);
+}
+
+#endif
diff --git a/include/libcrypto_static.lib b/include/libcrypto_static.lib
new file mode 100644
index 00000000..0ddd830c
--- /dev/null
+++ b/include/libcrypto_static.lib
Binary files differ
diff --git a/include/libcurl/include/curl/curl.h b/include/libcurl/include/curl/curl.h
new file mode 100644
index 00000000..7b69ce2d
--- /dev/null
+++ b/include/libcurl/include/curl/curl.h
@@ -0,0 +1,3103 @@
+#ifndef CURLINC_CURL_H
+#define CURLINC_CURL_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * If you have libcurl problems, all docs and details are found here:
+ * https://curl.se/libcurl/
+ */
+
+#ifdef CURL_NO_OLDIES
+#define CURL_STRICTER
+#endif
+
+#include "curlver.h" /* libcurl version defines */
+#include "system.h" /* determine things run-time */
+
+/*
+ * Define CURL_WIN32 when build target is Win32 API
+ */
+
+#if (defined(_WIN32) || defined(__WIN32__) || defined(WIN32)) && \
+ !defined(__SYMBIAN32__)
+#define CURL_WIN32
+#endif
+
+#include <stdio.h>
+#include <limits.h>
+
+#if (defined(__FreeBSD__) && (__FreeBSD__ >= 2)) || defined(__MidnightBSD__)
+/* Needed for __FreeBSD_version or __MidnightBSD_version symbol definition */
+#include <osreldate.h>
+#endif
+
+/* The include stuff here below is mainly for time_t! */
+#include <sys/types.h>
+#include <time.h>
+
+#if defined(CURL_WIN32) && !defined(_WIN32_WCE) && !defined(__CYGWIN__)
+#if !(defined(_WINSOCKAPI_) || defined(_WINSOCK_H) || \
+ defined(__LWIP_OPT_H__) || defined(LWIP_HDR_OPT_H))
+/* The check above prevents the winsock2 inclusion if winsock.h already was
+ included, since they can't co-exist without problems */
+#include <winsock2.h>
+#include <ws2tcpip.h>
+#endif
+#endif
+
+/* HP-UX systems version 9, 10 and 11 lack sys/select.h and so does oldish
+ libc5-based Linux systems. Only include it on systems that are known to
+ require it! */
+#if defined(_AIX) || defined(__NOVELL_LIBC__) || defined(__NetBSD__) || \
+ defined(__minix) || defined(__SYMBIAN32__) || defined(__INTEGRITY) || \
+ defined(ANDROID) || defined(__ANDROID__) || defined(__OpenBSD__) || \
+ defined(__CYGWIN__) || defined(AMIGA) || defined(__NuttX__) || \
+ (defined(__FreeBSD_version) && (__FreeBSD_version < 800000)) || \
+ (defined(__MidnightBSD_version) && (__MidnightBSD_version < 100000)) || \
+ defined(__VXWORKS__)
+#include <sys/select.h>
+#endif
+
+#if !defined(CURL_WIN32) && !defined(_WIN32_WCE)
+#include <sys/socket.h>
+#endif
+
+#if !defined(CURL_WIN32) && !defined(__WATCOMC__) && !defined(__VXWORKS__)
+#include <sys/time.h>
+#endif
+
+#ifdef __BEOS__
+#include <support/SupportDefs.h>
+#endif
+
+/* Compatibility for non-Clang compilers */
+#ifndef __has_declspec_attribute
+# define __has_declspec_attribute(x) 0
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER)
+typedef struct Curl_easy CURL;
+typedef struct Curl_share CURLSH;
+#else
+typedef void CURL;
+typedef void CURLSH;
+#endif
+
+/*
+ * libcurl external API function linkage decorations.
+ */
+
+#ifdef CURL_STATICLIB
+# define CURL_EXTERN
+#elif defined(CURL_WIN32) || defined(__SYMBIAN32__) || \
+ (__has_declspec_attribute(dllexport) && \
+ __has_declspec_attribute(dllimport))
+# if defined(BUILDING_LIBCURL)
+# define CURL_EXTERN __declspec(dllexport)
+# else
+# define CURL_EXTERN __declspec(dllimport)
+# endif
+#elif defined(BUILDING_LIBCURL) && defined(CURL_HIDDEN_SYMBOLS)
+# define CURL_EXTERN CURL_EXTERN_SYMBOL
+#else
+# define CURL_EXTERN
+#endif
+
+#ifndef curl_socket_typedef
+/* socket typedef */
+#if defined(CURL_WIN32) && !defined(__LWIP_OPT_H__) && !defined(LWIP_HDR_OPT_H)
+typedef SOCKET curl_socket_t;
+#define CURL_SOCKET_BAD INVALID_SOCKET
+#else
+typedef int curl_socket_t;
+#define CURL_SOCKET_BAD -1
+#endif
+#define curl_socket_typedef
+#endif /* curl_socket_typedef */
+
+/* enum for the different supported SSL backends */
+typedef enum {
+ CURLSSLBACKEND_NONE = 0,
+ CURLSSLBACKEND_OPENSSL = 1,
+ CURLSSLBACKEND_GNUTLS = 2,
+ CURLSSLBACKEND_NSS = 3,
+ CURLSSLBACKEND_OBSOLETE4 = 4, /* Was QSOSSL. */
+ CURLSSLBACKEND_GSKIT = 5,
+ CURLSSLBACKEND_POLARSSL = 6,
+ CURLSSLBACKEND_WOLFSSL = 7,
+ CURLSSLBACKEND_SCHANNEL = 8,
+ CURLSSLBACKEND_SECURETRANSPORT = 9,
+ CURLSSLBACKEND_AXTLS = 10, /* never used since 7.63.0 */
+ CURLSSLBACKEND_MBEDTLS = 11,
+ CURLSSLBACKEND_MESALINK = 12,
+ CURLSSLBACKEND_BEARSSL = 13,
+ CURLSSLBACKEND_RUSTLS = 14
+} curl_sslbackend;
+
+/* aliases for library clones and renames */
+#define CURLSSLBACKEND_LIBRESSL CURLSSLBACKEND_OPENSSL
+#define CURLSSLBACKEND_BORINGSSL CURLSSLBACKEND_OPENSSL
+
+/* deprecated names: */
+#define CURLSSLBACKEND_CYASSL CURLSSLBACKEND_WOLFSSL
+#define CURLSSLBACKEND_DARWINSSL CURLSSLBACKEND_SECURETRANSPORT
+
+struct curl_httppost {
+ struct curl_httppost *next; /* next entry in the list */
+ char *name; /* pointer to allocated name */
+ long namelength; /* length of name length */
+ char *contents; /* pointer to allocated data contents */
+ long contentslength; /* length of contents field, see also
+ CURL_HTTPPOST_LARGE */
+ char *buffer; /* pointer to allocated buffer contents */
+ long bufferlength; /* length of buffer field */
+ char *contenttype; /* Content-Type */
+ struct curl_slist *contentheader; /* list of extra headers for this form */
+ struct curl_httppost *more; /* if one field name has more than one
+ file, this link should link to following
+ files */
+ long flags; /* as defined below */
+
+/* specified content is a file name */
+#define CURL_HTTPPOST_FILENAME (1<<0)
+/* specified content is a file name */
+#define CURL_HTTPPOST_READFILE (1<<1)
+/* name is only stored pointer do not free in formfree */
+#define CURL_HTTPPOST_PTRNAME (1<<2)
+/* contents is only stored pointer do not free in formfree */
+#define CURL_HTTPPOST_PTRCONTENTS (1<<3)
+/* upload file from buffer */
+#define CURL_HTTPPOST_BUFFER (1<<4)
+/* upload file from pointer contents */
+#define CURL_HTTPPOST_PTRBUFFER (1<<5)
+/* upload file contents by using the regular read callback to get the data and
+ pass the given pointer as custom pointer */
+#define CURL_HTTPPOST_CALLBACK (1<<6)
+/* use size in 'contentlen', added in 7.46.0 */
+#define CURL_HTTPPOST_LARGE (1<<7)
+
+ char *showfilename; /* The file name to show. If not set, the
+ actual file name will be used (if this
+ is a file part) */
+ void *userp; /* custom pointer used for
+ HTTPPOST_CALLBACK posts */
+ curl_off_t contentlen; /* alternative length of contents
+ field. Used if CURL_HTTPPOST_LARGE is
+ set. Added in 7.46.0 */
+};
+
+
+/* This is a return code for the progress callback that, when returned, will
+ signal libcurl to continue executing the default progress function */
+#define CURL_PROGRESSFUNC_CONTINUE 0x10000001
+
+/* This is the CURLOPT_PROGRESSFUNCTION callback prototype. It is now
+ considered deprecated but was the only choice up until 7.31.0 */
+typedef int (*curl_progress_callback)(void *clientp,
+ double dltotal,
+ double dlnow,
+ double ultotal,
+ double ulnow);
+
+/* This is the CURLOPT_XFERINFOFUNCTION callback prototype. It was introduced
+ in 7.32.0, avoids the use of floating point numbers and provides more
+ detailed information. */
+typedef int (*curl_xferinfo_callback)(void *clientp,
+ curl_off_t dltotal,
+ curl_off_t dlnow,
+ curl_off_t ultotal,
+ curl_off_t ulnow);
+
+#ifndef CURL_MAX_READ_SIZE
+ /* The maximum receive buffer size configurable via CURLOPT_BUFFERSIZE. */
+#define CURL_MAX_READ_SIZE 524288
+#endif
+
+#ifndef CURL_MAX_WRITE_SIZE
+ /* Tests have proven that 20K is a very bad buffer size for uploads on
+ Windows, while 16K for some odd reason performed a lot better.
+ We do the ifndef check to allow this value to easier be changed at build
+ time for those who feel adventurous. The practical minimum is about
+ 400 bytes since libcurl uses a buffer of this size as a scratch area
+ (unrelated to network send operations). */
+#define CURL_MAX_WRITE_SIZE 16384
+#endif
+
+#ifndef CURL_MAX_HTTP_HEADER
+/* The only reason to have a max limit for this is to avoid the risk of a bad
+ server feeding libcurl with a never-ending header that will cause reallocs
+ infinitely */
+#define CURL_MAX_HTTP_HEADER (100*1024)
+#endif
+
+/* This is a magic return code for the write callback that, when returned,
+ will signal libcurl to pause receiving on the current transfer. */
+#define CURL_WRITEFUNC_PAUSE 0x10000001
+
+typedef size_t (*curl_write_callback)(char *buffer,
+ size_t size,
+ size_t nitems,
+ void *outstream);
+
+/* This callback will be called when a new resolver request is made */
+typedef int (*curl_resolver_start_callback)(void *resolver_state,
+ void *reserved, void *userdata);
+
+/* enumeration of file types */
+typedef enum {
+ CURLFILETYPE_FILE = 0,
+ CURLFILETYPE_DIRECTORY,
+ CURLFILETYPE_SYMLINK,
+ CURLFILETYPE_DEVICE_BLOCK,
+ CURLFILETYPE_DEVICE_CHAR,
+ CURLFILETYPE_NAMEDPIPE,
+ CURLFILETYPE_SOCKET,
+ CURLFILETYPE_DOOR, /* is possible only on Sun Solaris now */
+
+ CURLFILETYPE_UNKNOWN /* should never occur */
+} curlfiletype;
+
+#define CURLFINFOFLAG_KNOWN_FILENAME (1<<0)
+#define CURLFINFOFLAG_KNOWN_FILETYPE (1<<1)
+#define CURLFINFOFLAG_KNOWN_TIME (1<<2)
+#define CURLFINFOFLAG_KNOWN_PERM (1<<3)
+#define CURLFINFOFLAG_KNOWN_UID (1<<4)
+#define CURLFINFOFLAG_KNOWN_GID (1<<5)
+#define CURLFINFOFLAG_KNOWN_SIZE (1<<6)
+#define CURLFINFOFLAG_KNOWN_HLINKCOUNT (1<<7)
+
+/* Information about a single file, used when doing FTP wildcard matching */
+struct curl_fileinfo {
+ char *filename;
+ curlfiletype filetype;
+ time_t time; /* always zero! */
+ unsigned int perm;
+ int uid;
+ int gid;
+ curl_off_t size;
+ long int hardlinks;
+
+ struct {
+ /* If some of these fields is not NULL, it is a pointer to b_data. */
+ char *time;
+ char *perm;
+ char *user;
+ char *group;
+ char *target; /* pointer to the target filename of a symlink */
+ } strings;
+
+ unsigned int flags;
+
+ /* used internally */
+ char *b_data;
+ size_t b_size;
+ size_t b_used;
+};
+
+/* return codes for CURLOPT_CHUNK_BGN_FUNCTION */
+#define CURL_CHUNK_BGN_FUNC_OK 0
+#define CURL_CHUNK_BGN_FUNC_FAIL 1 /* tell the lib to end the task */
+#define CURL_CHUNK_BGN_FUNC_SKIP 2 /* skip this chunk over */
+
+/* if splitting of data transfer is enabled, this callback is called before
+ download of an individual chunk started. Note that parameter "remains" works
+ only for FTP wildcard downloading (for now), otherwise is not used */
+typedef long (*curl_chunk_bgn_callback)(const void *transfer_info,
+ void *ptr,
+ int remains);
+
+/* return codes for CURLOPT_CHUNK_END_FUNCTION */
+#define CURL_CHUNK_END_FUNC_OK 0
+#define CURL_CHUNK_END_FUNC_FAIL 1 /* tell the lib to end the task */
+
+/* If splitting of data transfer is enabled this callback is called after
+ download of an individual chunk finished.
+ Note! After this callback was set then it have to be called FOR ALL chunks.
+ Even if downloading of this chunk was skipped in CHUNK_BGN_FUNC.
+ This is the reason why we don't need "transfer_info" parameter in this
+ callback and we are not interested in "remains" parameter too. */
+typedef long (*curl_chunk_end_callback)(void *ptr);
+
+/* return codes for FNMATCHFUNCTION */
+#define CURL_FNMATCHFUNC_MATCH 0 /* string corresponds to the pattern */
+#define CURL_FNMATCHFUNC_NOMATCH 1 /* pattern doesn't match the string */
+#define CURL_FNMATCHFUNC_FAIL 2 /* an error occurred */
+
+/* callback type for wildcard downloading pattern matching. If the
+ string matches the pattern, return CURL_FNMATCHFUNC_MATCH value, etc. */
+typedef int (*curl_fnmatch_callback)(void *ptr,
+ const char *pattern,
+ const char *string);
+
+/* These are the return codes for the seek callbacks */
+#define CURL_SEEKFUNC_OK 0
+#define CURL_SEEKFUNC_FAIL 1 /* fail the entire transfer */
+#define CURL_SEEKFUNC_CANTSEEK 2 /* tell libcurl seeking can't be done, so
+ libcurl might try other means instead */
+typedef int (*curl_seek_callback)(void *instream,
+ curl_off_t offset,
+ int origin); /* 'whence' */
+
+/* This is a return code for the read callback that, when returned, will
+ signal libcurl to immediately abort the current transfer. */
+#define CURL_READFUNC_ABORT 0x10000000
+/* This is a return code for the read callback that, when returned, will
+ signal libcurl to pause sending data on the current transfer. */
+#define CURL_READFUNC_PAUSE 0x10000001
+
+/* Return code for when the trailing headers' callback has terminated
+ without any errors*/
+#define CURL_TRAILERFUNC_OK 0
+/* Return code for when was an error in the trailing header's list and we
+ want to abort the request */
+#define CURL_TRAILERFUNC_ABORT 1
+
+typedef size_t (*curl_read_callback)(char *buffer,
+ size_t size,
+ size_t nitems,
+ void *instream);
+
+typedef int (*curl_trailer_callback)(struct curl_slist **list,
+ void *userdata);
+
+typedef enum {
+ CURLSOCKTYPE_IPCXN, /* socket created for a specific IP connection */
+ CURLSOCKTYPE_ACCEPT, /* socket created by accept() call */
+ CURLSOCKTYPE_LAST /* never use */
+} curlsocktype;
+
+/* The return code from the sockopt_callback can signal information back
+ to libcurl: */
+#define CURL_SOCKOPT_OK 0
+#define CURL_SOCKOPT_ERROR 1 /* causes libcurl to abort and return
+ CURLE_ABORTED_BY_CALLBACK */
+#define CURL_SOCKOPT_ALREADY_CONNECTED 2
+
+typedef int (*curl_sockopt_callback)(void *clientp,
+ curl_socket_t curlfd,
+ curlsocktype purpose);
+
+struct curl_sockaddr {
+ int family;
+ int socktype;
+ int protocol;
+ unsigned int addrlen; /* addrlen was a socklen_t type before 7.18.0 but it
+ turned really ugly and painful on the systems that
+ lack this type */
+ struct sockaddr addr;
+};
+
+typedef curl_socket_t
+(*curl_opensocket_callback)(void *clientp,
+ curlsocktype purpose,
+ struct curl_sockaddr *address);
+
+typedef int
+(*curl_closesocket_callback)(void *clientp, curl_socket_t item);
+
+typedef enum {
+ CURLIOE_OK, /* I/O operation successful */
+ CURLIOE_UNKNOWNCMD, /* command was unknown to callback */
+ CURLIOE_FAILRESTART, /* failed to restart the read */
+ CURLIOE_LAST /* never use */
+} curlioerr;
+
+typedef enum {
+ CURLIOCMD_NOP, /* no operation */
+ CURLIOCMD_RESTARTREAD, /* restart the read stream from start */
+ CURLIOCMD_LAST /* never use */
+} curliocmd;
+
+typedef curlioerr (*curl_ioctl_callback)(CURL *handle,
+ int cmd,
+ void *clientp);
+
+#ifndef CURL_DID_MEMORY_FUNC_TYPEDEFS
+/*
+ * The following typedef's are signatures of malloc, free, realloc, strdup and
+ * calloc respectively. Function pointers of these types can be passed to the
+ * curl_global_init_mem() function to set user defined memory management
+ * callback routines.
+ */
+typedef void *(*curl_malloc_callback)(size_t size);
+typedef void (*curl_free_callback)(void *ptr);
+typedef void *(*curl_realloc_callback)(void *ptr, size_t size);
+typedef char *(*curl_strdup_callback)(const char *str);
+typedef void *(*curl_calloc_callback)(size_t nmemb, size_t size);
+
+#define CURL_DID_MEMORY_FUNC_TYPEDEFS
+#endif
+
+/* the kind of data that is passed to information_callback*/
+typedef enum {
+ CURLINFO_TEXT = 0,
+ CURLINFO_HEADER_IN, /* 1 */
+ CURLINFO_HEADER_OUT, /* 2 */
+ CURLINFO_DATA_IN, /* 3 */
+ CURLINFO_DATA_OUT, /* 4 */
+ CURLINFO_SSL_DATA_IN, /* 5 */
+ CURLINFO_SSL_DATA_OUT, /* 6 */
+ CURLINFO_END
+} curl_infotype;
+
+typedef int (*curl_debug_callback)
+ (CURL *handle, /* the handle/transfer this concerns */
+ curl_infotype type, /* what kind of data */
+ char *data, /* points to the data */
+ size_t size, /* size of the data pointed to */
+ void *userptr); /* whatever the user please */
+
+/* This is the CURLOPT_PREREQFUNCTION callback prototype. */
+typedef int (*curl_prereq_callback)(void *clientp,
+ char *conn_primary_ip,
+ char *conn_local_ip,
+ int conn_primary_port,
+ int conn_local_port);
+
+/* Return code for when the pre-request callback has terminated without
+ any errors */
+#define CURL_PREREQFUNC_OK 0
+/* Return code for when the pre-request callback wants to abort the
+ request */
+#define CURL_PREREQFUNC_ABORT 1
+
+/* All possible error codes from all sorts of curl functions. Future versions
+ may return other values, stay prepared.
+
+ Always add new return codes last. Never *EVER* remove any. The return
+ codes must remain the same!
+ */
+
+typedef enum {
+ CURLE_OK = 0,
+ CURLE_UNSUPPORTED_PROTOCOL, /* 1 */
+ CURLE_FAILED_INIT, /* 2 */
+ CURLE_URL_MALFORMAT, /* 3 */
+ CURLE_NOT_BUILT_IN, /* 4 - [was obsoleted in August 2007 for
+ 7.17.0, reused in April 2011 for 7.21.5] */
+ CURLE_COULDNT_RESOLVE_PROXY, /* 5 */
+ CURLE_COULDNT_RESOLVE_HOST, /* 6 */
+ CURLE_COULDNT_CONNECT, /* 7 */
+ CURLE_WEIRD_SERVER_REPLY, /* 8 */
+ CURLE_REMOTE_ACCESS_DENIED, /* 9 a service was denied by the server
+ due to lack of access - when login fails
+ this is not returned. */
+ CURLE_FTP_ACCEPT_FAILED, /* 10 - [was obsoleted in April 2006 for
+ 7.15.4, reused in Dec 2011 for 7.24.0]*/
+ CURLE_FTP_WEIRD_PASS_REPLY, /* 11 */
+ CURLE_FTP_ACCEPT_TIMEOUT, /* 12 - timeout occurred accepting server
+ [was obsoleted in August 2007 for 7.17.0,
+ reused in Dec 2011 for 7.24.0]*/
+ CURLE_FTP_WEIRD_PASV_REPLY, /* 13 */
+ CURLE_FTP_WEIRD_227_FORMAT, /* 14 */
+ CURLE_FTP_CANT_GET_HOST, /* 15 */
+ CURLE_HTTP2, /* 16 - A problem in the http2 framing layer.
+ [was obsoleted in August 2007 for 7.17.0,
+ reused in July 2014 for 7.38.0] */
+ CURLE_FTP_COULDNT_SET_TYPE, /* 17 */
+ CURLE_PARTIAL_FILE, /* 18 */
+ CURLE_FTP_COULDNT_RETR_FILE, /* 19 */
+ CURLE_OBSOLETE20, /* 20 - NOT USED */
+ CURLE_QUOTE_ERROR, /* 21 - quote command failure */
+ CURLE_HTTP_RETURNED_ERROR, /* 22 */
+ CURLE_WRITE_ERROR, /* 23 */
+ CURLE_OBSOLETE24, /* 24 - NOT USED */
+ CURLE_UPLOAD_FAILED, /* 25 - failed upload "command" */
+ CURLE_READ_ERROR, /* 26 - couldn't open/read from file */
+ CURLE_OUT_OF_MEMORY, /* 27 */
+ /* Note: CURLE_OUT_OF_MEMORY may sometimes indicate a conversion error
+ instead of a memory allocation error if CURL_DOES_CONVERSIONS
+ is defined
+ */
+ CURLE_OPERATION_TIMEDOUT, /* 28 - the timeout time was reached */
+ CURLE_OBSOLETE29, /* 29 - NOT USED */
+ CURLE_FTP_PORT_FAILED, /* 30 - FTP PORT operation failed */
+ CURLE_FTP_COULDNT_USE_REST, /* 31 - the REST command failed */
+ CURLE_OBSOLETE32, /* 32 - NOT USED */
+ CURLE_RANGE_ERROR, /* 33 - RANGE "command" didn't work */
+ CURLE_HTTP_POST_ERROR, /* 34 */
+ CURLE_SSL_CONNECT_ERROR, /* 35 - wrong when connecting with SSL */
+ CURLE_BAD_DOWNLOAD_RESUME, /* 36 - couldn't resume download */
+ CURLE_FILE_COULDNT_READ_FILE, /* 37 */
+ CURLE_LDAP_CANNOT_BIND, /* 38 */
+ CURLE_LDAP_SEARCH_FAILED, /* 39 */
+ CURLE_OBSOLETE40, /* 40 - NOT USED */
+ CURLE_FUNCTION_NOT_FOUND, /* 41 - NOT USED starting with 7.53.0 */
+ CURLE_ABORTED_BY_CALLBACK, /* 42 */
+ CURLE_BAD_FUNCTION_ARGUMENT, /* 43 */
+ CURLE_OBSOLETE44, /* 44 - NOT USED */
+ CURLE_INTERFACE_FAILED, /* 45 - CURLOPT_INTERFACE failed */
+ CURLE_OBSOLETE46, /* 46 - NOT USED */
+ CURLE_TOO_MANY_REDIRECTS, /* 47 - catch endless re-direct loops */
+ CURLE_UNKNOWN_OPTION, /* 48 - User specified an unknown option */
+ CURLE_SETOPT_OPTION_SYNTAX, /* 49 - Malformed setopt option */
+ CURLE_OBSOLETE50, /* 50 - NOT USED */
+ CURLE_OBSOLETE51, /* 51 - NOT USED */
+ CURLE_GOT_NOTHING, /* 52 - when this is a specific error */
+ CURLE_SSL_ENGINE_NOTFOUND, /* 53 - SSL crypto engine not found */
+ CURLE_SSL_ENGINE_SETFAILED, /* 54 - can not set SSL crypto engine as
+ default */
+ CURLE_SEND_ERROR, /* 55 - failed sending network data */
+ CURLE_RECV_ERROR, /* 56 - failure in receiving network data */
+ CURLE_OBSOLETE57, /* 57 - NOT IN USE */
+ CURLE_SSL_CERTPROBLEM, /* 58 - problem with the local certificate */
+ CURLE_SSL_CIPHER, /* 59 - couldn't use specified cipher */
+ CURLE_PEER_FAILED_VERIFICATION, /* 60 - peer's certificate or fingerprint
+ wasn't verified fine */
+ CURLE_BAD_CONTENT_ENCODING, /* 61 - Unrecognized/bad encoding */
+ CURLE_LDAP_INVALID_URL, /* 62 - Invalid LDAP URL */
+ CURLE_FILESIZE_EXCEEDED, /* 63 - Maximum file size exceeded */
+ CURLE_USE_SSL_FAILED, /* 64 - Requested FTP SSL level failed */
+ CURLE_SEND_FAIL_REWIND, /* 65 - Sending the data requires a rewind
+ that failed */
+ CURLE_SSL_ENGINE_INITFAILED, /* 66 - failed to initialise ENGINE */
+ CURLE_LOGIN_DENIED, /* 67 - user, password or similar was not
+ accepted and we failed to login */
+ CURLE_TFTP_NOTFOUND, /* 68 - file not found on server */
+ CURLE_TFTP_PERM, /* 69 - permission problem on server */
+ CURLE_REMOTE_DISK_FULL, /* 70 - out of disk space on server */
+ CURLE_TFTP_ILLEGAL, /* 71 - Illegal TFTP operation */
+ CURLE_TFTP_UNKNOWNID, /* 72 - Unknown transfer ID */
+ CURLE_REMOTE_FILE_EXISTS, /* 73 - File already exists */
+ CURLE_TFTP_NOSUCHUSER, /* 74 - No such user */
+ CURLE_CONV_FAILED, /* 75 - conversion failed */
+ CURLE_CONV_REQD, /* 76 - caller must register conversion
+ callbacks using curl_easy_setopt options
+ CURLOPT_CONV_FROM_NETWORK_FUNCTION,
+ CURLOPT_CONV_TO_NETWORK_FUNCTION, and
+ CURLOPT_CONV_FROM_UTF8_FUNCTION */
+ CURLE_SSL_CACERT_BADFILE, /* 77 - could not load CACERT file, missing
+ or wrong format */
+ CURLE_REMOTE_FILE_NOT_FOUND, /* 78 - remote file not found */
+ CURLE_SSH, /* 79 - error from the SSH layer, somewhat
+ generic so the error message will be of
+ interest when this has happened */
+
+ CURLE_SSL_SHUTDOWN_FAILED, /* 80 - Failed to shut down the SSL
+ connection */
+ CURLE_AGAIN, /* 81 - socket is not ready for send/recv,
+ wait till it's ready and try again (Added
+ in 7.18.2) */
+ CURLE_SSL_CRL_BADFILE, /* 82 - could not load CRL file, missing or
+ wrong format (Added in 7.19.0) */
+ CURLE_SSL_ISSUER_ERROR, /* 83 - Issuer check failed. (Added in
+ 7.19.0) */
+ CURLE_FTP_PRET_FAILED, /* 84 - a PRET command failed */
+ CURLE_RTSP_CSEQ_ERROR, /* 85 - mismatch of RTSP CSeq numbers */
+ CURLE_RTSP_SESSION_ERROR, /* 86 - mismatch of RTSP Session Ids */
+ CURLE_FTP_BAD_FILE_LIST, /* 87 - unable to parse FTP file list */
+ CURLE_CHUNK_FAILED, /* 88 - chunk callback reported error */
+ CURLE_NO_CONNECTION_AVAILABLE, /* 89 - No connection available, the
+ session will be queued */
+ CURLE_SSL_PINNEDPUBKEYNOTMATCH, /* 90 - specified pinned public key did not
+ match */
+ CURLE_SSL_INVALIDCERTSTATUS, /* 91 - invalid certificate status */
+ CURLE_HTTP2_STREAM, /* 92 - stream error in HTTP/2 framing layer
+ */
+ CURLE_RECURSIVE_API_CALL, /* 93 - an api function was called from
+ inside a callback */
+ CURLE_AUTH_ERROR, /* 94 - an authentication function returned an
+ error */
+ CURLE_HTTP3, /* 95 - An HTTP/3 layer problem */
+ CURLE_QUIC_CONNECT_ERROR, /* 96 - QUIC connection error */
+ CURLE_PROXY, /* 97 - proxy handshake error */
+ CURLE_SSL_CLIENTCERT, /* 98 - client-side certificate required */
+ CURL_LAST /* never use! */
+} CURLcode;
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Previously obsolete error code re-used in 7.38.0 */
+#define CURLE_OBSOLETE16 CURLE_HTTP2
+
+/* Previously obsolete error codes re-used in 7.24.0 */
+#define CURLE_OBSOLETE10 CURLE_FTP_ACCEPT_FAILED
+#define CURLE_OBSOLETE12 CURLE_FTP_ACCEPT_TIMEOUT
+
+/* compatibility with older names */
+#define CURLOPT_ENCODING CURLOPT_ACCEPT_ENCODING
+#define CURLE_FTP_WEIRD_SERVER_REPLY CURLE_WEIRD_SERVER_REPLY
+
+/* The following were added in 7.62.0 */
+#define CURLE_SSL_CACERT CURLE_PEER_FAILED_VERIFICATION
+
+/* The following were added in 7.21.5, April 2011 */
+#define CURLE_UNKNOWN_TELNET_OPTION CURLE_UNKNOWN_OPTION
+
+/* Added for 7.78.0 */
+#define CURLE_TELNET_OPTION_SYNTAX CURLE_SETOPT_OPTION_SYNTAX
+
+/* The following were added in 7.17.1 */
+/* These are scheduled to disappear by 2009 */
+#define CURLE_SSL_PEER_CERTIFICATE CURLE_PEER_FAILED_VERIFICATION
+
+/* The following were added in 7.17.0 */
+/* These are scheduled to disappear by 2009 */
+#define CURLE_OBSOLETE CURLE_OBSOLETE50 /* no one should be using this! */
+#define CURLE_BAD_PASSWORD_ENTERED CURLE_OBSOLETE46
+#define CURLE_BAD_CALLING_ORDER CURLE_OBSOLETE44
+#define CURLE_FTP_USER_PASSWORD_INCORRECT CURLE_OBSOLETE10
+#define CURLE_FTP_CANT_RECONNECT CURLE_OBSOLETE16
+#define CURLE_FTP_COULDNT_GET_SIZE CURLE_OBSOLETE32
+#define CURLE_FTP_COULDNT_SET_ASCII CURLE_OBSOLETE29
+#define CURLE_FTP_WEIRD_USER_REPLY CURLE_OBSOLETE12
+#define CURLE_FTP_WRITE_ERROR CURLE_OBSOLETE20
+#define CURLE_LIBRARY_NOT_FOUND CURLE_OBSOLETE40
+#define CURLE_MALFORMAT_USER CURLE_OBSOLETE24
+#define CURLE_SHARE_IN_USE CURLE_OBSOLETE57
+#define CURLE_URL_MALFORMAT_USER CURLE_NOT_BUILT_IN
+
+#define CURLE_FTP_ACCESS_DENIED CURLE_REMOTE_ACCESS_DENIED
+#define CURLE_FTP_COULDNT_SET_BINARY CURLE_FTP_COULDNT_SET_TYPE
+#define CURLE_FTP_QUOTE_ERROR CURLE_QUOTE_ERROR
+#define CURLE_TFTP_DISKFULL CURLE_REMOTE_DISK_FULL
+#define CURLE_TFTP_EXISTS CURLE_REMOTE_FILE_EXISTS
+#define CURLE_HTTP_RANGE_ERROR CURLE_RANGE_ERROR
+#define CURLE_FTP_SSL_FAILED CURLE_USE_SSL_FAILED
+
+/* The following were added earlier */
+
+#define CURLE_OPERATION_TIMEOUTED CURLE_OPERATION_TIMEDOUT
+
+#define CURLE_HTTP_NOT_FOUND CURLE_HTTP_RETURNED_ERROR
+#define CURLE_HTTP_PORT_FAILED CURLE_INTERFACE_FAILED
+#define CURLE_FTP_COULDNT_STOR_FILE CURLE_UPLOAD_FAILED
+
+#define CURLE_FTP_PARTIAL_FILE CURLE_PARTIAL_FILE
+#define CURLE_FTP_BAD_DOWNLOAD_RESUME CURLE_BAD_DOWNLOAD_RESUME
+
+/* This was the error code 50 in 7.7.3 and a few earlier versions, this
+ is no longer used by libcurl but is instead #defined here only to not
+ make programs break */
+#define CURLE_ALREADY_COMPLETE 99999
+
+/* Provide defines for really old option names */
+#define CURLOPT_FILE CURLOPT_WRITEDATA /* name changed in 7.9.7 */
+#define CURLOPT_INFILE CURLOPT_READDATA /* name changed in 7.9.7 */
+#define CURLOPT_WRITEHEADER CURLOPT_HEADERDATA
+
+/* Since long deprecated options with no code in the lib that does anything
+ with them. */
+#define CURLOPT_WRITEINFO CURLOPT_OBSOLETE40
+#define CURLOPT_CLOSEPOLICY CURLOPT_OBSOLETE72
+
+#endif /*!CURL_NO_OLDIES*/
+
+/*
+ * Proxy error codes. Returned in CURLINFO_PROXY_ERROR if CURLE_PROXY was
+ * return for the transfers.
+ */
+typedef enum {
+ CURLPX_OK,
+ CURLPX_BAD_ADDRESS_TYPE,
+ CURLPX_BAD_VERSION,
+ CURLPX_CLOSED,
+ CURLPX_GSSAPI,
+ CURLPX_GSSAPI_PERMSG,
+ CURLPX_GSSAPI_PROTECTION,
+ CURLPX_IDENTD,
+ CURLPX_IDENTD_DIFFER,
+ CURLPX_LONG_HOSTNAME,
+ CURLPX_LONG_PASSWD,
+ CURLPX_LONG_USER,
+ CURLPX_NO_AUTH,
+ CURLPX_RECV_ADDRESS,
+ CURLPX_RECV_AUTH,
+ CURLPX_RECV_CONNECT,
+ CURLPX_RECV_REQACK,
+ CURLPX_REPLY_ADDRESS_TYPE_NOT_SUPPORTED,
+ CURLPX_REPLY_COMMAND_NOT_SUPPORTED,
+ CURLPX_REPLY_CONNECTION_REFUSED,
+ CURLPX_REPLY_GENERAL_SERVER_FAILURE,
+ CURLPX_REPLY_HOST_UNREACHABLE,
+ CURLPX_REPLY_NETWORK_UNREACHABLE,
+ CURLPX_REPLY_NOT_ALLOWED,
+ CURLPX_REPLY_TTL_EXPIRED,
+ CURLPX_REPLY_UNASSIGNED,
+ CURLPX_REQUEST_FAILED,
+ CURLPX_RESOLVE_HOST,
+ CURLPX_SEND_AUTH,
+ CURLPX_SEND_CONNECT,
+ CURLPX_SEND_REQUEST,
+ CURLPX_UNKNOWN_FAIL,
+ CURLPX_UNKNOWN_MODE,
+ CURLPX_USER_REJECTED,
+ CURLPX_LAST /* never use */
+} CURLproxycode;
+
+/* This prototype applies to all conversion callbacks */
+typedef CURLcode (*curl_conv_callback)(char *buffer, size_t length);
+
+typedef CURLcode (*curl_ssl_ctx_callback)(CURL *curl, /* easy handle */
+ void *ssl_ctx, /* actually an OpenSSL
+ or WolfSSL SSL_CTX,
+ or an mbedTLS
+ mbedtls_ssl_config */
+ void *userptr);
+
+typedef enum {
+ CURLPROXY_HTTP = 0, /* added in 7.10, new in 7.19.4 default is to use
+ CONNECT HTTP/1.1 */
+ CURLPROXY_HTTP_1_0 = 1, /* added in 7.19.4, force to use CONNECT
+ HTTP/1.0 */
+ CURLPROXY_HTTPS = 2, /* added in 7.52.0 */
+ CURLPROXY_SOCKS4 = 4, /* support added in 7.15.2, enum existed already
+ in 7.10 */
+ CURLPROXY_SOCKS5 = 5, /* added in 7.10 */
+ CURLPROXY_SOCKS4A = 6, /* added in 7.18.0 */
+ CURLPROXY_SOCKS5_HOSTNAME = 7 /* Use the SOCKS5 protocol but pass along the
+ host name rather than the IP address. added
+ in 7.18.0 */
+} curl_proxytype; /* this enum was added in 7.10 */
+
+/*
+ * Bitmasks for CURLOPT_HTTPAUTH and CURLOPT_PROXYAUTH options:
+ *
+ * CURLAUTH_NONE - No HTTP authentication
+ * CURLAUTH_BASIC - HTTP Basic authentication (default)
+ * CURLAUTH_DIGEST - HTTP Digest authentication
+ * CURLAUTH_NEGOTIATE - HTTP Negotiate (SPNEGO) authentication
+ * CURLAUTH_GSSNEGOTIATE - Alias for CURLAUTH_NEGOTIATE (deprecated)
+ * CURLAUTH_NTLM - HTTP NTLM authentication
+ * CURLAUTH_DIGEST_IE - HTTP Digest authentication with IE flavour
+ * CURLAUTH_NTLM_WB - HTTP NTLM authentication delegated to winbind helper
+ * CURLAUTH_BEARER - HTTP Bearer token authentication
+ * CURLAUTH_ONLY - Use together with a single other type to force no
+ * authentication or just that single type
+ * CURLAUTH_ANY - All fine types set
+ * CURLAUTH_ANYSAFE - All fine types except Basic
+ */
+
+#define CURLAUTH_NONE ((unsigned long)0)
+#define CURLAUTH_BASIC (((unsigned long)1)<<0)
+#define CURLAUTH_DIGEST (((unsigned long)1)<<1)
+#define CURLAUTH_NEGOTIATE (((unsigned long)1)<<2)
+/* Deprecated since the advent of CURLAUTH_NEGOTIATE */
+#define CURLAUTH_GSSNEGOTIATE CURLAUTH_NEGOTIATE
+/* Used for CURLOPT_SOCKS5_AUTH to stay terminologically correct */
+#define CURLAUTH_GSSAPI CURLAUTH_NEGOTIATE
+#define CURLAUTH_NTLM (((unsigned long)1)<<3)
+#define CURLAUTH_DIGEST_IE (((unsigned long)1)<<4)
+#define CURLAUTH_NTLM_WB (((unsigned long)1)<<5)
+#define CURLAUTH_BEARER (((unsigned long)1)<<6)
+#define CURLAUTH_AWS_SIGV4 (((unsigned long)1)<<7)
+#define CURLAUTH_ONLY (((unsigned long)1)<<31)
+#define CURLAUTH_ANY (~CURLAUTH_DIGEST_IE)
+#define CURLAUTH_ANYSAFE (~(CURLAUTH_BASIC|CURLAUTH_DIGEST_IE))
+
+#define CURLSSH_AUTH_ANY ~0 /* all types supported by the server */
+#define CURLSSH_AUTH_NONE 0 /* none allowed, silly but complete */
+#define CURLSSH_AUTH_PUBLICKEY (1<<0) /* public/private key files */
+#define CURLSSH_AUTH_PASSWORD (1<<1) /* password */
+#define CURLSSH_AUTH_HOST (1<<2) /* host key files */
+#define CURLSSH_AUTH_KEYBOARD (1<<3) /* keyboard interactive */
+#define CURLSSH_AUTH_AGENT (1<<4) /* agent (ssh-agent, pageant...) */
+#define CURLSSH_AUTH_GSSAPI (1<<5) /* gssapi (kerberos, ...) */
+#define CURLSSH_AUTH_DEFAULT CURLSSH_AUTH_ANY
+
+#define CURLGSSAPI_DELEGATION_NONE 0 /* no delegation (default) */
+#define CURLGSSAPI_DELEGATION_POLICY_FLAG (1<<0) /* if permitted by policy */
+#define CURLGSSAPI_DELEGATION_FLAG (1<<1) /* delegate always */
+
+#define CURL_ERROR_SIZE 256
+
+enum curl_khtype {
+ CURLKHTYPE_UNKNOWN,
+ CURLKHTYPE_RSA1,
+ CURLKHTYPE_RSA,
+ CURLKHTYPE_DSS,
+ CURLKHTYPE_ECDSA,
+ CURLKHTYPE_ED25519
+};
+
+struct curl_khkey {
+ const char *key; /* points to a null-terminated string encoded with base64
+ if len is zero, otherwise to the "raw" data */
+ size_t len;
+ enum curl_khtype keytype;
+};
+
+/* this is the set of return values expected from the curl_sshkeycallback
+ callback */
+enum curl_khstat {
+ CURLKHSTAT_FINE_ADD_TO_FILE,
+ CURLKHSTAT_FINE,
+ CURLKHSTAT_REJECT, /* reject the connection, return an error */
+ CURLKHSTAT_DEFER, /* do not accept it, but we can't answer right now so
+ this causes a CURLE_DEFER error but otherwise the
+ connection will be left intact etc */
+ CURLKHSTAT_FINE_REPLACE, /* accept and replace the wrong key*/
+ CURLKHSTAT_LAST /* not for use, only a marker for last-in-list */
+};
+
+/* this is the set of status codes pass in to the callback */
+enum curl_khmatch {
+ CURLKHMATCH_OK, /* match */
+ CURLKHMATCH_MISMATCH, /* host found, key mismatch! */
+ CURLKHMATCH_MISSING, /* no matching host/key found */
+ CURLKHMATCH_LAST /* not for use, only a marker for last-in-list */
+};
+
+typedef int
+ (*curl_sshkeycallback) (CURL *easy, /* easy handle */
+ const struct curl_khkey *knownkey, /* known */
+ const struct curl_khkey *foundkey, /* found */
+ enum curl_khmatch, /* libcurl's view on the keys */
+ void *clientp); /* custom pointer passed from app */
+
+/* parameter for the CURLOPT_USE_SSL option */
+typedef enum {
+ CURLUSESSL_NONE, /* do not attempt to use SSL */
+ CURLUSESSL_TRY, /* try using SSL, proceed anyway otherwise */
+ CURLUSESSL_CONTROL, /* SSL for the control connection or fail */
+ CURLUSESSL_ALL, /* SSL for all communication or fail */
+ CURLUSESSL_LAST /* not an option, never use */
+} curl_usessl;
+
+/* Definition of bits for the CURLOPT_SSL_OPTIONS argument: */
+
+/* - ALLOW_BEAST tells libcurl to allow the BEAST SSL vulnerability in the
+ name of improving interoperability with older servers. Some SSL libraries
+ have introduced work-arounds for this flaw but those work-arounds sometimes
+ make the SSL communication fail. To regain functionality with those broken
+ servers, a user can this way allow the vulnerability back. */
+#define CURLSSLOPT_ALLOW_BEAST (1<<0)
+
+/* - NO_REVOKE tells libcurl to disable certificate revocation checks for those
+ SSL backends where such behavior is present. */
+#define CURLSSLOPT_NO_REVOKE (1<<1)
+
+/* - NO_PARTIALCHAIN tells libcurl to *NOT* accept a partial certificate chain
+ if possible. The OpenSSL backend has this ability. */
+#define CURLSSLOPT_NO_PARTIALCHAIN (1<<2)
+
+/* - REVOKE_BEST_EFFORT tells libcurl to ignore certificate revocation offline
+ checks and ignore missing revocation list for those SSL backends where such
+ behavior is present. */
+#define CURLSSLOPT_REVOKE_BEST_EFFORT (1<<3)
+
+/* - CURLSSLOPT_NATIVE_CA tells libcurl to use standard certificate store of
+ operating system. Currently implemented under MS-Windows. */
+#define CURLSSLOPT_NATIVE_CA (1<<4)
+
+/* - CURLSSLOPT_AUTO_CLIENT_CERT tells libcurl to automatically locate and use
+ a client certificate for authentication. (Schannel) */
+#define CURLSSLOPT_AUTO_CLIENT_CERT (1<<5)
+
+/* The default connection attempt delay in milliseconds for happy eyeballs.
+ CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS.3 and happy-eyeballs-timeout-ms.d document
+ this value, keep them in sync. */
+#define CURL_HET_DEFAULT 200L
+
+/* The default connection upkeep interval in milliseconds. */
+#define CURL_UPKEEP_INTERVAL_DEFAULT 60000L
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Backwards compatibility with older names */
+/* These are scheduled to disappear by 2009 */
+
+#define CURLFTPSSL_NONE CURLUSESSL_NONE
+#define CURLFTPSSL_TRY CURLUSESSL_TRY
+#define CURLFTPSSL_CONTROL CURLUSESSL_CONTROL
+#define CURLFTPSSL_ALL CURLUSESSL_ALL
+#define CURLFTPSSL_LAST CURLUSESSL_LAST
+#define curl_ftpssl curl_usessl
+#endif /*!CURL_NO_OLDIES*/
+
+/* parameter for the CURLOPT_FTP_SSL_CCC option */
+typedef enum {
+ CURLFTPSSL_CCC_NONE, /* do not send CCC */
+ CURLFTPSSL_CCC_PASSIVE, /* Let the server initiate the shutdown */
+ CURLFTPSSL_CCC_ACTIVE, /* Initiate the shutdown */
+ CURLFTPSSL_CCC_LAST /* not an option, never use */
+} curl_ftpccc;
+
+/* parameter for the CURLOPT_FTPSSLAUTH option */
+typedef enum {
+ CURLFTPAUTH_DEFAULT, /* let libcurl decide */
+ CURLFTPAUTH_SSL, /* use "AUTH SSL" */
+ CURLFTPAUTH_TLS, /* use "AUTH TLS" */
+ CURLFTPAUTH_LAST /* not an option, never use */
+} curl_ftpauth;
+
+/* parameter for the CURLOPT_FTP_CREATE_MISSING_DIRS option */
+typedef enum {
+ CURLFTP_CREATE_DIR_NONE, /* do NOT create missing dirs! */
+ CURLFTP_CREATE_DIR, /* (FTP/SFTP) if CWD fails, try MKD and then CWD
+ again if MKD succeeded, for SFTP this does
+ similar magic */
+ CURLFTP_CREATE_DIR_RETRY, /* (FTP only) if CWD fails, try MKD and then CWD
+ again even if MKD failed! */
+ CURLFTP_CREATE_DIR_LAST /* not an option, never use */
+} curl_ftpcreatedir;
+
+/* parameter for the CURLOPT_FTP_FILEMETHOD option */
+typedef enum {
+ CURLFTPMETHOD_DEFAULT, /* let libcurl pick */
+ CURLFTPMETHOD_MULTICWD, /* single CWD operation for each path part */
+ CURLFTPMETHOD_NOCWD, /* no CWD at all */
+ CURLFTPMETHOD_SINGLECWD, /* one CWD to full dir, then work on file */
+ CURLFTPMETHOD_LAST /* not an option, never use */
+} curl_ftpmethod;
+
+/* bitmask defines for CURLOPT_HEADEROPT */
+#define CURLHEADER_UNIFIED 0
+#define CURLHEADER_SEPARATE (1<<0)
+
+/* CURLALTSVC_* are bits for the CURLOPT_ALTSVC_CTRL option */
+#define CURLALTSVC_READONLYFILE (1<<2)
+#define CURLALTSVC_H1 (1<<3)
+#define CURLALTSVC_H2 (1<<4)
+#define CURLALTSVC_H3 (1<<5)
+
+
+struct curl_hstsentry {
+ char *name;
+ size_t namelen;
+ unsigned int includeSubDomains:1;
+ char expire[18]; /* YYYYMMDD HH:MM:SS [null-terminated] */
+};
+
+struct curl_index {
+ size_t index; /* the provided entry's "index" or count */
+ size_t total; /* total number of entries to save */
+};
+
+typedef enum {
+ CURLSTS_OK,
+ CURLSTS_DONE,
+ CURLSTS_FAIL
+} CURLSTScode;
+
+typedef CURLSTScode (*curl_hstsread_callback)(CURL *easy,
+ struct curl_hstsentry *e,
+ void *userp);
+typedef CURLSTScode (*curl_hstswrite_callback)(CURL *easy,
+ struct curl_hstsentry *e,
+ struct curl_index *i,
+ void *userp);
+
+/* CURLHSTS_* are bits for the CURLOPT_HSTS option */
+#define CURLHSTS_ENABLE (long)(1<<0)
+#define CURLHSTS_READONLYFILE (long)(1<<1)
+
+/* CURLPROTO_ defines are for the CURLOPT_*PROTOCOLS options */
+#define CURLPROTO_HTTP (1<<0)
+#define CURLPROTO_HTTPS (1<<1)
+#define CURLPROTO_FTP (1<<2)
+#define CURLPROTO_FTPS (1<<3)
+#define CURLPROTO_SCP (1<<4)
+#define CURLPROTO_SFTP (1<<5)
+#define CURLPROTO_TELNET (1<<6)
+#define CURLPROTO_LDAP (1<<7)
+#define CURLPROTO_LDAPS (1<<8)
+#define CURLPROTO_DICT (1<<9)
+#define CURLPROTO_FILE (1<<10)
+#define CURLPROTO_TFTP (1<<11)
+#define CURLPROTO_IMAP (1<<12)
+#define CURLPROTO_IMAPS (1<<13)
+#define CURLPROTO_POP3 (1<<14)
+#define CURLPROTO_POP3S (1<<15)
+#define CURLPROTO_SMTP (1<<16)
+#define CURLPROTO_SMTPS (1<<17)
+#define CURLPROTO_RTSP (1<<18)
+#define CURLPROTO_RTMP (1<<19)
+#define CURLPROTO_RTMPT (1<<20)
+#define CURLPROTO_RTMPE (1<<21)
+#define CURLPROTO_RTMPTE (1<<22)
+#define CURLPROTO_RTMPS (1<<23)
+#define CURLPROTO_RTMPTS (1<<24)
+#define CURLPROTO_GOPHER (1<<25)
+#define CURLPROTO_SMB (1<<26)
+#define CURLPROTO_SMBS (1<<27)
+#define CURLPROTO_MQTT (1<<28)
+#define CURLPROTO_GOPHERS (1<<29)
+#define CURLPROTO_ALL (~0) /* enable everything */
+
+/* long may be 32 or 64 bits, but we should never depend on anything else
+ but 32 */
+#define CURLOPTTYPE_LONG 0
+#define CURLOPTTYPE_OBJECTPOINT 10000
+#define CURLOPTTYPE_FUNCTIONPOINT 20000
+#define CURLOPTTYPE_OFF_T 30000
+#define CURLOPTTYPE_BLOB 40000
+
+/* *STRINGPOINT is an alias for OBJECTPOINT to allow tools to extract the
+ string options from the header file */
+
+
+#define CURLOPT(na,t,nu) na = t + nu
+
+/* CURLOPT aliases that make no run-time difference */
+
+/* 'char *' argument to a string with a trailing zero */
+#define CURLOPTTYPE_STRINGPOINT CURLOPTTYPE_OBJECTPOINT
+
+/* 'struct curl_slist *' argument */
+#define CURLOPTTYPE_SLISTPOINT CURLOPTTYPE_OBJECTPOINT
+
+/* 'void *' argument passed untouched to callback */
+#define CURLOPTTYPE_CBPOINT CURLOPTTYPE_OBJECTPOINT
+
+/* 'long' argument with a set of values/bitmask */
+#define CURLOPTTYPE_VALUES CURLOPTTYPE_LONG
+
+/*
+ * All CURLOPT_* values.
+ */
+
+typedef enum {
+ /* This is the FILE * or void * the regular output should be written to. */
+ CURLOPT(CURLOPT_WRITEDATA, CURLOPTTYPE_CBPOINT, 1),
+
+ /* The full URL to get/put */
+ CURLOPT(CURLOPT_URL, CURLOPTTYPE_STRINGPOINT, 2),
+
+ /* Port number to connect to, if other than default. */
+ CURLOPT(CURLOPT_PORT, CURLOPTTYPE_LONG, 3),
+
+ /* Name of proxy to use. */
+ CURLOPT(CURLOPT_PROXY, CURLOPTTYPE_STRINGPOINT, 4),
+
+ /* "user:password;options" to use when fetching. */
+ CURLOPT(CURLOPT_USERPWD, CURLOPTTYPE_STRINGPOINT, 5),
+
+ /* "user:password" to use with proxy. */
+ CURLOPT(CURLOPT_PROXYUSERPWD, CURLOPTTYPE_STRINGPOINT, 6),
+
+ /* Range to get, specified as an ASCII string. */
+ CURLOPT(CURLOPT_RANGE, CURLOPTTYPE_STRINGPOINT, 7),
+
+ /* not used */
+
+ /* Specified file stream to upload from (use as input): */
+ CURLOPT(CURLOPT_READDATA, CURLOPTTYPE_CBPOINT, 9),
+
+ /* Buffer to receive error messages in, must be at least CURL_ERROR_SIZE
+ * bytes big. */
+ CURLOPT(CURLOPT_ERRORBUFFER, CURLOPTTYPE_OBJECTPOINT, 10),
+
+ /* Function that will be called to store the output (instead of fwrite). The
+ * parameters will use fwrite() syntax, make sure to follow them. */
+ CURLOPT(CURLOPT_WRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 11),
+
+ /* Function that will be called to read the input (instead of fread). The
+ * parameters will use fread() syntax, make sure to follow them. */
+ CURLOPT(CURLOPT_READFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 12),
+
+ /* Time-out the read operation after this amount of seconds */
+ CURLOPT(CURLOPT_TIMEOUT, CURLOPTTYPE_LONG, 13),
+
+ /* If the CURLOPT_INFILE is used, this can be used to inform libcurl about
+ * how large the file being sent really is. That allows better error
+ * checking and better verifies that the upload was successful. -1 means
+ * unknown size.
+ *
+ * For large file support, there is also a _LARGE version of the key
+ * which takes an off_t type, allowing platforms with larger off_t
+ * sizes to handle larger files. See below for INFILESIZE_LARGE.
+ */
+ CURLOPT(CURLOPT_INFILESIZE, CURLOPTTYPE_LONG, 14),
+
+ /* POST static input fields. */
+ CURLOPT(CURLOPT_POSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 15),
+
+ /* Set the referrer page (needed by some CGIs) */
+ CURLOPT(CURLOPT_REFERER, CURLOPTTYPE_STRINGPOINT, 16),
+
+ /* Set the FTP PORT string (interface name, named or numerical IP address)
+ Use i.e '-' to use default address. */
+ CURLOPT(CURLOPT_FTPPORT, CURLOPTTYPE_STRINGPOINT, 17),
+
+ /* Set the User-Agent string (examined by some CGIs) */
+ CURLOPT(CURLOPT_USERAGENT, CURLOPTTYPE_STRINGPOINT, 18),
+
+ /* If the download receives less than "low speed limit" bytes/second
+ * during "low speed time" seconds, the operations is aborted.
+ * You could i.e if you have a pretty high speed connection, abort if
+ * it is less than 2000 bytes/sec during 20 seconds.
+ */
+
+ /* Set the "low speed limit" */
+ CURLOPT(CURLOPT_LOW_SPEED_LIMIT, CURLOPTTYPE_LONG, 19),
+
+ /* Set the "low speed time" */
+ CURLOPT(CURLOPT_LOW_SPEED_TIME, CURLOPTTYPE_LONG, 20),
+
+ /* Set the continuation offset.
+ *
+ * Note there is also a _LARGE version of this key which uses
+ * off_t types, allowing for large file offsets on platforms which
+ * use larger-than-32-bit off_t's. Look below for RESUME_FROM_LARGE.
+ */
+ CURLOPT(CURLOPT_RESUME_FROM, CURLOPTTYPE_LONG, 21),
+
+ /* Set cookie in request: */
+ CURLOPT(CURLOPT_COOKIE, CURLOPTTYPE_STRINGPOINT, 22),
+
+ /* This points to a linked list of headers, struct curl_slist kind. This
+ list is also used for RTSP (in spite of its name) */
+ CURLOPT(CURLOPT_HTTPHEADER, CURLOPTTYPE_SLISTPOINT, 23),
+
+ /* This points to a linked list of post entries, struct curl_httppost */
+ CURLOPT(CURLOPT_HTTPPOST, CURLOPTTYPE_OBJECTPOINT, 24),
+
+ /* name of the file keeping your private SSL-certificate */
+ CURLOPT(CURLOPT_SSLCERT, CURLOPTTYPE_STRINGPOINT, 25),
+
+ /* password for the SSL or SSH private key */
+ CURLOPT(CURLOPT_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 26),
+
+ /* send TYPE parameter? */
+ CURLOPT(CURLOPT_CRLF, CURLOPTTYPE_LONG, 27),
+
+ /* send linked-list of QUOTE commands */
+ CURLOPT(CURLOPT_QUOTE, CURLOPTTYPE_SLISTPOINT, 28),
+
+ /* send FILE * or void * to store headers to, if you use a callback it
+ is simply passed to the callback unmodified */
+ CURLOPT(CURLOPT_HEADERDATA, CURLOPTTYPE_CBPOINT, 29),
+
+ /* point to a file to read the initial cookies from, also enables
+ "cookie awareness" */
+ CURLOPT(CURLOPT_COOKIEFILE, CURLOPTTYPE_STRINGPOINT, 31),
+
+ /* What version to specifically try to use.
+ See CURL_SSLVERSION defines below. */
+ CURLOPT(CURLOPT_SSLVERSION, CURLOPTTYPE_VALUES, 32),
+
+ /* What kind of HTTP time condition to use, see defines */
+ CURLOPT(CURLOPT_TIMECONDITION, CURLOPTTYPE_VALUES, 33),
+
+ /* Time to use with the above condition. Specified in number of seconds
+ since 1 Jan 1970 */
+ CURLOPT(CURLOPT_TIMEVALUE, CURLOPTTYPE_LONG, 34),
+
+ /* 35 = OBSOLETE */
+
+ /* Custom request, for customizing the get command like
+ HTTP: DELETE, TRACE and others
+ FTP: to use a different list command
+ */
+ CURLOPT(CURLOPT_CUSTOMREQUEST, CURLOPTTYPE_STRINGPOINT, 36),
+
+ /* FILE handle to use instead of stderr */
+ CURLOPT(CURLOPT_STDERR, CURLOPTTYPE_OBJECTPOINT, 37),
+
+ /* 38 is not used */
+
+ /* send linked-list of post-transfer QUOTE commands */
+ CURLOPT(CURLOPT_POSTQUOTE, CURLOPTTYPE_SLISTPOINT, 39),
+
+ /* OBSOLETE, do not use! */
+ CURLOPT(CURLOPT_OBSOLETE40, CURLOPTTYPE_OBJECTPOINT, 40),
+
+ /* talk a lot */
+ CURLOPT(CURLOPT_VERBOSE, CURLOPTTYPE_LONG, 41),
+
+ /* throw the header out too */
+ CURLOPT(CURLOPT_HEADER, CURLOPTTYPE_LONG, 42),
+
+ /* shut off the progress meter */
+ CURLOPT(CURLOPT_NOPROGRESS, CURLOPTTYPE_LONG, 43),
+
+ /* use HEAD to get http document */
+ CURLOPT(CURLOPT_NOBODY, CURLOPTTYPE_LONG, 44),
+
+ /* no output on http error codes >= 400 */
+ CURLOPT(CURLOPT_FAILONERROR, CURLOPTTYPE_LONG, 45),
+
+ /* this is an upload */
+ CURLOPT(CURLOPT_UPLOAD, CURLOPTTYPE_LONG, 46),
+
+ /* HTTP POST method */
+ CURLOPT(CURLOPT_POST, CURLOPTTYPE_LONG, 47),
+
+ /* bare names when listing directories */
+ CURLOPT(CURLOPT_DIRLISTONLY, CURLOPTTYPE_LONG, 48),
+
+ /* Append instead of overwrite on upload! */
+ CURLOPT(CURLOPT_APPEND, CURLOPTTYPE_LONG, 50),
+
+ /* Specify whether to read the user+password from the .netrc or the URL.
+ * This must be one of the CURL_NETRC_* enums below. */
+ CURLOPT(CURLOPT_NETRC, CURLOPTTYPE_VALUES, 51),
+
+ /* use Location: Luke! */
+ CURLOPT(CURLOPT_FOLLOWLOCATION, CURLOPTTYPE_LONG, 52),
+
+ /* transfer data in text/ASCII format */
+ CURLOPT(CURLOPT_TRANSFERTEXT, CURLOPTTYPE_LONG, 53),
+
+ /* HTTP PUT */
+ CURLOPT(CURLOPT_PUT, CURLOPTTYPE_LONG, 54),
+
+ /* 55 = OBSOLETE */
+
+ /* DEPRECATED
+ * Function that will be called instead of the internal progress display
+ * function. This function should be defined as the curl_progress_callback
+ * prototype defines. */
+ CURLOPT(CURLOPT_PROGRESSFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 56),
+
+ /* Data passed to the CURLOPT_PROGRESSFUNCTION and CURLOPT_XFERINFOFUNCTION
+ callbacks */
+ CURLOPT(CURLOPT_XFERINFODATA, CURLOPTTYPE_CBPOINT, 57),
+#define CURLOPT_PROGRESSDATA CURLOPT_XFERINFODATA
+
+ /* We want the referrer field set automatically when following locations */
+ CURLOPT(CURLOPT_AUTOREFERER, CURLOPTTYPE_LONG, 58),
+
+ /* Port of the proxy, can be set in the proxy string as well with:
+ "[host]:[port]" */
+ CURLOPT(CURLOPT_PROXYPORT, CURLOPTTYPE_LONG, 59),
+
+ /* size of the POST input data, if strlen() is not good to use */
+ CURLOPT(CURLOPT_POSTFIELDSIZE, CURLOPTTYPE_LONG, 60),
+
+ /* tunnel non-http operations through a HTTP proxy */
+ CURLOPT(CURLOPT_HTTPPROXYTUNNEL, CURLOPTTYPE_LONG, 61),
+
+ /* Set the interface string to use as outgoing network interface */
+ CURLOPT(CURLOPT_INTERFACE, CURLOPTTYPE_STRINGPOINT, 62),
+
+ /* Set the krb4/5 security level, this also enables krb4/5 awareness. This
+ * is a string, 'clear', 'safe', 'confidential' or 'private'. If the string
+ * is set but doesn't match one of these, 'private' will be used. */
+ CURLOPT(CURLOPT_KRBLEVEL, CURLOPTTYPE_STRINGPOINT, 63),
+
+ /* Set if we should verify the peer in ssl handshake, set 1 to verify. */
+ CURLOPT(CURLOPT_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 64),
+
+ /* The CApath or CAfile used to validate the peer certificate
+ this option is used only if SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_CAINFO, CURLOPTTYPE_STRINGPOINT, 65),
+
+ /* 66 = OBSOLETE */
+ /* 67 = OBSOLETE */
+
+ /* Maximum number of http redirects to follow */
+ CURLOPT(CURLOPT_MAXREDIRS, CURLOPTTYPE_LONG, 68),
+
+ /* Pass a long set to 1 to get the date of the requested document (if
+ possible)! Pass a zero to shut it off. */
+ CURLOPT(CURLOPT_FILETIME, CURLOPTTYPE_LONG, 69),
+
+ /* This points to a linked list of telnet options */
+ CURLOPT(CURLOPT_TELNETOPTIONS, CURLOPTTYPE_SLISTPOINT, 70),
+
+ /* Max amount of cached alive connections */
+ CURLOPT(CURLOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 71),
+
+ /* OBSOLETE, do not use! */
+ CURLOPT(CURLOPT_OBSOLETE72, CURLOPTTYPE_LONG, 72),
+
+ /* 73 = OBSOLETE */
+
+ /* Set to explicitly use a new connection for the upcoming transfer.
+ Do not use this unless you're absolutely sure of this, as it makes the
+ operation slower and is less friendly for the network. */
+ CURLOPT(CURLOPT_FRESH_CONNECT, CURLOPTTYPE_LONG, 74),
+
+ /* Set to explicitly forbid the upcoming transfer's connection to be re-used
+ when done. Do not use this unless you're absolutely sure of this, as it
+ makes the operation slower and is less friendly for the network. */
+ CURLOPT(CURLOPT_FORBID_REUSE, CURLOPTTYPE_LONG, 75),
+
+ /* Set to a file name that contains random data for libcurl to use to
+ seed the random engine when doing SSL connects. */
+ CURLOPT(CURLOPT_RANDOM_FILE, CURLOPTTYPE_STRINGPOINT, 76),
+
+ /* Set to the Entropy Gathering Daemon socket pathname */
+ CURLOPT(CURLOPT_EGDSOCKET, CURLOPTTYPE_STRINGPOINT, 77),
+
+ /* Time-out connect operations after this amount of seconds, if connects are
+ OK within this time, then fine... This only aborts the connect phase. */
+ CURLOPT(CURLOPT_CONNECTTIMEOUT, CURLOPTTYPE_LONG, 78),
+
+ /* Function that will be called to store headers (instead of fwrite). The
+ * parameters will use fwrite() syntax, make sure to follow them. */
+ CURLOPT(CURLOPT_HEADERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 79),
+
+ /* Set this to force the HTTP request to get back to GET. Only really usable
+ if POST, PUT or a custom request have been used first.
+ */
+ CURLOPT(CURLOPT_HTTPGET, CURLOPTTYPE_LONG, 80),
+
+ /* Set if we should verify the Common name from the peer certificate in ssl
+ * handshake, set 1 to check existence, 2 to ensure that it matches the
+ * provided hostname. */
+ CURLOPT(CURLOPT_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 81),
+
+ /* Specify which file name to write all known cookies in after completed
+ operation. Set file name to "-" (dash) to make it go to stdout. */
+ CURLOPT(CURLOPT_COOKIEJAR, CURLOPTTYPE_STRINGPOINT, 82),
+
+ /* Specify which SSL ciphers to use */
+ CURLOPT(CURLOPT_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 83),
+
+ /* Specify which HTTP version to use! This must be set to one of the
+ CURL_HTTP_VERSION* enums set below. */
+ CURLOPT(CURLOPT_HTTP_VERSION, CURLOPTTYPE_VALUES, 84),
+
+ /* Specifically switch on or off the FTP engine's use of the EPSV command. By
+ default, that one will always be attempted before the more traditional
+ PASV command. */
+ CURLOPT(CURLOPT_FTP_USE_EPSV, CURLOPTTYPE_LONG, 85),
+
+ /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") */
+ CURLOPT(CURLOPT_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 86),
+
+ /* name of the file keeping your private SSL-key */
+ CURLOPT(CURLOPT_SSLKEY, CURLOPTTYPE_STRINGPOINT, 87),
+
+ /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") */
+ CURLOPT(CURLOPT_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 88),
+
+ /* crypto engine for the SSL-sub system */
+ CURLOPT(CURLOPT_SSLENGINE, CURLOPTTYPE_STRINGPOINT, 89),
+
+ /* set the crypto engine for the SSL-sub system as default
+ the param has no meaning...
+ */
+ CURLOPT(CURLOPT_SSLENGINE_DEFAULT, CURLOPTTYPE_LONG, 90),
+
+ /* Non-zero value means to use the global dns cache */
+ /* DEPRECATED, do not use! */
+ CURLOPT(CURLOPT_DNS_USE_GLOBAL_CACHE, CURLOPTTYPE_LONG, 91),
+
+ /* DNS cache timeout */
+ CURLOPT(CURLOPT_DNS_CACHE_TIMEOUT, CURLOPTTYPE_LONG, 92),
+
+ /* send linked-list of pre-transfer QUOTE commands */
+ CURLOPT(CURLOPT_PREQUOTE, CURLOPTTYPE_SLISTPOINT, 93),
+
+ /* set the debug function */
+ CURLOPT(CURLOPT_DEBUGFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 94),
+
+ /* set the data for the debug function */
+ CURLOPT(CURLOPT_DEBUGDATA, CURLOPTTYPE_CBPOINT, 95),
+
+ /* mark this as start of a cookie session */
+ CURLOPT(CURLOPT_COOKIESESSION, CURLOPTTYPE_LONG, 96),
+
+ /* The CApath directory used to validate the peer certificate
+ this option is used only if SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_CAPATH, CURLOPTTYPE_STRINGPOINT, 97),
+
+ /* Instruct libcurl to use a smaller receive buffer */
+ CURLOPT(CURLOPT_BUFFERSIZE, CURLOPTTYPE_LONG, 98),
+
+ /* Instruct libcurl to not use any signal/alarm handlers, even when using
+ timeouts. This option is useful for multi-threaded applications.
+ See libcurl-the-guide for more background information. */
+ CURLOPT(CURLOPT_NOSIGNAL, CURLOPTTYPE_LONG, 99),
+
+ /* Provide a CURLShare for mutexing non-ts data */
+ CURLOPT(CURLOPT_SHARE, CURLOPTTYPE_OBJECTPOINT, 100),
+
+ /* indicates type of proxy. accepted values are CURLPROXY_HTTP (default),
+ CURLPROXY_HTTPS, CURLPROXY_SOCKS4, CURLPROXY_SOCKS4A and
+ CURLPROXY_SOCKS5. */
+ CURLOPT(CURLOPT_PROXYTYPE, CURLOPTTYPE_VALUES, 101),
+
+ /* Set the Accept-Encoding string. Use this to tell a server you would like
+ the response to be compressed. Before 7.21.6, this was known as
+ CURLOPT_ENCODING */
+ CURLOPT(CURLOPT_ACCEPT_ENCODING, CURLOPTTYPE_STRINGPOINT, 102),
+
+ /* Set pointer to private data */
+ CURLOPT(CURLOPT_PRIVATE, CURLOPTTYPE_OBJECTPOINT, 103),
+
+ /* Set aliases for HTTP 200 in the HTTP Response header */
+ CURLOPT(CURLOPT_HTTP200ALIASES, CURLOPTTYPE_SLISTPOINT, 104),
+
+ /* Continue to send authentication (user+password) when following locations,
+ even when hostname changed. This can potentially send off the name
+ and password to whatever host the server decides. */
+ CURLOPT(CURLOPT_UNRESTRICTED_AUTH, CURLOPTTYPE_LONG, 105),
+
+ /* Specifically switch on or off the FTP engine's use of the EPRT command (
+ it also disables the LPRT attempt). By default, those ones will always be
+ attempted before the good old traditional PORT command. */
+ CURLOPT(CURLOPT_FTP_USE_EPRT, CURLOPTTYPE_LONG, 106),
+
+ /* Set this to a bitmask value to enable the particular authentications
+ methods you like. Use this in combination with CURLOPT_USERPWD.
+ Note that setting multiple bits may cause extra network round-trips. */
+ CURLOPT(CURLOPT_HTTPAUTH, CURLOPTTYPE_VALUES, 107),
+
+ /* Set the ssl context callback function, currently only for OpenSSL or
+ WolfSSL ssl_ctx, or mbedTLS mbedtls_ssl_config in the second argument.
+ The function must match the curl_ssl_ctx_callback prototype. */
+ CURLOPT(CURLOPT_SSL_CTX_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 108),
+
+ /* Set the userdata for the ssl context callback function's third
+ argument */
+ CURLOPT(CURLOPT_SSL_CTX_DATA, CURLOPTTYPE_CBPOINT, 109),
+
+ /* FTP Option that causes missing dirs to be created on the remote server.
+ In 7.19.4 we introduced the convenience enums for this option using the
+ CURLFTP_CREATE_DIR prefix.
+ */
+ CURLOPT(CURLOPT_FTP_CREATE_MISSING_DIRS, CURLOPTTYPE_LONG, 110),
+
+ /* Set this to a bitmask value to enable the particular authentications
+ methods you like. Use this in combination with CURLOPT_PROXYUSERPWD.
+ Note that setting multiple bits may cause extra network round-trips. */
+ CURLOPT(CURLOPT_PROXYAUTH, CURLOPTTYPE_VALUES, 111),
+
+ /* FTP option that changes the timeout, in seconds, associated with
+ getting a response. This is different from transfer timeout time and
+ essentially places a demand on the FTP server to acknowledge commands
+ in a timely manner. */
+ CURLOPT(CURLOPT_FTP_RESPONSE_TIMEOUT, CURLOPTTYPE_LONG, 112),
+#define CURLOPT_SERVER_RESPONSE_TIMEOUT CURLOPT_FTP_RESPONSE_TIMEOUT
+
+ /* Set this option to one of the CURL_IPRESOLVE_* defines (see below) to
+ tell libcurl to use those IP versions only. This only has effect on
+ systems with support for more than one, i.e IPv4 _and_ IPv6. */
+ CURLOPT(CURLOPT_IPRESOLVE, CURLOPTTYPE_VALUES, 113),
+
+ /* Set this option to limit the size of a file that will be downloaded from
+ an HTTP or FTP server.
+
+ Note there is also _LARGE version which adds large file support for
+ platforms which have larger off_t sizes. See MAXFILESIZE_LARGE below. */
+ CURLOPT(CURLOPT_MAXFILESIZE, CURLOPTTYPE_LONG, 114),
+
+ /* See the comment for INFILESIZE above, but in short, specifies
+ * the size of the file being uploaded. -1 means unknown.
+ */
+ CURLOPT(CURLOPT_INFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 115),
+
+ /* Sets the continuation offset. There is also a CURLOPTTYPE_LONG version
+ * of this; look above for RESUME_FROM.
+ */
+ CURLOPT(CURLOPT_RESUME_FROM_LARGE, CURLOPTTYPE_OFF_T, 116),
+
+ /* Sets the maximum size of data that will be downloaded from
+ * an HTTP or FTP server. See MAXFILESIZE above for the LONG version.
+ */
+ CURLOPT(CURLOPT_MAXFILESIZE_LARGE, CURLOPTTYPE_OFF_T, 117),
+
+ /* Set this option to the file name of your .netrc file you want libcurl
+ to parse (using the CURLOPT_NETRC option). If not set, libcurl will do
+ a poor attempt to find the user's home directory and check for a .netrc
+ file in there. */
+ CURLOPT(CURLOPT_NETRC_FILE, CURLOPTTYPE_STRINGPOINT, 118),
+
+ /* Enable SSL/TLS for FTP, pick one of:
+ CURLUSESSL_TRY - try using SSL, proceed anyway otherwise
+ CURLUSESSL_CONTROL - SSL for the control connection or fail
+ CURLUSESSL_ALL - SSL for all communication or fail
+ */
+ CURLOPT(CURLOPT_USE_SSL, CURLOPTTYPE_VALUES, 119),
+
+ /* The _LARGE version of the standard POSTFIELDSIZE option */
+ CURLOPT(CURLOPT_POSTFIELDSIZE_LARGE, CURLOPTTYPE_OFF_T, 120),
+
+ /* Enable/disable the TCP Nagle algorithm */
+ CURLOPT(CURLOPT_TCP_NODELAY, CURLOPTTYPE_LONG, 121),
+
+ /* 122 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 123 OBSOLETE. Gone in 7.16.0 */
+ /* 124 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 125 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 126 OBSOLETE, used in 7.12.3. Gone in 7.13.0 */
+ /* 127 OBSOLETE. Gone in 7.16.0 */
+ /* 128 OBSOLETE. Gone in 7.16.0 */
+
+ /* When FTP over SSL/TLS is selected (with CURLOPT_USE_SSL), this option
+ can be used to change libcurl's default action which is to first try
+ "AUTH SSL" and then "AUTH TLS" in this order, and proceed when a OK
+ response has been received.
+
+ Available parameters are:
+ CURLFTPAUTH_DEFAULT - let libcurl decide
+ CURLFTPAUTH_SSL - try "AUTH SSL" first, then TLS
+ CURLFTPAUTH_TLS - try "AUTH TLS" first, then SSL
+ */
+ CURLOPT(CURLOPT_FTPSSLAUTH, CURLOPTTYPE_VALUES, 129),
+
+ CURLOPT(CURLOPT_IOCTLFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 130),
+ CURLOPT(CURLOPT_IOCTLDATA, CURLOPTTYPE_CBPOINT, 131),
+
+ /* 132 OBSOLETE. Gone in 7.16.0 */
+ /* 133 OBSOLETE. Gone in 7.16.0 */
+
+ /* null-terminated string for pass on to the FTP server when asked for
+ "account" info */
+ CURLOPT(CURLOPT_FTP_ACCOUNT, CURLOPTTYPE_STRINGPOINT, 134),
+
+ /* feed cookie into cookie engine */
+ CURLOPT(CURLOPT_COOKIELIST, CURLOPTTYPE_STRINGPOINT, 135),
+
+ /* ignore Content-Length */
+ CURLOPT(CURLOPT_IGNORE_CONTENT_LENGTH, CURLOPTTYPE_LONG, 136),
+
+ /* Set to non-zero to skip the IP address received in a 227 PASV FTP server
+ response. Typically used for FTP-SSL purposes but is not restricted to
+ that. libcurl will then instead use the same IP address it used for the
+ control connection. */
+ CURLOPT(CURLOPT_FTP_SKIP_PASV_IP, CURLOPTTYPE_LONG, 137),
+
+ /* Select "file method" to use when doing FTP, see the curl_ftpmethod
+ above. */
+ CURLOPT(CURLOPT_FTP_FILEMETHOD, CURLOPTTYPE_VALUES, 138),
+
+ /* Local port number to bind the socket to */
+ CURLOPT(CURLOPT_LOCALPORT, CURLOPTTYPE_LONG, 139),
+
+ /* Number of ports to try, including the first one set with LOCALPORT.
+ Thus, setting it to 1 will make no additional attempts but the first.
+ */
+ CURLOPT(CURLOPT_LOCALPORTRANGE, CURLOPTTYPE_LONG, 140),
+
+ /* no transfer, set up connection and let application use the socket by
+ extracting it with CURLINFO_LASTSOCKET */
+ CURLOPT(CURLOPT_CONNECT_ONLY, CURLOPTTYPE_LONG, 141),
+
+ /* Function that will be called to convert from the
+ network encoding (instead of using the iconv calls in libcurl) */
+ CURLOPT(CURLOPT_CONV_FROM_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 142),
+
+ /* Function that will be called to convert to the
+ network encoding (instead of using the iconv calls in libcurl) */
+ CURLOPT(CURLOPT_CONV_TO_NETWORK_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 143),
+
+ /* Function that will be called to convert from UTF8
+ (instead of using the iconv calls in libcurl)
+ Note that this is used only for SSL certificate processing */
+ CURLOPT(CURLOPT_CONV_FROM_UTF8_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 144),
+
+ /* if the connection proceeds too quickly then need to slow it down */
+ /* limit-rate: maximum number of bytes per second to send or receive */
+ CURLOPT(CURLOPT_MAX_SEND_SPEED_LARGE, CURLOPTTYPE_OFF_T, 145),
+ CURLOPT(CURLOPT_MAX_RECV_SPEED_LARGE, CURLOPTTYPE_OFF_T, 146),
+
+ /* Pointer to command string to send if USER/PASS fails. */
+ CURLOPT(CURLOPT_FTP_ALTERNATIVE_TO_USER, CURLOPTTYPE_STRINGPOINT, 147),
+
+ /* callback function for setting socket options */
+ CURLOPT(CURLOPT_SOCKOPTFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 148),
+ CURLOPT(CURLOPT_SOCKOPTDATA, CURLOPTTYPE_CBPOINT, 149),
+
+ /* set to 0 to disable session ID re-use for this transfer, default is
+ enabled (== 1) */
+ CURLOPT(CURLOPT_SSL_SESSIONID_CACHE, CURLOPTTYPE_LONG, 150),
+
+ /* allowed SSH authentication methods */
+ CURLOPT(CURLOPT_SSH_AUTH_TYPES, CURLOPTTYPE_VALUES, 151),
+
+ /* Used by scp/sftp to do public/private key authentication */
+ CURLOPT(CURLOPT_SSH_PUBLIC_KEYFILE, CURLOPTTYPE_STRINGPOINT, 152),
+ CURLOPT(CURLOPT_SSH_PRIVATE_KEYFILE, CURLOPTTYPE_STRINGPOINT, 153),
+
+ /* Send CCC (Clear Command Channel) after authentication */
+ CURLOPT(CURLOPT_FTP_SSL_CCC, CURLOPTTYPE_LONG, 154),
+
+ /* Same as TIMEOUT and CONNECTTIMEOUT, but with ms resolution */
+ CURLOPT(CURLOPT_TIMEOUT_MS, CURLOPTTYPE_LONG, 155),
+ CURLOPT(CURLOPT_CONNECTTIMEOUT_MS, CURLOPTTYPE_LONG, 156),
+
+ /* set to zero to disable the libcurl's decoding and thus pass the raw body
+ data to the application even when it is encoded/compressed */
+ CURLOPT(CURLOPT_HTTP_TRANSFER_DECODING, CURLOPTTYPE_LONG, 157),
+ CURLOPT(CURLOPT_HTTP_CONTENT_DECODING, CURLOPTTYPE_LONG, 158),
+
+ /* Permission used when creating new files and directories on the remote
+ server for protocols that support it, SFTP/SCP/FILE */
+ CURLOPT(CURLOPT_NEW_FILE_PERMS, CURLOPTTYPE_LONG, 159),
+ CURLOPT(CURLOPT_NEW_DIRECTORY_PERMS, CURLOPTTYPE_LONG, 160),
+
+ /* Set the behavior of POST when redirecting. Values must be set to one
+ of CURL_REDIR* defines below. This used to be called CURLOPT_POST301 */
+ CURLOPT(CURLOPT_POSTREDIR, CURLOPTTYPE_VALUES, 161),
+
+ /* used by scp/sftp to verify the host's public key */
+ CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_MD5, CURLOPTTYPE_STRINGPOINT, 162),
+
+ /* Callback function for opening socket (instead of socket(2)). Optionally,
+ callback is able change the address or refuse to connect returning
+ CURL_SOCKET_BAD. The callback should have type
+ curl_opensocket_callback */
+ CURLOPT(CURLOPT_OPENSOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 163),
+ CURLOPT(CURLOPT_OPENSOCKETDATA, CURLOPTTYPE_CBPOINT, 164),
+
+ /* POST volatile input fields. */
+ CURLOPT(CURLOPT_COPYPOSTFIELDS, CURLOPTTYPE_OBJECTPOINT, 165),
+
+ /* set transfer mode (;type=<a|i>) when doing FTP via an HTTP proxy */
+ CURLOPT(CURLOPT_PROXY_TRANSFER_MODE, CURLOPTTYPE_LONG, 166),
+
+ /* Callback function for seeking in the input stream */
+ CURLOPT(CURLOPT_SEEKFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 167),
+ CURLOPT(CURLOPT_SEEKDATA, CURLOPTTYPE_CBPOINT, 168),
+
+ /* CRL file */
+ CURLOPT(CURLOPT_CRLFILE, CURLOPTTYPE_STRINGPOINT, 169),
+
+ /* Issuer certificate */
+ CURLOPT(CURLOPT_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 170),
+
+ /* (IPv6) Address scope */
+ CURLOPT(CURLOPT_ADDRESS_SCOPE, CURLOPTTYPE_LONG, 171),
+
+ /* Collect certificate chain info and allow it to get retrievable with
+ CURLINFO_CERTINFO after the transfer is complete. */
+ CURLOPT(CURLOPT_CERTINFO, CURLOPTTYPE_LONG, 172),
+
+ /* "name" and "pwd" to use when fetching. */
+ CURLOPT(CURLOPT_USERNAME, CURLOPTTYPE_STRINGPOINT, 173),
+ CURLOPT(CURLOPT_PASSWORD, CURLOPTTYPE_STRINGPOINT, 174),
+
+ /* "name" and "pwd" to use with Proxy when fetching. */
+ CURLOPT(CURLOPT_PROXYUSERNAME, CURLOPTTYPE_STRINGPOINT, 175),
+ CURLOPT(CURLOPT_PROXYPASSWORD, CURLOPTTYPE_STRINGPOINT, 176),
+
+ /* Comma separated list of hostnames defining no-proxy zones. These should
+ match both hostnames directly, and hostnames within a domain. For
+ example, local.com will match local.com and www.local.com, but NOT
+ notlocal.com or www.notlocal.com. For compatibility with other
+ implementations of this, .local.com will be considered to be the same as
+ local.com. A single * is the only valid wildcard, and effectively
+ disables the use of proxy. */
+ CURLOPT(CURLOPT_NOPROXY, CURLOPTTYPE_STRINGPOINT, 177),
+
+ /* block size for TFTP transfers */
+ CURLOPT(CURLOPT_TFTP_BLKSIZE, CURLOPTTYPE_LONG, 178),
+
+ /* Socks Service */
+ /* DEPRECATED, do not use! */
+ CURLOPT(CURLOPT_SOCKS5_GSSAPI_SERVICE, CURLOPTTYPE_STRINGPOINT, 179),
+
+ /* Socks Service */
+ CURLOPT(CURLOPT_SOCKS5_GSSAPI_NEC, CURLOPTTYPE_LONG, 180),
+
+ /* set the bitmask for the protocols that are allowed to be used for the
+ transfer, which thus helps the app which takes URLs from users or other
+ external inputs and want to restrict what protocol(s) to deal
+ with. Defaults to CURLPROTO_ALL. */
+ CURLOPT(CURLOPT_PROTOCOLS, CURLOPTTYPE_LONG, 181),
+
+ /* set the bitmask for the protocols that libcurl is allowed to follow to,
+ as a subset of the CURLOPT_PROTOCOLS ones. That means the protocol needs
+ to be set in both bitmasks to be allowed to get redirected to. */
+ CURLOPT(CURLOPT_REDIR_PROTOCOLS, CURLOPTTYPE_LONG, 182),
+
+ /* set the SSH knownhost file name to use */
+ CURLOPT(CURLOPT_SSH_KNOWNHOSTS, CURLOPTTYPE_STRINGPOINT, 183),
+
+ /* set the SSH host key callback, must point to a curl_sshkeycallback
+ function */
+ CURLOPT(CURLOPT_SSH_KEYFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 184),
+
+ /* set the SSH host key callback custom pointer */
+ CURLOPT(CURLOPT_SSH_KEYDATA, CURLOPTTYPE_CBPOINT, 185),
+
+ /* set the SMTP mail originator */
+ CURLOPT(CURLOPT_MAIL_FROM, CURLOPTTYPE_STRINGPOINT, 186),
+
+ /* set the list of SMTP mail receiver(s) */
+ CURLOPT(CURLOPT_MAIL_RCPT, CURLOPTTYPE_SLISTPOINT, 187),
+
+ /* FTP: send PRET before PASV */
+ CURLOPT(CURLOPT_FTP_USE_PRET, CURLOPTTYPE_LONG, 188),
+
+ /* RTSP request method (OPTIONS, SETUP, PLAY, etc...) */
+ CURLOPT(CURLOPT_RTSP_REQUEST, CURLOPTTYPE_VALUES, 189),
+
+ /* The RTSP session identifier */
+ CURLOPT(CURLOPT_RTSP_SESSION_ID, CURLOPTTYPE_STRINGPOINT, 190),
+
+ /* The RTSP stream URI */
+ CURLOPT(CURLOPT_RTSP_STREAM_URI, CURLOPTTYPE_STRINGPOINT, 191),
+
+ /* The Transport: header to use in RTSP requests */
+ CURLOPT(CURLOPT_RTSP_TRANSPORT, CURLOPTTYPE_STRINGPOINT, 192),
+
+ /* Manually initialize the client RTSP CSeq for this handle */
+ CURLOPT(CURLOPT_RTSP_CLIENT_CSEQ, CURLOPTTYPE_LONG, 193),
+
+ /* Manually initialize the server RTSP CSeq for this handle */
+ CURLOPT(CURLOPT_RTSP_SERVER_CSEQ, CURLOPTTYPE_LONG, 194),
+
+ /* The stream to pass to INTERLEAVEFUNCTION. */
+ CURLOPT(CURLOPT_INTERLEAVEDATA, CURLOPTTYPE_CBPOINT, 195),
+
+ /* Let the application define a custom write method for RTP data */
+ CURLOPT(CURLOPT_INTERLEAVEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 196),
+
+ /* Turn on wildcard matching */
+ CURLOPT(CURLOPT_WILDCARDMATCH, CURLOPTTYPE_LONG, 197),
+
+ /* Directory matching callback called before downloading of an
+ individual file (chunk) started */
+ CURLOPT(CURLOPT_CHUNK_BGN_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 198),
+
+ /* Directory matching callback called after the file (chunk)
+ was downloaded, or skipped */
+ CURLOPT(CURLOPT_CHUNK_END_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 199),
+
+ /* Change match (fnmatch-like) callback for wildcard matching */
+ CURLOPT(CURLOPT_FNMATCH_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 200),
+
+ /* Let the application define custom chunk data pointer */
+ CURLOPT(CURLOPT_CHUNK_DATA, CURLOPTTYPE_CBPOINT, 201),
+
+ /* FNMATCH_FUNCTION user pointer */
+ CURLOPT(CURLOPT_FNMATCH_DATA, CURLOPTTYPE_CBPOINT, 202),
+
+ /* send linked-list of name:port:address sets */
+ CURLOPT(CURLOPT_RESOLVE, CURLOPTTYPE_SLISTPOINT, 203),
+
+ /* Set a username for authenticated TLS */
+ CURLOPT(CURLOPT_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 204),
+
+ /* Set a password for authenticated TLS */
+ CURLOPT(CURLOPT_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 205),
+
+ /* Set authentication type for authenticated TLS */
+ CURLOPT(CURLOPT_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 206),
+
+ /* Set to 1 to enable the "TE:" header in HTTP requests to ask for
+ compressed transfer-encoded responses. Set to 0 to disable the use of TE:
+ in outgoing requests. The current default is 0, but it might change in a
+ future libcurl release.
+
+ libcurl will ask for the compressed methods it knows of, and if that
+ isn't any, it will not ask for transfer-encoding at all even if this
+ option is set to 1.
+
+ */
+ CURLOPT(CURLOPT_TRANSFER_ENCODING, CURLOPTTYPE_LONG, 207),
+
+ /* Callback function for closing socket (instead of close(2)). The callback
+ should have type curl_closesocket_callback */
+ CURLOPT(CURLOPT_CLOSESOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 208),
+ CURLOPT(CURLOPT_CLOSESOCKETDATA, CURLOPTTYPE_CBPOINT, 209),
+
+ /* allow GSSAPI credential delegation */
+ CURLOPT(CURLOPT_GSSAPI_DELEGATION, CURLOPTTYPE_VALUES, 210),
+
+ /* Set the name servers to use for DNS resolution */
+ CURLOPT(CURLOPT_DNS_SERVERS, CURLOPTTYPE_STRINGPOINT, 211),
+
+ /* Time-out accept operations (currently for FTP only) after this amount
+ of milliseconds. */
+ CURLOPT(CURLOPT_ACCEPTTIMEOUT_MS, CURLOPTTYPE_LONG, 212),
+
+ /* Set TCP keepalive */
+ CURLOPT(CURLOPT_TCP_KEEPALIVE, CURLOPTTYPE_LONG, 213),
+
+ /* non-universal keepalive knobs (Linux, AIX, HP-UX, more) */
+ CURLOPT(CURLOPT_TCP_KEEPIDLE, CURLOPTTYPE_LONG, 214),
+ CURLOPT(CURLOPT_TCP_KEEPINTVL, CURLOPTTYPE_LONG, 215),
+
+ /* Enable/disable specific SSL features with a bitmask, see CURLSSLOPT_* */
+ CURLOPT(CURLOPT_SSL_OPTIONS, CURLOPTTYPE_VALUES, 216),
+
+ /* Set the SMTP auth originator */
+ CURLOPT(CURLOPT_MAIL_AUTH, CURLOPTTYPE_STRINGPOINT, 217),
+
+ /* Enable/disable SASL initial response */
+ CURLOPT(CURLOPT_SASL_IR, CURLOPTTYPE_LONG, 218),
+
+ /* Function that will be called instead of the internal progress display
+ * function. This function should be defined as the curl_xferinfo_callback
+ * prototype defines. (Deprecates CURLOPT_PROGRESSFUNCTION) */
+ CURLOPT(CURLOPT_XFERINFOFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 219),
+
+ /* The XOAUTH2 bearer token */
+ CURLOPT(CURLOPT_XOAUTH2_BEARER, CURLOPTTYPE_STRINGPOINT, 220),
+
+ /* Set the interface string to use as outgoing network
+ * interface for DNS requests.
+ * Only supported by the c-ares DNS backend */
+ CURLOPT(CURLOPT_DNS_INTERFACE, CURLOPTTYPE_STRINGPOINT, 221),
+
+ /* Set the local IPv4 address to use for outgoing DNS requests.
+ * Only supported by the c-ares DNS backend */
+ CURLOPT(CURLOPT_DNS_LOCAL_IP4, CURLOPTTYPE_STRINGPOINT, 222),
+
+ /* Set the local IPv6 address to use for outgoing DNS requests.
+ * Only supported by the c-ares DNS backend */
+ CURLOPT(CURLOPT_DNS_LOCAL_IP6, CURLOPTTYPE_STRINGPOINT, 223),
+
+ /* Set authentication options directly */
+ CURLOPT(CURLOPT_LOGIN_OPTIONS, CURLOPTTYPE_STRINGPOINT, 224),
+
+ /* Enable/disable TLS NPN extension (http2 over ssl might fail without) */
+ CURLOPT(CURLOPT_SSL_ENABLE_NPN, CURLOPTTYPE_LONG, 225),
+
+ /* Enable/disable TLS ALPN extension (http2 over ssl might fail without) */
+ CURLOPT(CURLOPT_SSL_ENABLE_ALPN, CURLOPTTYPE_LONG, 226),
+
+ /* Time to wait for a response to a HTTP request containing an
+ * Expect: 100-continue header before sending the data anyway. */
+ CURLOPT(CURLOPT_EXPECT_100_TIMEOUT_MS, CURLOPTTYPE_LONG, 227),
+
+ /* This points to a linked list of headers used for proxy requests only,
+ struct curl_slist kind */
+ CURLOPT(CURLOPT_PROXYHEADER, CURLOPTTYPE_SLISTPOINT, 228),
+
+ /* Pass in a bitmask of "header options" */
+ CURLOPT(CURLOPT_HEADEROPT, CURLOPTTYPE_VALUES, 229),
+
+ /* The public key in DER form used to validate the peer public key
+ this option is used only if SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 230),
+
+ /* Path to Unix domain socket */
+ CURLOPT(CURLOPT_UNIX_SOCKET_PATH, CURLOPTTYPE_STRINGPOINT, 231),
+
+ /* Set if we should verify the certificate status. */
+ CURLOPT(CURLOPT_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 232),
+
+ /* Set if we should enable TLS false start. */
+ CURLOPT(CURLOPT_SSL_FALSESTART, CURLOPTTYPE_LONG, 233),
+
+ /* Do not squash dot-dot sequences */
+ CURLOPT(CURLOPT_PATH_AS_IS, CURLOPTTYPE_LONG, 234),
+
+ /* Proxy Service Name */
+ CURLOPT(CURLOPT_PROXY_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 235),
+
+ /* Service Name */
+ CURLOPT(CURLOPT_SERVICE_NAME, CURLOPTTYPE_STRINGPOINT, 236),
+
+ /* Wait/don't wait for pipe/mutex to clarify */
+ CURLOPT(CURLOPT_PIPEWAIT, CURLOPTTYPE_LONG, 237),
+
+ /* Set the protocol used when curl is given a URL without a protocol */
+ CURLOPT(CURLOPT_DEFAULT_PROTOCOL, CURLOPTTYPE_STRINGPOINT, 238),
+
+ /* Set stream weight, 1 - 256 (default is 16) */
+ CURLOPT(CURLOPT_STREAM_WEIGHT, CURLOPTTYPE_LONG, 239),
+
+ /* Set stream dependency on another CURL handle */
+ CURLOPT(CURLOPT_STREAM_DEPENDS, CURLOPTTYPE_OBJECTPOINT, 240),
+
+ /* Set E-xclusive stream dependency on another CURL handle */
+ CURLOPT(CURLOPT_STREAM_DEPENDS_E, CURLOPTTYPE_OBJECTPOINT, 241),
+
+ /* Do not send any tftp option requests to the server */
+ CURLOPT(CURLOPT_TFTP_NO_OPTIONS, CURLOPTTYPE_LONG, 242),
+
+ /* Linked-list of host:port:connect-to-host:connect-to-port,
+ overrides the URL's host:port (only for the network layer) */
+ CURLOPT(CURLOPT_CONNECT_TO, CURLOPTTYPE_SLISTPOINT, 243),
+
+ /* Set TCP Fast Open */
+ CURLOPT(CURLOPT_TCP_FASTOPEN, CURLOPTTYPE_LONG, 244),
+
+ /* Continue to send data if the server responds early with an
+ * HTTP status code >= 300 */
+ CURLOPT(CURLOPT_KEEP_SENDING_ON_ERROR, CURLOPTTYPE_LONG, 245),
+
+ /* The CApath or CAfile used to validate the proxy certificate
+ this option is used only if PROXY_SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_PROXY_CAINFO, CURLOPTTYPE_STRINGPOINT, 246),
+
+ /* The CApath directory used to validate the proxy certificate
+ this option is used only if PROXY_SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_PROXY_CAPATH, CURLOPTTYPE_STRINGPOINT, 247),
+
+ /* Set if we should verify the proxy in ssl handshake,
+ set 1 to verify. */
+ CURLOPT(CURLOPT_PROXY_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 248),
+
+ /* Set if we should verify the Common name from the proxy certificate in ssl
+ * handshake, set 1 to check existence, 2 to ensure that it matches
+ * the provided hostname. */
+ CURLOPT(CURLOPT_PROXY_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 249),
+
+ /* What version to specifically try to use for proxy.
+ See CURL_SSLVERSION defines below. */
+ CURLOPT(CURLOPT_PROXY_SSLVERSION, CURLOPTTYPE_VALUES, 250),
+
+ /* Set a username for authenticated TLS for proxy */
+ CURLOPT(CURLOPT_PROXY_TLSAUTH_USERNAME, CURLOPTTYPE_STRINGPOINT, 251),
+
+ /* Set a password for authenticated TLS for proxy */
+ CURLOPT(CURLOPT_PROXY_TLSAUTH_PASSWORD, CURLOPTTYPE_STRINGPOINT, 252),
+
+ /* Set authentication type for authenticated TLS for proxy */
+ CURLOPT(CURLOPT_PROXY_TLSAUTH_TYPE, CURLOPTTYPE_STRINGPOINT, 253),
+
+ /* name of the file keeping your private SSL-certificate for proxy */
+ CURLOPT(CURLOPT_PROXY_SSLCERT, CURLOPTTYPE_STRINGPOINT, 254),
+
+ /* type of the file keeping your SSL-certificate ("DER", "PEM", "ENG") for
+ proxy */
+ CURLOPT(CURLOPT_PROXY_SSLCERTTYPE, CURLOPTTYPE_STRINGPOINT, 255),
+
+ /* name of the file keeping your private SSL-key for proxy */
+ CURLOPT(CURLOPT_PROXY_SSLKEY, CURLOPTTYPE_STRINGPOINT, 256),
+
+ /* type of the file keeping your private SSL-key ("DER", "PEM", "ENG") for
+ proxy */
+ CURLOPT(CURLOPT_PROXY_SSLKEYTYPE, CURLOPTTYPE_STRINGPOINT, 257),
+
+ /* password for the SSL private key for proxy */
+ CURLOPT(CURLOPT_PROXY_KEYPASSWD, CURLOPTTYPE_STRINGPOINT, 258),
+
+ /* Specify which SSL ciphers to use for proxy */
+ CURLOPT(CURLOPT_PROXY_SSL_CIPHER_LIST, CURLOPTTYPE_STRINGPOINT, 259),
+
+ /* CRL file for proxy */
+ CURLOPT(CURLOPT_PROXY_CRLFILE, CURLOPTTYPE_STRINGPOINT, 260),
+
+ /* Enable/disable specific SSL features with a bitmask for proxy, see
+ CURLSSLOPT_* */
+ CURLOPT(CURLOPT_PROXY_SSL_OPTIONS, CURLOPTTYPE_LONG, 261),
+
+ /* Name of pre proxy to use. */
+ CURLOPT(CURLOPT_PRE_PROXY, CURLOPTTYPE_STRINGPOINT, 262),
+
+ /* The public key in DER form used to validate the proxy public key
+ this option is used only if PROXY_SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_PROXY_PINNEDPUBLICKEY, CURLOPTTYPE_STRINGPOINT, 263),
+
+ /* Path to an abstract Unix domain socket */
+ CURLOPT(CURLOPT_ABSTRACT_UNIX_SOCKET, CURLOPTTYPE_STRINGPOINT, 264),
+
+ /* Suppress proxy CONNECT response headers from user callbacks */
+ CURLOPT(CURLOPT_SUPPRESS_CONNECT_HEADERS, CURLOPTTYPE_LONG, 265),
+
+ /* The request target, instead of extracted from the URL */
+ CURLOPT(CURLOPT_REQUEST_TARGET, CURLOPTTYPE_STRINGPOINT, 266),
+
+ /* bitmask of allowed auth methods for connections to SOCKS5 proxies */
+ CURLOPT(CURLOPT_SOCKS5_AUTH, CURLOPTTYPE_LONG, 267),
+
+ /* Enable/disable SSH compression */
+ CURLOPT(CURLOPT_SSH_COMPRESSION, CURLOPTTYPE_LONG, 268),
+
+ /* Post MIME data. */
+ CURLOPT(CURLOPT_MIMEPOST, CURLOPTTYPE_OBJECTPOINT, 269),
+
+ /* Time to use with the CURLOPT_TIMECONDITION. Specified in number of
+ seconds since 1 Jan 1970. */
+ CURLOPT(CURLOPT_TIMEVALUE_LARGE, CURLOPTTYPE_OFF_T, 270),
+
+ /* Head start in milliseconds to give happy eyeballs. */
+ CURLOPT(CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS, CURLOPTTYPE_LONG, 271),
+
+ /* Function that will be called before a resolver request is made */
+ CURLOPT(CURLOPT_RESOLVER_START_FUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 272),
+
+ /* User data to pass to the resolver start callback. */
+ CURLOPT(CURLOPT_RESOLVER_START_DATA, CURLOPTTYPE_CBPOINT, 273),
+
+ /* send HAProxy PROXY protocol header? */
+ CURLOPT(CURLOPT_HAPROXYPROTOCOL, CURLOPTTYPE_LONG, 274),
+
+ /* shuffle addresses before use when DNS returns multiple */
+ CURLOPT(CURLOPT_DNS_SHUFFLE_ADDRESSES, CURLOPTTYPE_LONG, 275),
+
+ /* Specify which TLS 1.3 ciphers suites to use */
+ CURLOPT(CURLOPT_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 276),
+ CURLOPT(CURLOPT_PROXY_TLS13_CIPHERS, CURLOPTTYPE_STRINGPOINT, 277),
+
+ /* Disallow specifying username/login in URL. */
+ CURLOPT(CURLOPT_DISALLOW_USERNAME_IN_URL, CURLOPTTYPE_LONG, 278),
+
+ /* DNS-over-HTTPS URL */
+ CURLOPT(CURLOPT_DOH_URL, CURLOPTTYPE_STRINGPOINT, 279),
+
+ /* Preferred buffer size to use for uploads */
+ CURLOPT(CURLOPT_UPLOAD_BUFFERSIZE, CURLOPTTYPE_LONG, 280),
+
+ /* Time in ms between connection upkeep calls for long-lived connections. */
+ CURLOPT(CURLOPT_UPKEEP_INTERVAL_MS, CURLOPTTYPE_LONG, 281),
+
+ /* Specify URL using CURL URL API. */
+ CURLOPT(CURLOPT_CURLU, CURLOPTTYPE_OBJECTPOINT, 282),
+
+ /* add trailing data just after no more data is available */
+ CURLOPT(CURLOPT_TRAILERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 283),
+
+ /* pointer to be passed to HTTP_TRAILER_FUNCTION */
+ CURLOPT(CURLOPT_TRAILERDATA, CURLOPTTYPE_CBPOINT, 284),
+
+ /* set this to 1L to allow HTTP/0.9 responses or 0L to disallow */
+ CURLOPT(CURLOPT_HTTP09_ALLOWED, CURLOPTTYPE_LONG, 285),
+
+ /* alt-svc control bitmask */
+ CURLOPT(CURLOPT_ALTSVC_CTRL, CURLOPTTYPE_LONG, 286),
+
+ /* alt-svc cache file name to possibly read from/write to */
+ CURLOPT(CURLOPT_ALTSVC, CURLOPTTYPE_STRINGPOINT, 287),
+
+ /* maximum age (idle time) of a connection to consider it for reuse
+ * (in seconds) */
+ CURLOPT(CURLOPT_MAXAGE_CONN, CURLOPTTYPE_LONG, 288),
+
+ /* SASL authorisation identity */
+ CURLOPT(CURLOPT_SASL_AUTHZID, CURLOPTTYPE_STRINGPOINT, 289),
+
+ /* allow RCPT TO command to fail for some recipients */
+ CURLOPT(CURLOPT_MAIL_RCPT_ALLLOWFAILS, CURLOPTTYPE_LONG, 290),
+
+ /* the private SSL-certificate as a "blob" */
+ CURLOPT(CURLOPT_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 291),
+ CURLOPT(CURLOPT_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 292),
+ CURLOPT(CURLOPT_PROXY_SSLCERT_BLOB, CURLOPTTYPE_BLOB, 293),
+ CURLOPT(CURLOPT_PROXY_SSLKEY_BLOB, CURLOPTTYPE_BLOB, 294),
+ CURLOPT(CURLOPT_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 295),
+
+ /* Issuer certificate for proxy */
+ CURLOPT(CURLOPT_PROXY_ISSUERCERT, CURLOPTTYPE_STRINGPOINT, 296),
+ CURLOPT(CURLOPT_PROXY_ISSUERCERT_BLOB, CURLOPTTYPE_BLOB, 297),
+
+ /* the EC curves requested by the TLS client (RFC 8422, 5.1);
+ * OpenSSL support via 'set_groups'/'set_curves':
+ * https://www.openssl.org/docs/manmaster/man3/SSL_CTX_set1_groups.html
+ */
+ CURLOPT(CURLOPT_SSL_EC_CURVES, CURLOPTTYPE_STRINGPOINT, 298),
+
+ /* HSTS bitmask */
+ CURLOPT(CURLOPT_HSTS_CTRL, CURLOPTTYPE_LONG, 299),
+ /* HSTS file name */
+ CURLOPT(CURLOPT_HSTS, CURLOPTTYPE_STRINGPOINT, 300),
+
+ /* HSTS read callback */
+ CURLOPT(CURLOPT_HSTSREADFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 301),
+ CURLOPT(CURLOPT_HSTSREADDATA, CURLOPTTYPE_CBPOINT, 302),
+
+ /* HSTS write callback */
+ CURLOPT(CURLOPT_HSTSWRITEFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 303),
+ CURLOPT(CURLOPT_HSTSWRITEDATA, CURLOPTTYPE_CBPOINT, 304),
+
+ /* Parameters for V4 signature */
+ CURLOPT(CURLOPT_AWS_SIGV4, CURLOPTTYPE_STRINGPOINT, 305),
+
+ /* Same as CURLOPT_SSL_VERIFYPEER but for DoH (DNS-over-HTTPS) servers. */
+ CURLOPT(CURLOPT_DOH_SSL_VERIFYPEER, CURLOPTTYPE_LONG, 306),
+
+ /* Same as CURLOPT_SSL_VERIFYHOST but for DoH (DNS-over-HTTPS) servers. */
+ CURLOPT(CURLOPT_DOH_SSL_VERIFYHOST, CURLOPTTYPE_LONG, 307),
+
+ /* Same as CURLOPT_SSL_VERIFYSTATUS but for DoH (DNS-over-HTTPS) servers. */
+ CURLOPT(CURLOPT_DOH_SSL_VERIFYSTATUS, CURLOPTTYPE_LONG, 308),
+
+ /* The CA certificates as "blob" used to validate the peer certificate
+ this option is used only if SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_CAINFO_BLOB, CURLOPTTYPE_BLOB, 309),
+
+ /* The CA certificates as "blob" used to validate the proxy certificate
+ this option is used only if PROXY_SSL_VERIFYPEER is true */
+ CURLOPT(CURLOPT_PROXY_CAINFO_BLOB, CURLOPTTYPE_BLOB, 310),
+
+ /* used by scp/sftp to verify the host's public key */
+ CURLOPT(CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256, CURLOPTTYPE_STRINGPOINT, 311),
+
+ /* Function that will be called immediately before the initial request
+ is made on a connection (after any protocol negotiation step). */
+ CURLOPT(CURLOPT_PREREQFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 312),
+
+ /* Data passed to the CURLOPT_PREREQFUNCTION callback */
+ CURLOPT(CURLOPT_PREREQDATA, CURLOPTTYPE_CBPOINT, 313),
+
+ /* maximum age (since creation) of a connection to consider it for reuse
+ * (in seconds) */
+ CURLOPT(CURLOPT_MAXLIFETIME_CONN, CURLOPTTYPE_LONG, 314),
+
+ /* Set MIME option flags. */
+ CURLOPT(CURLOPT_MIME_OPTIONS, CURLOPTTYPE_LONG, 315),
+
+ CURLOPT_LASTENTRY /* the last unused */
+} CURLoption;
+
+#ifndef CURL_NO_OLDIES /* define this to test if your app builds with all
+ the obsolete stuff removed! */
+
+/* Backwards compatibility with older names */
+/* These are scheduled to disappear by 2011 */
+
+/* This was added in version 7.19.1 */
+#define CURLOPT_POST301 CURLOPT_POSTREDIR
+
+/* These are scheduled to disappear by 2009 */
+
+/* The following were added in 7.17.0 */
+#define CURLOPT_SSLKEYPASSWD CURLOPT_KEYPASSWD
+#define CURLOPT_FTPAPPEND CURLOPT_APPEND
+#define CURLOPT_FTPLISTONLY CURLOPT_DIRLISTONLY
+#define CURLOPT_FTP_SSL CURLOPT_USE_SSL
+
+/* The following were added earlier */
+
+#define CURLOPT_SSLCERTPASSWD CURLOPT_KEYPASSWD
+#define CURLOPT_KRB4LEVEL CURLOPT_KRBLEVEL
+
+#else
+/* This is set if CURL_NO_OLDIES is defined at compile-time */
+#undef CURLOPT_DNS_USE_GLOBAL_CACHE /* soon obsolete */
+#endif
+
+
+ /* Below here follows defines for the CURLOPT_IPRESOLVE option. If a host
+ name resolves addresses using more than one IP protocol version, this
+ option might be handy to force libcurl to use a specific IP version. */
+#define CURL_IPRESOLVE_WHATEVER 0 /* default, uses addresses to all IP
+ versions that your system allows */
+#define CURL_IPRESOLVE_V4 1 /* uses only IPv4 addresses/connections */
+#define CURL_IPRESOLVE_V6 2 /* uses only IPv6 addresses/connections */
+
+ /* three convenient "aliases" that follow the name scheme better */
+#define CURLOPT_RTSPHEADER CURLOPT_HTTPHEADER
+
+ /* These enums are for use with the CURLOPT_HTTP_VERSION option. */
+enum {
+ CURL_HTTP_VERSION_NONE, /* setting this means we don't care, and that we'd
+ like the library to choose the best possible
+ for us! */
+ CURL_HTTP_VERSION_1_0, /* please use HTTP 1.0 in the request */
+ CURL_HTTP_VERSION_1_1, /* please use HTTP 1.1 in the request */
+ CURL_HTTP_VERSION_2_0, /* please use HTTP 2 in the request */
+ CURL_HTTP_VERSION_2TLS, /* use version 2 for HTTPS, version 1.1 for HTTP */
+ CURL_HTTP_VERSION_2_PRIOR_KNOWLEDGE, /* please use HTTP 2 without HTTP/1.1
+ Upgrade */
+ CURL_HTTP_VERSION_3 = 30, /* Makes use of explicit HTTP/3 without fallback.
+ Use CURLOPT_ALTSVC to enable HTTP/3 upgrade */
+ CURL_HTTP_VERSION_LAST /* *ILLEGAL* http version */
+};
+
+/* Convenience definition simple because the name of the version is HTTP/2 and
+ not 2.0. The 2_0 version of the enum name was set while the version was
+ still planned to be 2.0 and we stick to it for compatibility. */
+#define CURL_HTTP_VERSION_2 CURL_HTTP_VERSION_2_0
+
+/*
+ * Public API enums for RTSP requests
+ */
+enum {
+ CURL_RTSPREQ_NONE, /* first in list */
+ CURL_RTSPREQ_OPTIONS,
+ CURL_RTSPREQ_DESCRIBE,
+ CURL_RTSPREQ_ANNOUNCE,
+ CURL_RTSPREQ_SETUP,
+ CURL_RTSPREQ_PLAY,
+ CURL_RTSPREQ_PAUSE,
+ CURL_RTSPREQ_TEARDOWN,
+ CURL_RTSPREQ_GET_PARAMETER,
+ CURL_RTSPREQ_SET_PARAMETER,
+ CURL_RTSPREQ_RECORD,
+ CURL_RTSPREQ_RECEIVE,
+ CURL_RTSPREQ_LAST /* last in list */
+};
+
+ /* These enums are for use with the CURLOPT_NETRC option. */
+enum CURL_NETRC_OPTION {
+ CURL_NETRC_IGNORED, /* The .netrc will never be read.
+ * This is the default. */
+ CURL_NETRC_OPTIONAL, /* A user:password in the URL will be preferred
+ * to one in the .netrc. */
+ CURL_NETRC_REQUIRED, /* A user:password in the URL will be ignored.
+ * Unless one is set programmatically, the .netrc
+ * will be queried. */
+ CURL_NETRC_LAST
+};
+
+enum {
+ CURL_SSLVERSION_DEFAULT,
+ CURL_SSLVERSION_TLSv1, /* TLS 1.x */
+ CURL_SSLVERSION_SSLv2,
+ CURL_SSLVERSION_SSLv3,
+ CURL_SSLVERSION_TLSv1_0,
+ CURL_SSLVERSION_TLSv1_1,
+ CURL_SSLVERSION_TLSv1_2,
+ CURL_SSLVERSION_TLSv1_3,
+
+ CURL_SSLVERSION_LAST /* never use, keep last */
+};
+
+enum {
+ CURL_SSLVERSION_MAX_NONE = 0,
+ CURL_SSLVERSION_MAX_DEFAULT = (CURL_SSLVERSION_TLSv1 << 16),
+ CURL_SSLVERSION_MAX_TLSv1_0 = (CURL_SSLVERSION_TLSv1_0 << 16),
+ CURL_SSLVERSION_MAX_TLSv1_1 = (CURL_SSLVERSION_TLSv1_1 << 16),
+ CURL_SSLVERSION_MAX_TLSv1_2 = (CURL_SSLVERSION_TLSv1_2 << 16),
+ CURL_SSLVERSION_MAX_TLSv1_3 = (CURL_SSLVERSION_TLSv1_3 << 16),
+
+ /* never use, keep last */
+ CURL_SSLVERSION_MAX_LAST = (CURL_SSLVERSION_LAST << 16)
+};
+
+enum CURL_TLSAUTH {
+ CURL_TLSAUTH_NONE,
+ CURL_TLSAUTH_SRP,
+ CURL_TLSAUTH_LAST /* never use, keep last */
+};
+
+/* symbols to use with CURLOPT_POSTREDIR.
+ CURL_REDIR_POST_301, CURL_REDIR_POST_302 and CURL_REDIR_POST_303
+ can be bitwise ORed so that CURL_REDIR_POST_301 | CURL_REDIR_POST_302
+ | CURL_REDIR_POST_303 == CURL_REDIR_POST_ALL */
+
+#define CURL_REDIR_GET_ALL 0
+#define CURL_REDIR_POST_301 1
+#define CURL_REDIR_POST_302 2
+#define CURL_REDIR_POST_303 4
+#define CURL_REDIR_POST_ALL \
+ (CURL_REDIR_POST_301|CURL_REDIR_POST_302|CURL_REDIR_POST_303)
+
+typedef enum {
+ CURL_TIMECOND_NONE,
+
+ CURL_TIMECOND_IFMODSINCE,
+ CURL_TIMECOND_IFUNMODSINCE,
+ CURL_TIMECOND_LASTMOD,
+
+ CURL_TIMECOND_LAST
+} curl_TimeCond;
+
+/* Special size_t value signaling a null-terminated string. */
+#define CURL_ZERO_TERMINATED ((size_t) -1)
+
+/* curl_strequal() and curl_strnequal() are subject for removal in a future
+ release */
+CURL_EXTERN int curl_strequal(const char *s1, const char *s2);
+CURL_EXTERN int curl_strnequal(const char *s1, const char *s2, size_t n);
+
+/* Mime/form handling support. */
+typedef struct curl_mime curl_mime; /* Mime context. */
+typedef struct curl_mimepart curl_mimepart; /* Mime part context. */
+
+/* CURLMIMEOPT_ defines are for the CURLOPT_MIME_OPTIONS option. */
+#define CURLMIMEOPT_FORMESCAPE (1<<0) /* Use backslash-escaping for forms. */
+
+/*
+ * NAME curl_mime_init()
+ *
+ * DESCRIPTION
+ *
+ * Create a mime context and return its handle. The easy parameter is the
+ * target handle.
+ */
+CURL_EXTERN curl_mime *curl_mime_init(CURL *easy);
+
+/*
+ * NAME curl_mime_free()
+ *
+ * DESCRIPTION
+ *
+ * release a mime handle and its substructures.
+ */
+CURL_EXTERN void curl_mime_free(curl_mime *mime);
+
+/*
+ * NAME curl_mime_addpart()
+ *
+ * DESCRIPTION
+ *
+ * Append a new empty part to the given mime context and return a handle to
+ * the created part.
+ */
+CURL_EXTERN curl_mimepart *curl_mime_addpart(curl_mime *mime);
+
+/*
+ * NAME curl_mime_name()
+ *
+ * DESCRIPTION
+ *
+ * Set mime/form part name.
+ */
+CURL_EXTERN CURLcode curl_mime_name(curl_mimepart *part, const char *name);
+
+/*
+ * NAME curl_mime_filename()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part remote file name.
+ */
+CURL_EXTERN CURLcode curl_mime_filename(curl_mimepart *part,
+ const char *filename);
+
+/*
+ * NAME curl_mime_type()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part type.
+ */
+CURL_EXTERN CURLcode curl_mime_type(curl_mimepart *part, const char *mimetype);
+
+/*
+ * NAME curl_mime_encoder()
+ *
+ * DESCRIPTION
+ *
+ * Set mime data transfer encoder.
+ */
+CURL_EXTERN CURLcode curl_mime_encoder(curl_mimepart *part,
+ const char *encoding);
+
+/*
+ * NAME curl_mime_data()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from memory data,
+ */
+CURL_EXTERN CURLcode curl_mime_data(curl_mimepart *part,
+ const char *data, size_t datasize);
+
+/*
+ * NAME curl_mime_filedata()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from named file.
+ */
+CURL_EXTERN CURLcode curl_mime_filedata(curl_mimepart *part,
+ const char *filename);
+
+/*
+ * NAME curl_mime_data_cb()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from callback function.
+ */
+CURL_EXTERN CURLcode curl_mime_data_cb(curl_mimepart *part,
+ curl_off_t datasize,
+ curl_read_callback readfunc,
+ curl_seek_callback seekfunc,
+ curl_free_callback freefunc,
+ void *arg);
+
+/*
+ * NAME curl_mime_subparts()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part data source from subparts.
+ */
+CURL_EXTERN CURLcode curl_mime_subparts(curl_mimepart *part,
+ curl_mime *subparts);
+/*
+ * NAME curl_mime_headers()
+ *
+ * DESCRIPTION
+ *
+ * Set mime part headers.
+ */
+CURL_EXTERN CURLcode curl_mime_headers(curl_mimepart *part,
+ struct curl_slist *headers,
+ int take_ownership);
+
+typedef enum {
+ CURLFORM_NOTHING, /********* the first one is unused ************/
+ CURLFORM_COPYNAME,
+ CURLFORM_PTRNAME,
+ CURLFORM_NAMELENGTH,
+ CURLFORM_COPYCONTENTS,
+ CURLFORM_PTRCONTENTS,
+ CURLFORM_CONTENTSLENGTH,
+ CURLFORM_FILECONTENT,
+ CURLFORM_ARRAY,
+ CURLFORM_OBSOLETE,
+ CURLFORM_FILE,
+
+ CURLFORM_BUFFER,
+ CURLFORM_BUFFERPTR,
+ CURLFORM_BUFFERLENGTH,
+
+ CURLFORM_CONTENTTYPE,
+ CURLFORM_CONTENTHEADER,
+ CURLFORM_FILENAME,
+ CURLFORM_END,
+ CURLFORM_OBSOLETE2,
+
+ CURLFORM_STREAM,
+ CURLFORM_CONTENTLEN, /* added in 7.46.0, provide a curl_off_t length */
+
+ CURLFORM_LASTENTRY /* the last unused */
+} CURLformoption;
+
+/* structure to be used as parameter for CURLFORM_ARRAY */
+struct curl_forms {
+ CURLformoption option;
+ const char *value;
+};
+
+/* use this for multipart formpost building */
+/* Returns code for curl_formadd()
+ *
+ * Returns:
+ * CURL_FORMADD_OK on success
+ * CURL_FORMADD_MEMORY if the FormInfo allocation fails
+ * CURL_FORMADD_OPTION_TWICE if one option is given twice for one Form
+ * CURL_FORMADD_NULL if a null pointer was given for a char
+ * CURL_FORMADD_MEMORY if the allocation of a FormInfo struct failed
+ * CURL_FORMADD_UNKNOWN_OPTION if an unknown option was used
+ * CURL_FORMADD_INCOMPLETE if the some FormInfo is not complete (or error)
+ * CURL_FORMADD_MEMORY if a curl_httppost struct cannot be allocated
+ * CURL_FORMADD_MEMORY if some allocation for string copying failed.
+ * CURL_FORMADD_ILLEGAL_ARRAY if an illegal option is used in an array
+ *
+ ***************************************************************************/
+typedef enum {
+ CURL_FORMADD_OK, /* first, no error */
+
+ CURL_FORMADD_MEMORY,
+ CURL_FORMADD_OPTION_TWICE,
+ CURL_FORMADD_NULL,
+ CURL_FORMADD_UNKNOWN_OPTION,
+ CURL_FORMADD_INCOMPLETE,
+ CURL_FORMADD_ILLEGAL_ARRAY,
+ CURL_FORMADD_DISABLED, /* libcurl was built with this disabled */
+
+ CURL_FORMADD_LAST /* last */
+} CURLFORMcode;
+
+/*
+ * NAME curl_formadd()
+ *
+ * DESCRIPTION
+ *
+ * Pretty advanced function for building multi-part formposts. Each invoke
+ * adds one part that together construct a full post. Then use
+ * CURLOPT_HTTPPOST to send it off to libcurl.
+ */
+CURL_EXTERN CURLFORMcode curl_formadd(struct curl_httppost **httppost,
+ struct curl_httppost **last_post,
+ ...);
+
+/*
+ * callback function for curl_formget()
+ * The void *arg pointer will be the one passed as second argument to
+ * curl_formget().
+ * The character buffer passed to it must not be freed.
+ * Should return the buffer length passed to it as the argument "len" on
+ * success.
+ */
+typedef size_t (*curl_formget_callback)(void *arg, const char *buf,
+ size_t len);
+
+/*
+ * NAME curl_formget()
+ *
+ * DESCRIPTION
+ *
+ * Serialize a curl_httppost struct built with curl_formadd().
+ * Accepts a void pointer as second argument which will be passed to
+ * the curl_formget_callback function.
+ * Returns 0 on success.
+ */
+CURL_EXTERN int curl_formget(struct curl_httppost *form, void *arg,
+ curl_formget_callback append);
+/*
+ * NAME curl_formfree()
+ *
+ * DESCRIPTION
+ *
+ * Free a multipart formpost previously built with curl_formadd().
+ */
+CURL_EXTERN void curl_formfree(struct curl_httppost *form);
+
+/*
+ * NAME curl_getenv()
+ *
+ * DESCRIPTION
+ *
+ * Returns a malloc()'ed string that MUST be curl_free()ed after usage is
+ * complete. DEPRECATED - see lib/README.curlx
+ */
+CURL_EXTERN char *curl_getenv(const char *variable);
+
+/*
+ * NAME curl_version()
+ *
+ * DESCRIPTION
+ *
+ * Returns a static ascii string of the libcurl version.
+ */
+CURL_EXTERN char *curl_version(void);
+
+/*
+ * NAME curl_easy_escape()
+ *
+ * DESCRIPTION
+ *
+ * Escapes URL strings (converts all letters consider illegal in URLs to their
+ * %XX versions). This function returns a new allocated string or NULL if an
+ * error occurred.
+ */
+CURL_EXTERN char *curl_easy_escape(CURL *handle,
+ const char *string,
+ int length);
+
+/* the previous version: */
+CURL_EXTERN char *curl_escape(const char *string,
+ int length);
+
+
+/*
+ * NAME curl_easy_unescape()
+ *
+ * DESCRIPTION
+ *
+ * Unescapes URL encoding in strings (converts all %XX codes to their 8bit
+ * versions). This function returns a new allocated string or NULL if an error
+ * occurred.
+ * Conversion Note: On non-ASCII platforms the ASCII %XX codes are
+ * converted into the host encoding.
+ */
+CURL_EXTERN char *curl_easy_unescape(CURL *handle,
+ const char *string,
+ int length,
+ int *outlength);
+
+/* the previous version */
+CURL_EXTERN char *curl_unescape(const char *string,
+ int length);
+
+/*
+ * NAME curl_free()
+ *
+ * DESCRIPTION
+ *
+ * Provided for de-allocation in the same translation unit that did the
+ * allocation. Added in libcurl 7.10
+ */
+CURL_EXTERN void curl_free(void *p);
+
+/*
+ * NAME curl_global_init()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_init() should be invoked exactly once for each application that
+ * uses libcurl and before any call of other libcurl functions.
+ *
+ * This function is not thread-safe!
+ */
+CURL_EXTERN CURLcode curl_global_init(long flags);
+
+/*
+ * NAME curl_global_init_mem()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_init() or curl_global_init_mem() should be invoked exactly once
+ * for each application that uses libcurl. This function can be used to
+ * initialize libcurl and set user defined memory management callback
+ * functions. Users can implement memory management routines to check for
+ * memory leaks, check for mis-use of the curl library etc. User registered
+ * callback routines will be invoked by this library instead of the system
+ * memory management routines like malloc, free etc.
+ */
+CURL_EXTERN CURLcode curl_global_init_mem(long flags,
+ curl_malloc_callback m,
+ curl_free_callback f,
+ curl_realloc_callback r,
+ curl_strdup_callback s,
+ curl_calloc_callback c);
+
+/*
+ * NAME curl_global_cleanup()
+ *
+ * DESCRIPTION
+ *
+ * curl_global_cleanup() should be invoked exactly once for each application
+ * that uses libcurl
+ */
+CURL_EXTERN void curl_global_cleanup(void);
+
+/* linked-list structure for the CURLOPT_QUOTE option (and other) */
+struct curl_slist {
+ char *data;
+ struct curl_slist *next;
+};
+
+/*
+ * NAME curl_global_sslset()
+ *
+ * DESCRIPTION
+ *
+ * When built with multiple SSL backends, curl_global_sslset() allows to
+ * choose one. This function can only be called once, and it must be called
+ * *before* curl_global_init().
+ *
+ * The backend can be identified by the id (e.g. CURLSSLBACKEND_OPENSSL). The
+ * backend can also be specified via the name parameter (passing -1 as id).
+ * If both id and name are specified, the name will be ignored. If neither id
+ * nor name are specified, the function will fail with
+ * CURLSSLSET_UNKNOWN_BACKEND and set the "avail" pointer to the
+ * NULL-terminated list of available backends.
+ *
+ * Upon success, the function returns CURLSSLSET_OK.
+ *
+ * If the specified SSL backend is not available, the function returns
+ * CURLSSLSET_UNKNOWN_BACKEND and sets the "avail" pointer to a NULL-terminated
+ * list of available SSL backends.
+ *
+ * The SSL backend can be set only once. If it has already been set, a
+ * subsequent attempt to change it will result in a CURLSSLSET_TOO_LATE.
+ */
+
+struct curl_ssl_backend {
+ curl_sslbackend id;
+ const char *name;
+};
+typedef struct curl_ssl_backend curl_ssl_backend;
+
+typedef enum {
+ CURLSSLSET_OK = 0,
+ CURLSSLSET_UNKNOWN_BACKEND,
+ CURLSSLSET_TOO_LATE,
+ CURLSSLSET_NO_BACKENDS /* libcurl was built without any SSL support */
+} CURLsslset;
+
+CURL_EXTERN CURLsslset curl_global_sslset(curl_sslbackend id, const char *name,
+ const curl_ssl_backend ***avail);
+
+/*
+ * NAME curl_slist_append()
+ *
+ * DESCRIPTION
+ *
+ * Appends a string to a linked list. If no list exists, it will be created
+ * first. Returns the new list, after appending.
+ */
+CURL_EXTERN struct curl_slist *curl_slist_append(struct curl_slist *,
+ const char *);
+
+/*
+ * NAME curl_slist_free_all()
+ *
+ * DESCRIPTION
+ *
+ * free a previously built curl_slist.
+ */
+CURL_EXTERN void curl_slist_free_all(struct curl_slist *);
+
+/*
+ * NAME curl_getdate()
+ *
+ * DESCRIPTION
+ *
+ * Returns the time, in seconds since 1 Jan 1970 of the time string given in
+ * the first argument. The time argument in the second parameter is unused
+ * and should be set to NULL.
+ */
+CURL_EXTERN time_t curl_getdate(const char *p, const time_t *unused);
+
+/* info about the certificate chain, only for OpenSSL, GnuTLS, Schannel, NSS
+ and GSKit builds. Asked for with CURLOPT_CERTINFO / CURLINFO_CERTINFO */
+struct curl_certinfo {
+ int num_of_certs; /* number of certificates with information */
+ struct curl_slist **certinfo; /* for each index in this array, there's a
+ linked list with textual information in the
+ format "name: value" */
+};
+
+/* Information about the SSL library used and the respective internal SSL
+ handle, which can be used to obtain further information regarding the
+ connection. Asked for with CURLINFO_TLS_SSL_PTR or CURLINFO_TLS_SESSION. */
+struct curl_tlssessioninfo {
+ curl_sslbackend backend;
+ void *internals;
+};
+
+#define CURLINFO_STRING 0x100000
+#define CURLINFO_LONG 0x200000
+#define CURLINFO_DOUBLE 0x300000
+#define CURLINFO_SLIST 0x400000
+#define CURLINFO_PTR 0x400000 /* same as SLIST */
+#define CURLINFO_SOCKET 0x500000
+#define CURLINFO_OFF_T 0x600000
+#define CURLINFO_MASK 0x0fffff
+#define CURLINFO_TYPEMASK 0xf00000
+
+typedef enum {
+ CURLINFO_NONE, /* first, never use this */
+ CURLINFO_EFFECTIVE_URL = CURLINFO_STRING + 1,
+ CURLINFO_RESPONSE_CODE = CURLINFO_LONG + 2,
+ CURLINFO_TOTAL_TIME = CURLINFO_DOUBLE + 3,
+ CURLINFO_NAMELOOKUP_TIME = CURLINFO_DOUBLE + 4,
+ CURLINFO_CONNECT_TIME = CURLINFO_DOUBLE + 5,
+ CURLINFO_PRETRANSFER_TIME = CURLINFO_DOUBLE + 6,
+ CURLINFO_SIZE_UPLOAD = CURLINFO_DOUBLE + 7,
+ CURLINFO_SIZE_UPLOAD_T = CURLINFO_OFF_T + 7,
+ CURLINFO_SIZE_DOWNLOAD = CURLINFO_DOUBLE + 8,
+ CURLINFO_SIZE_DOWNLOAD_T = CURLINFO_OFF_T + 8,
+ CURLINFO_SPEED_DOWNLOAD = CURLINFO_DOUBLE + 9,
+ CURLINFO_SPEED_DOWNLOAD_T = CURLINFO_OFF_T + 9,
+ CURLINFO_SPEED_UPLOAD = CURLINFO_DOUBLE + 10,
+ CURLINFO_SPEED_UPLOAD_T = CURLINFO_OFF_T + 10,
+ CURLINFO_HEADER_SIZE = CURLINFO_LONG + 11,
+ CURLINFO_REQUEST_SIZE = CURLINFO_LONG + 12,
+ CURLINFO_SSL_VERIFYRESULT = CURLINFO_LONG + 13,
+ CURLINFO_FILETIME = CURLINFO_LONG + 14,
+ CURLINFO_FILETIME_T = CURLINFO_OFF_T + 14,
+ CURLINFO_CONTENT_LENGTH_DOWNLOAD = CURLINFO_DOUBLE + 15,
+ CURLINFO_CONTENT_LENGTH_DOWNLOAD_T = CURLINFO_OFF_T + 15,
+ CURLINFO_CONTENT_LENGTH_UPLOAD = CURLINFO_DOUBLE + 16,
+ CURLINFO_CONTENT_LENGTH_UPLOAD_T = CURLINFO_OFF_T + 16,
+ CURLINFO_STARTTRANSFER_TIME = CURLINFO_DOUBLE + 17,
+ CURLINFO_CONTENT_TYPE = CURLINFO_STRING + 18,
+ CURLINFO_REDIRECT_TIME = CURLINFO_DOUBLE + 19,
+ CURLINFO_REDIRECT_COUNT = CURLINFO_LONG + 20,
+ CURLINFO_PRIVATE = CURLINFO_STRING + 21,
+ CURLINFO_HTTP_CONNECTCODE = CURLINFO_LONG + 22,
+ CURLINFO_HTTPAUTH_AVAIL = CURLINFO_LONG + 23,
+ CURLINFO_PROXYAUTH_AVAIL = CURLINFO_LONG + 24,
+ CURLINFO_OS_ERRNO = CURLINFO_LONG + 25,
+ CURLINFO_NUM_CONNECTS = CURLINFO_LONG + 26,
+ CURLINFO_SSL_ENGINES = CURLINFO_SLIST + 27,
+ CURLINFO_COOKIELIST = CURLINFO_SLIST + 28,
+ CURLINFO_LASTSOCKET = CURLINFO_LONG + 29,
+ CURLINFO_FTP_ENTRY_PATH = CURLINFO_STRING + 30,
+ CURLINFO_REDIRECT_URL = CURLINFO_STRING + 31,
+ CURLINFO_PRIMARY_IP = CURLINFO_STRING + 32,
+ CURLINFO_APPCONNECT_TIME = CURLINFO_DOUBLE + 33,
+ CURLINFO_CERTINFO = CURLINFO_PTR + 34,
+ CURLINFO_CONDITION_UNMET = CURLINFO_LONG + 35,
+ CURLINFO_RTSP_SESSION_ID = CURLINFO_STRING + 36,
+ CURLINFO_RTSP_CLIENT_CSEQ = CURLINFO_LONG + 37,
+ CURLINFO_RTSP_SERVER_CSEQ = CURLINFO_LONG + 38,
+ CURLINFO_RTSP_CSEQ_RECV = CURLINFO_LONG + 39,
+ CURLINFO_PRIMARY_PORT = CURLINFO_LONG + 40,
+ CURLINFO_LOCAL_IP = CURLINFO_STRING + 41,
+ CURLINFO_LOCAL_PORT = CURLINFO_LONG + 42,
+ CURLINFO_TLS_SESSION = CURLINFO_PTR + 43,
+ CURLINFO_ACTIVESOCKET = CURLINFO_SOCKET + 44,
+ CURLINFO_TLS_SSL_PTR = CURLINFO_PTR + 45,
+ CURLINFO_HTTP_VERSION = CURLINFO_LONG + 46,
+ CURLINFO_PROXY_SSL_VERIFYRESULT = CURLINFO_LONG + 47,
+ CURLINFO_PROTOCOL = CURLINFO_LONG + 48,
+ CURLINFO_SCHEME = CURLINFO_STRING + 49,
+ CURLINFO_TOTAL_TIME_T = CURLINFO_OFF_T + 50,
+ CURLINFO_NAMELOOKUP_TIME_T = CURLINFO_OFF_T + 51,
+ CURLINFO_CONNECT_TIME_T = CURLINFO_OFF_T + 52,
+ CURLINFO_PRETRANSFER_TIME_T = CURLINFO_OFF_T + 53,
+ CURLINFO_STARTTRANSFER_TIME_T = CURLINFO_OFF_T + 54,
+ CURLINFO_REDIRECT_TIME_T = CURLINFO_OFF_T + 55,
+ CURLINFO_APPCONNECT_TIME_T = CURLINFO_OFF_T + 56,
+ CURLINFO_RETRY_AFTER = CURLINFO_OFF_T + 57,
+ CURLINFO_EFFECTIVE_METHOD = CURLINFO_STRING + 58,
+ CURLINFO_PROXY_ERROR = CURLINFO_LONG + 59,
+ CURLINFO_REFERER = CURLINFO_STRING + 60,
+
+ CURLINFO_LASTONE = 60
+} CURLINFO;
+
+/* CURLINFO_RESPONSE_CODE is the new name for the option previously known as
+ CURLINFO_HTTP_CODE */
+#define CURLINFO_HTTP_CODE CURLINFO_RESPONSE_CODE
+
+typedef enum {
+ CURLCLOSEPOLICY_NONE, /* first, never use this */
+
+ CURLCLOSEPOLICY_OLDEST,
+ CURLCLOSEPOLICY_LEAST_RECENTLY_USED,
+ CURLCLOSEPOLICY_LEAST_TRAFFIC,
+ CURLCLOSEPOLICY_SLOWEST,
+ CURLCLOSEPOLICY_CALLBACK,
+
+ CURLCLOSEPOLICY_LAST /* last, never use this */
+} curl_closepolicy;
+
+#define CURL_GLOBAL_SSL (1<<0) /* no purpose since since 7.57.0 */
+#define CURL_GLOBAL_WIN32 (1<<1)
+#define CURL_GLOBAL_ALL (CURL_GLOBAL_SSL|CURL_GLOBAL_WIN32)
+#define CURL_GLOBAL_NOTHING 0
+#define CURL_GLOBAL_DEFAULT CURL_GLOBAL_ALL
+#define CURL_GLOBAL_ACK_EINTR (1<<2)
+
+
+/*****************************************************************************
+ * Setup defines, protos etc for the sharing stuff.
+ */
+
+/* Different data locks for a single share */
+typedef enum {
+ CURL_LOCK_DATA_NONE = 0,
+ /* CURL_LOCK_DATA_SHARE is used internally to say that
+ * the locking is just made to change the internal state of the share
+ * itself.
+ */
+ CURL_LOCK_DATA_SHARE,
+ CURL_LOCK_DATA_COOKIE,
+ CURL_LOCK_DATA_DNS,
+ CURL_LOCK_DATA_SSL_SESSION,
+ CURL_LOCK_DATA_CONNECT,
+ CURL_LOCK_DATA_PSL,
+ CURL_LOCK_DATA_LAST
+} curl_lock_data;
+
+/* Different lock access types */
+typedef enum {
+ CURL_LOCK_ACCESS_NONE = 0, /* unspecified action */
+ CURL_LOCK_ACCESS_SHARED = 1, /* for read perhaps */
+ CURL_LOCK_ACCESS_SINGLE = 2, /* for write perhaps */
+ CURL_LOCK_ACCESS_LAST /* never use */
+} curl_lock_access;
+
+typedef void (*curl_lock_function)(CURL *handle,
+ curl_lock_data data,
+ curl_lock_access locktype,
+ void *userptr);
+typedef void (*curl_unlock_function)(CURL *handle,
+ curl_lock_data data,
+ void *userptr);
+
+
+typedef enum {
+ CURLSHE_OK, /* all is fine */
+ CURLSHE_BAD_OPTION, /* 1 */
+ CURLSHE_IN_USE, /* 2 */
+ CURLSHE_INVALID, /* 3 */
+ CURLSHE_NOMEM, /* 4 out of memory */
+ CURLSHE_NOT_BUILT_IN, /* 5 feature not present in lib */
+ CURLSHE_LAST /* never use */
+} CURLSHcode;
+
+typedef enum {
+ CURLSHOPT_NONE, /* don't use */
+ CURLSHOPT_SHARE, /* specify a data type to share */
+ CURLSHOPT_UNSHARE, /* specify which data type to stop sharing */
+ CURLSHOPT_LOCKFUNC, /* pass in a 'curl_lock_function' pointer */
+ CURLSHOPT_UNLOCKFUNC, /* pass in a 'curl_unlock_function' pointer */
+ CURLSHOPT_USERDATA, /* pass in a user data pointer used in the lock/unlock
+ callback functions */
+ CURLSHOPT_LAST /* never use */
+} CURLSHoption;
+
+CURL_EXTERN CURLSH *curl_share_init(void);
+CURL_EXTERN CURLSHcode curl_share_setopt(CURLSH *, CURLSHoption option, ...);
+CURL_EXTERN CURLSHcode curl_share_cleanup(CURLSH *);
+
+/****************************************************************************
+ * Structures for querying information about the curl library at runtime.
+ */
+
+typedef enum {
+ CURLVERSION_FIRST,
+ CURLVERSION_SECOND,
+ CURLVERSION_THIRD,
+ CURLVERSION_FOURTH,
+ CURLVERSION_FIFTH,
+ CURLVERSION_SIXTH,
+ CURLVERSION_SEVENTH,
+ CURLVERSION_EIGHTH,
+ CURLVERSION_NINTH,
+ CURLVERSION_TENTH,
+ CURLVERSION_LAST /* never actually use this */
+} CURLversion;
+
+/* The 'CURLVERSION_NOW' is the symbolic name meant to be used by
+ basically all programs ever that want to get version information. It is
+ meant to be a built-in version number for what kind of struct the caller
+ expects. If the struct ever changes, we redefine the NOW to another enum
+ from above. */
+#define CURLVERSION_NOW CURLVERSION_TENTH
+
+struct curl_version_info_data {
+ CURLversion age; /* age of the returned struct */
+ const char *version; /* LIBCURL_VERSION */
+ unsigned int version_num; /* LIBCURL_VERSION_NUM */
+ const char *host; /* OS/host/cpu/machine when configured */
+ int features; /* bitmask, see defines below */
+ const char *ssl_version; /* human readable string */
+ long ssl_version_num; /* not used anymore, always 0 */
+ const char *libz_version; /* human readable string */
+ /* protocols is terminated by an entry with a NULL protoname */
+ const char * const *protocols;
+
+ /* The fields below this were added in CURLVERSION_SECOND */
+ const char *ares;
+ int ares_num;
+
+ /* This field was added in CURLVERSION_THIRD */
+ const char *libidn;
+
+ /* These field were added in CURLVERSION_FOURTH */
+
+ /* Same as '_libiconv_version' if built with HAVE_ICONV */
+ int iconv_ver_num;
+
+ const char *libssh_version; /* human readable string */
+
+ /* These fields were added in CURLVERSION_FIFTH */
+ unsigned int brotli_ver_num; /* Numeric Brotli version
+ (MAJOR << 24) | (MINOR << 12) | PATCH */
+ const char *brotli_version; /* human readable string. */
+
+ /* These fields were added in CURLVERSION_SIXTH */
+ unsigned int nghttp2_ver_num; /* Numeric nghttp2 version
+ (MAJOR << 16) | (MINOR << 8) | PATCH */
+ const char *nghttp2_version; /* human readable string. */
+ const char *quic_version; /* human readable quic (+ HTTP/3) library +
+ version or NULL */
+
+ /* These fields were added in CURLVERSION_SEVENTH */
+ const char *cainfo; /* the built-in default CURLOPT_CAINFO, might
+ be NULL */
+ const char *capath; /* the built-in default CURLOPT_CAPATH, might
+ be NULL */
+
+ /* These fields were added in CURLVERSION_EIGHTH */
+ unsigned int zstd_ver_num; /* Numeric Zstd version
+ (MAJOR << 24) | (MINOR << 12) | PATCH */
+ const char *zstd_version; /* human readable string. */
+
+ /* These fields were added in CURLVERSION_NINTH */
+ const char *hyper_version; /* human readable string. */
+
+ /* These fields were added in CURLVERSION_TENTH */
+ const char *gsasl_version; /* human readable string. */
+};
+typedef struct curl_version_info_data curl_version_info_data;
+
+#define CURL_VERSION_IPV6 (1<<0) /* IPv6-enabled */
+#define CURL_VERSION_KERBEROS4 (1<<1) /* Kerberos V4 auth is supported
+ (deprecated) */
+#define CURL_VERSION_SSL (1<<2) /* SSL options are present */
+#define CURL_VERSION_LIBZ (1<<3) /* libz features are present */
+#define CURL_VERSION_NTLM (1<<4) /* NTLM auth is supported */
+#define CURL_VERSION_GSSNEGOTIATE (1<<5) /* Negotiate auth is supported
+ (deprecated) */
+#define CURL_VERSION_DEBUG (1<<6) /* Built with debug capabilities */
+#define CURL_VERSION_ASYNCHDNS (1<<7) /* Asynchronous DNS resolves */
+#define CURL_VERSION_SPNEGO (1<<8) /* SPNEGO auth is supported */
+#define CURL_VERSION_LARGEFILE (1<<9) /* Supports files larger than 2GB */
+#define CURL_VERSION_IDN (1<<10) /* Internationized Domain Names are
+ supported */
+#define CURL_VERSION_SSPI (1<<11) /* Built against Windows SSPI */
+#define CURL_VERSION_CONV (1<<12) /* Character conversions supported */
+#define CURL_VERSION_CURLDEBUG (1<<13) /* Debug memory tracking supported */
+#define CURL_VERSION_TLSAUTH_SRP (1<<14) /* TLS-SRP auth is supported */
+#define CURL_VERSION_NTLM_WB (1<<15) /* NTLM delegation to winbind helper
+ is supported */
+#define CURL_VERSION_HTTP2 (1<<16) /* HTTP2 support built-in */
+#define CURL_VERSION_GSSAPI (1<<17) /* Built against a GSS-API library */
+#define CURL_VERSION_KERBEROS5 (1<<18) /* Kerberos V5 auth is supported */
+#define CURL_VERSION_UNIX_SOCKETS (1<<19) /* Unix domain sockets support */
+#define CURL_VERSION_PSL (1<<20) /* Mozilla's Public Suffix List, used
+ for cookie domain verification */
+#define CURL_VERSION_HTTPS_PROXY (1<<21) /* HTTPS-proxy support built-in */
+#define CURL_VERSION_MULTI_SSL (1<<22) /* Multiple SSL backends available */
+#define CURL_VERSION_BROTLI (1<<23) /* Brotli features are present. */
+#define CURL_VERSION_ALTSVC (1<<24) /* Alt-Svc handling built-in */
+#define CURL_VERSION_HTTP3 (1<<25) /* HTTP3 support built-in */
+#define CURL_VERSION_ZSTD (1<<26) /* zstd features are present */
+#define CURL_VERSION_UNICODE (1<<27) /* Unicode support on Windows */
+#define CURL_VERSION_HSTS (1<<28) /* HSTS is supported */
+#define CURL_VERSION_GSASL (1<<29) /* libgsasl is supported */
+
+ /*
+ * NAME curl_version_info()
+ *
+ * DESCRIPTION
+ *
+ * This function returns a pointer to a static copy of the version info
+ * struct. See above.
+ */
+CURL_EXTERN curl_version_info_data *curl_version_info(CURLversion);
+
+/*
+ * NAME curl_easy_strerror()
+ *
+ * DESCRIPTION
+ *
+ * The curl_easy_strerror function may be used to turn a CURLcode value
+ * into the equivalent human readable error string. This is useful
+ * for printing meaningful error messages.
+ */
+CURL_EXTERN const char *curl_easy_strerror(CURLcode);
+
+/*
+ * NAME curl_share_strerror()
+ *
+ * DESCRIPTION
+ *
+ * The curl_share_strerror function may be used to turn a CURLSHcode value
+ * into the equivalent human readable error string. This is useful
+ * for printing meaningful error messages.
+ */
+CURL_EXTERN const char *curl_share_strerror(CURLSHcode);
+
+/*
+ * NAME curl_easy_pause()
+ *
+ * DESCRIPTION
+ *
+ * The curl_easy_pause function pauses or unpauses transfers. Select the new
+ * state by setting the bitmask, use the convenience defines below.
+ *
+ */
+CURL_EXTERN CURLcode curl_easy_pause(CURL *handle, int bitmask);
+
+#define CURLPAUSE_RECV (1<<0)
+#define CURLPAUSE_RECV_CONT (0)
+
+#define CURLPAUSE_SEND (1<<2)
+#define CURLPAUSE_SEND_CONT (0)
+
+#define CURLPAUSE_ALL (CURLPAUSE_RECV|CURLPAUSE_SEND)
+#define CURLPAUSE_CONT (CURLPAUSE_RECV_CONT|CURLPAUSE_SEND_CONT)
+
+#ifdef __cplusplus
+}
+#endif
+
+/* unfortunately, the easy.h and multi.h include files need options and info
+ stuff before they can be included! */
+#include "easy.h" /* nothing in curl is fun without the easy stuff */
+#include "multi.h"
+#include "urlapi.h"
+#include "options.h"
+
+/* the typechecker doesn't work in C++ (yet) */
+#if defined(__GNUC__) && defined(__GNUC_MINOR__) && \
+ ((__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 3)) && \
+ !defined(__cplusplus) && !defined(CURL_DISABLE_TYPECHECK)
+#include "typecheck-gcc.h"
+#else
+#if defined(__STDC__) && (__STDC__ >= 1)
+/* This preprocessor magic that replaces a call with the exact same call is
+ only done to make sure application authors pass exactly three arguments
+ to these functions. */
+#define curl_easy_setopt(handle,opt,param) curl_easy_setopt(handle,opt,param)
+#define curl_easy_getinfo(handle,info,arg) curl_easy_getinfo(handle,info,arg)
+#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
+#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
+#endif /* __STDC__ >= 1 */
+#endif /* gcc >= 4.3 && !__cplusplus */
+
+#endif /* CURLINC_CURL_H */
diff --git a/include/libcurl/include/curl/curlver.h b/include/libcurl/include/curl/curlver.h
new file mode 100644
index 00000000..fe57e430
--- /dev/null
+++ b/include/libcurl/include/curl/curlver.h
@@ -0,0 +1,77 @@
+#ifndef CURLINC_CURLVER_H
+#define CURLINC_CURLVER_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* This header file contains nothing but libcurl version info, generated by
+ a script at release-time. This was made its own header file in 7.11.2 */
+
+/* This is the global package copyright */
+#define LIBCURL_COPYRIGHT "1996 - 2021 Daniel Stenberg, <daniel@haxx.se>."
+
+/* This is the version number of the libcurl package from which this header
+ file origins: */
+#define LIBCURL_VERSION "7.81.0-DEV"
+
+/* The numeric version number is also available "in parts" by using these
+ defines: */
+#define LIBCURL_VERSION_MAJOR 7
+#define LIBCURL_VERSION_MINOR 81
+#define LIBCURL_VERSION_PATCH 0
+
+/* This is the numeric version of the libcurl version number, meant for easier
+ parsing and comparisons by programs. The LIBCURL_VERSION_NUM define will
+ always follow this syntax:
+
+ 0xXXYYZZ
+
+ Where XX, YY and ZZ are the main version, release and patch numbers in
+ hexadecimal (using 8 bits each). All three numbers are always represented
+ using two digits. 1.2 would appear as "0x010200" while version 9.11.7
+ appears as "0x090b07".
+
+ This 6-digit (24 bits) hexadecimal number does not show pre-release number,
+ and it is always a greater number in a more recent release. It makes
+ comparisons with greater than and less than work.
+
+ Note: This define is the full hex number and _does not_ use the
+ CURL_VERSION_BITS() macro since curl's own configure script greps for it
+ and needs it to contain the full number.
+*/
+#define LIBCURL_VERSION_NUM 0x075100
+
+/*
+ * This is the date and time when the full source package was created. The
+ * timestamp is not stored in git, as the timestamp is properly set in the
+ * tarballs by the maketgz script.
+ *
+ * The format of the date follows this template:
+ *
+ * "2007-11-23"
+ */
+#define LIBCURL_TIMESTAMP "[unreleased]"
+
+#define CURL_VERSION_BITS(x,y,z) ((x)<<16|(y)<<8|(z))
+#define CURL_AT_LEAST_VERSION(x,y,z) \
+ (LIBCURL_VERSION_NUM >= CURL_VERSION_BITS(x, y, z))
+
+#endif /* CURLINC_CURLVER_H */
diff --git a/include/libcurl/include/curl/easy.h b/include/libcurl/include/curl/easy.h
new file mode 100644
index 00000000..2dbfb26b
--- /dev/null
+++ b/include/libcurl/include/curl/easy.h
@@ -0,0 +1,123 @@
+#ifndef CURLINC_EASY_H
+#define CURLINC_EASY_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Flag bits in the curl_blob struct: */
+#define CURL_BLOB_COPY 1 /* tell libcurl to copy the data */
+#define CURL_BLOB_NOCOPY 0 /* tell libcurl to NOT copy the data */
+
+struct curl_blob {
+ void *data;
+ size_t len;
+ unsigned int flags; /* bit 0 is defined, the rest are reserved and should be
+ left zeroes */
+};
+
+CURL_EXTERN CURL *curl_easy_init(void);
+CURL_EXTERN CURLcode curl_easy_setopt(CURL *curl, CURLoption option, ...);
+CURL_EXTERN CURLcode curl_easy_perform(CURL *curl);
+CURL_EXTERN void curl_easy_cleanup(CURL *curl);
+
+/*
+ * NAME curl_easy_getinfo()
+ *
+ * DESCRIPTION
+ *
+ * Request internal information from the curl session with this function. The
+ * third argument MUST be a pointer to a long, a pointer to a char * or a
+ * pointer to a double (as the documentation describes elsewhere). The data
+ * pointed to will be filled in accordingly and can be relied upon only if the
+ * function returns CURLE_OK. This function is intended to get used *AFTER* a
+ * performed transfer, all results from this function are undefined until the
+ * transfer is completed.
+ */
+CURL_EXTERN CURLcode curl_easy_getinfo(CURL *curl, CURLINFO info, ...);
+
+
+/*
+ * NAME curl_easy_duphandle()
+ *
+ * DESCRIPTION
+ *
+ * Creates a new curl session handle with the same options set for the handle
+ * passed in. Duplicating a handle could only be a matter of cloning data and
+ * options, internal state info and things like persistent connections cannot
+ * be transferred. It is useful in multithreaded applications when you can run
+ * curl_easy_duphandle() for each new thread to avoid a series of identical
+ * curl_easy_setopt() invokes in every thread.
+ */
+CURL_EXTERN CURL *curl_easy_duphandle(CURL *curl);
+
+/*
+ * NAME curl_easy_reset()
+ *
+ * DESCRIPTION
+ *
+ * Re-initializes a CURL handle to the default values. This puts back the
+ * handle to the same state as it was in when it was just created.
+ *
+ * It does keep: live connections, the Session ID cache, the DNS cache and the
+ * cookies.
+ */
+CURL_EXTERN void curl_easy_reset(CURL *curl);
+
+/*
+ * NAME curl_easy_recv()
+ *
+ * DESCRIPTION
+ *
+ * Receives data from the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ */
+CURL_EXTERN CURLcode curl_easy_recv(CURL *curl, void *buffer, size_t buflen,
+ size_t *n);
+
+/*
+ * NAME curl_easy_send()
+ *
+ * DESCRIPTION
+ *
+ * Sends data over the connected socket. Use after successful
+ * curl_easy_perform() with CURLOPT_CONNECT_ONLY option.
+ */
+CURL_EXTERN CURLcode curl_easy_send(CURL *curl, const void *buffer,
+ size_t buflen, size_t *n);
+
+
+/*
+ * NAME curl_easy_upkeep()
+ *
+ * DESCRIPTION
+ *
+ * Performs connection upkeep for the given session handle.
+ */
+CURL_EXTERN CURLcode curl_easy_upkeep(CURL *curl);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/libcurl/include/curl/mprintf.h b/include/libcurl/include/curl/mprintf.h
new file mode 100644
index 00000000..3549552d
--- /dev/null
+++ b/include/libcurl/include/curl/mprintf.h
@@ -0,0 +1,50 @@
+#ifndef CURLINC_MPRINTF_H
+#define CURLINC_MPRINTF_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <stdarg.h>
+#include <stdio.h> /* needed for FILE */
+#include "curl.h" /* for CURL_EXTERN */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+CURL_EXTERN int curl_mprintf(const char *format, ...);
+CURL_EXTERN int curl_mfprintf(FILE *fd, const char *format, ...);
+CURL_EXTERN int curl_msprintf(char *buffer, const char *format, ...);
+CURL_EXTERN int curl_msnprintf(char *buffer, size_t maxlength,
+ const char *format, ...);
+CURL_EXTERN int curl_mvprintf(const char *format, va_list args);
+CURL_EXTERN int curl_mvfprintf(FILE *fd, const char *format, va_list args);
+CURL_EXTERN int curl_mvsprintf(char *buffer, const char *format, va_list args);
+CURL_EXTERN int curl_mvsnprintf(char *buffer, size_t maxlength,
+ const char *format, va_list args);
+CURL_EXTERN char *curl_maprintf(const char *format, ...);
+CURL_EXTERN char *curl_mvaprintf(const char *format, va_list args);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CURLINC_MPRINTF_H */
diff --git a/include/libcurl/include/curl/multi.h b/include/libcurl/include/curl/multi.h
new file mode 100644
index 00000000..91cd95d3
--- /dev/null
+++ b/include/libcurl/include/curl/multi.h
@@ -0,0 +1,457 @@
+#ifndef CURLINC_MULTI_H
+#define CURLINC_MULTI_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+/*
+ This is an "external" header file. Don't give away any internals here!
+
+ GOALS
+
+ o Enable a "pull" interface. The application that uses libcurl decides where
+ and when to ask libcurl to get/send data.
+
+ o Enable multiple simultaneous transfers in the same thread without making it
+ complicated for the application.
+
+ o Enable the application to select() on its own file descriptors and curl's
+ file descriptors simultaneous easily.
+
+*/
+
+/*
+ * This header file should not really need to include "curl.h" since curl.h
+ * itself includes this file and we expect user applications to do #include
+ * <curl/curl.h> without the need for especially including multi.h.
+ *
+ * For some reason we added this include here at one point, and rather than to
+ * break existing (wrongly written) libcurl applications, we leave it as-is
+ * but with this warning attached.
+ */
+#include "curl.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(BUILDING_LIBCURL) || defined(CURL_STRICTER)
+typedef struct Curl_multi CURLM;
+#else
+typedef void CURLM;
+#endif
+
+typedef enum {
+ CURLM_CALL_MULTI_PERFORM = -1, /* please call curl_multi_perform() or
+ curl_multi_socket*() soon */
+ CURLM_OK,
+ CURLM_BAD_HANDLE, /* the passed-in handle is not a valid CURLM handle */
+ CURLM_BAD_EASY_HANDLE, /* an easy handle was not good/valid */
+ CURLM_OUT_OF_MEMORY, /* if you ever get this, you're in deep sh*t */
+ CURLM_INTERNAL_ERROR, /* this is a libcurl bug */
+ CURLM_BAD_SOCKET, /* the passed in socket argument did not match */
+ CURLM_UNKNOWN_OPTION, /* curl_multi_setopt() with unsupported option */
+ CURLM_ADDED_ALREADY, /* an easy handle already added to a multi handle was
+ attempted to get added - again */
+ CURLM_RECURSIVE_API_CALL, /* an api function was called from inside a
+ callback */
+ CURLM_WAKEUP_FAILURE, /* wakeup is unavailable or failed */
+ CURLM_BAD_FUNCTION_ARGUMENT, /* function called with a bad parameter */
+ CURLM_ABORTED_BY_CALLBACK,
+ CURLM_LAST
+} CURLMcode;
+
+/* just to make code nicer when using curl_multi_socket() you can now check
+ for CURLM_CALL_MULTI_SOCKET too in the same style it works for
+ curl_multi_perform() and CURLM_CALL_MULTI_PERFORM */
+#define CURLM_CALL_MULTI_SOCKET CURLM_CALL_MULTI_PERFORM
+
+/* bitmask bits for CURLMOPT_PIPELINING */
+#define CURLPIPE_NOTHING 0L
+#define CURLPIPE_HTTP1 1L
+#define CURLPIPE_MULTIPLEX 2L
+
+typedef enum {
+ CURLMSG_NONE, /* first, not used */
+ CURLMSG_DONE, /* This easy handle has completed. 'result' contains
+ the CURLcode of the transfer */
+ CURLMSG_LAST /* last, not used */
+} CURLMSG;
+
+struct CURLMsg {
+ CURLMSG msg; /* what this message means */
+ CURL *easy_handle; /* the handle it concerns */
+ union {
+ void *whatever; /* message-specific data */
+ CURLcode result; /* return code for transfer */
+ } data;
+};
+typedef struct CURLMsg CURLMsg;
+
+/* Based on poll(2) structure and values.
+ * We don't use pollfd and POLL* constants explicitly
+ * to cover platforms without poll(). */
+#define CURL_WAIT_POLLIN 0x0001
+#define CURL_WAIT_POLLPRI 0x0002
+#define CURL_WAIT_POLLOUT 0x0004
+
+struct curl_waitfd {
+ curl_socket_t fd;
+ short events;
+ short revents; /* not supported yet */
+};
+
+/*
+ * Name: curl_multi_init()
+ *
+ * Desc: inititalize multi-style curl usage
+ *
+ * Returns: a new CURLM handle to use in all 'curl_multi' functions.
+ */
+CURL_EXTERN CURLM *curl_multi_init(void);
+
+/*
+ * Name: curl_multi_add_handle()
+ *
+ * Desc: add a standard curl handle to the multi stack
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_add_handle(CURLM *multi_handle,
+ CURL *curl_handle);
+
+ /*
+ * Name: curl_multi_remove_handle()
+ *
+ * Desc: removes a curl handle from the multi stack again
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_remove_handle(CURLM *multi_handle,
+ CURL *curl_handle);
+
+ /*
+ * Name: curl_multi_fdset()
+ *
+ * Desc: Ask curl for its fd_set sets. The app can use these to select() or
+ * poll() on. We want curl_multi_perform() called as soon as one of
+ * them are ready.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_fdset(CURLM *multi_handle,
+ fd_set *read_fd_set,
+ fd_set *write_fd_set,
+ fd_set *exc_fd_set,
+ int *max_fd);
+
+/*
+ * Name: curl_multi_wait()
+ *
+ * Desc: Poll on all fds within a CURLM set as well as any
+ * additional fds passed to the function.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_wait(CURLM *multi_handle,
+ struct curl_waitfd extra_fds[],
+ unsigned int extra_nfds,
+ int timeout_ms,
+ int *ret);
+
+/*
+ * Name: curl_multi_poll()
+ *
+ * Desc: Poll on all fds within a CURLM set as well as any
+ * additional fds passed to the function.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_poll(CURLM *multi_handle,
+ struct curl_waitfd extra_fds[],
+ unsigned int extra_nfds,
+ int timeout_ms,
+ int *ret);
+
+/*
+ * Name: curl_multi_wakeup()
+ *
+ * Desc: wakes up a sleeping curl_multi_poll call.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_wakeup(CURLM *multi_handle);
+
+ /*
+ * Name: curl_multi_perform()
+ *
+ * Desc: When the app thinks there's data available for curl it calls this
+ * function to read/write whatever there is right now. This returns
+ * as soon as the reads and writes are done. This function does not
+ * require that there actually is data available for reading or that
+ * data can be written, it can be called just in case. It returns
+ * the number of handles that still transfer data in the second
+ * argument's integer-pointer.
+ *
+ * Returns: CURLMcode type, general multi error code. *NOTE* that this only
+ * returns errors etc regarding the whole multi stack. There might
+ * still have occurred problems on individual transfers even when
+ * this returns OK.
+ */
+CURL_EXTERN CURLMcode curl_multi_perform(CURLM *multi_handle,
+ int *running_handles);
+
+ /*
+ * Name: curl_multi_cleanup()
+ *
+ * Desc: Cleans up and removes a whole multi stack. It does not free or
+ * touch any individual easy handles in any way. We need to define
+ * in what state those handles will be if this function is called
+ * in the middle of a transfer.
+ *
+ * Returns: CURLMcode type, general multi error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_cleanup(CURLM *multi_handle);
+
+/*
+ * Name: curl_multi_info_read()
+ *
+ * Desc: Ask the multi handle if there's any messages/informationals from
+ * the individual transfers. Messages include informationals such as
+ * error code from the transfer or just the fact that a transfer is
+ * completed. More details on these should be written down as well.
+ *
+ * Repeated calls to this function will return a new struct each
+ * time, until a special "end of msgs" struct is returned as a signal
+ * that there is no more to get at this point.
+ *
+ * The data the returned pointer points to will not survive calling
+ * curl_multi_cleanup().
+ *
+ * The 'CURLMsg' struct is meant to be very simple and only contain
+ * very basic information. If more involved information is wanted,
+ * we will provide the particular "transfer handle" in that struct
+ * and that should/could/would be used in subsequent
+ * curl_easy_getinfo() calls (or similar). The point being that we
+ * must never expose complex structs to applications, as then we'll
+ * undoubtably get backwards compatibility problems in the future.
+ *
+ * Returns: A pointer to a filled-in struct, or NULL if it failed or ran out
+ * of structs. It also writes the number of messages left in the
+ * queue (after this read) in the integer the second argument points
+ * to.
+ */
+CURL_EXTERN CURLMsg *curl_multi_info_read(CURLM *multi_handle,
+ int *msgs_in_queue);
+
+/*
+ * Name: curl_multi_strerror()
+ *
+ * Desc: The curl_multi_strerror function may be used to turn a CURLMcode
+ * value into the equivalent human readable error string. This is
+ * useful for printing meaningful error messages.
+ *
+ * Returns: A pointer to a null-terminated error message.
+ */
+CURL_EXTERN const char *curl_multi_strerror(CURLMcode);
+
+/*
+ * Name: curl_multi_socket() and
+ * curl_multi_socket_all()
+ *
+ * Desc: An alternative version of curl_multi_perform() that allows the
+ * application to pass in one of the file descriptors that have been
+ * detected to have "action" on them and let libcurl perform.
+ * See man page for details.
+ */
+#define CURL_POLL_NONE 0
+#define CURL_POLL_IN 1
+#define CURL_POLL_OUT 2
+#define CURL_POLL_INOUT 3
+#define CURL_POLL_REMOVE 4
+
+#define CURL_SOCKET_TIMEOUT CURL_SOCKET_BAD
+
+#define CURL_CSELECT_IN 0x01
+#define CURL_CSELECT_OUT 0x02
+#define CURL_CSELECT_ERR 0x04
+
+typedef int (*curl_socket_callback)(CURL *easy, /* easy handle */
+ curl_socket_t s, /* socket */
+ int what, /* see above */
+ void *userp, /* private callback
+ pointer */
+ void *socketp); /* private socket
+ pointer */
+/*
+ * Name: curl_multi_timer_callback
+ *
+ * Desc: Called by libcurl whenever the library detects a change in the
+ * maximum number of milliseconds the app is allowed to wait before
+ * curl_multi_socket() or curl_multi_perform() must be called
+ * (to allow libcurl's timed events to take place).
+ *
+ * Returns: The callback should return zero.
+ */
+typedef int (*curl_multi_timer_callback)(CURLM *multi, /* multi handle */
+ long timeout_ms, /* see above */
+ void *userp); /* private callback
+ pointer */
+
+CURL_EXTERN CURLMcode curl_multi_socket(CURLM *multi_handle, curl_socket_t s,
+ int *running_handles);
+
+CURL_EXTERN CURLMcode curl_multi_socket_action(CURLM *multi_handle,
+ curl_socket_t s,
+ int ev_bitmask,
+ int *running_handles);
+
+CURL_EXTERN CURLMcode curl_multi_socket_all(CURLM *multi_handle,
+ int *running_handles);
+
+#ifndef CURL_ALLOW_OLD_MULTI_SOCKET
+/* This macro below was added in 7.16.3 to push users who recompile to use
+ the new curl_multi_socket_action() instead of the old curl_multi_socket()
+*/
+#define curl_multi_socket(x,y,z) curl_multi_socket_action(x,y,0,z)
+#endif
+
+/*
+ * Name: curl_multi_timeout()
+ *
+ * Desc: Returns the maximum number of milliseconds the app is allowed to
+ * wait before curl_multi_socket() or curl_multi_perform() must be
+ * called (to allow libcurl's timed events to take place).
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_timeout(CURLM *multi_handle,
+ long *milliseconds);
+
+typedef enum {
+ /* This is the socket callback function pointer */
+ CURLOPT(CURLMOPT_SOCKETFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 1),
+
+ /* This is the argument passed to the socket callback */
+ CURLOPT(CURLMOPT_SOCKETDATA, CURLOPTTYPE_OBJECTPOINT, 2),
+
+ /* set to 1 to enable pipelining for this multi handle */
+ CURLOPT(CURLMOPT_PIPELINING, CURLOPTTYPE_LONG, 3),
+
+ /* This is the timer callback function pointer */
+ CURLOPT(CURLMOPT_TIMERFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 4),
+
+ /* This is the argument passed to the timer callback */
+ CURLOPT(CURLMOPT_TIMERDATA, CURLOPTTYPE_OBJECTPOINT, 5),
+
+ /* maximum number of entries in the connection cache */
+ CURLOPT(CURLMOPT_MAXCONNECTS, CURLOPTTYPE_LONG, 6),
+
+ /* maximum number of (pipelining) connections to one host */
+ CURLOPT(CURLMOPT_MAX_HOST_CONNECTIONS, CURLOPTTYPE_LONG, 7),
+
+ /* maximum number of requests in a pipeline */
+ CURLOPT(CURLMOPT_MAX_PIPELINE_LENGTH, CURLOPTTYPE_LONG, 8),
+
+ /* a connection with a content-length longer than this
+ will not be considered for pipelining */
+ CURLOPT(CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 9),
+
+ /* a connection with a chunk length longer than this
+ will not be considered for pipelining */
+ CURLOPT(CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE, CURLOPTTYPE_OFF_T, 10),
+
+ /* a list of site names(+port) that are blocked from pipelining */
+ CURLOPT(CURLMOPT_PIPELINING_SITE_BL, CURLOPTTYPE_OBJECTPOINT, 11),
+
+ /* a list of server types that are blocked from pipelining */
+ CURLOPT(CURLMOPT_PIPELINING_SERVER_BL, CURLOPTTYPE_OBJECTPOINT, 12),
+
+ /* maximum number of open connections in total */
+ CURLOPT(CURLMOPT_MAX_TOTAL_CONNECTIONS, CURLOPTTYPE_LONG, 13),
+
+ /* This is the server push callback function pointer */
+ CURLOPT(CURLMOPT_PUSHFUNCTION, CURLOPTTYPE_FUNCTIONPOINT, 14),
+
+ /* This is the argument passed to the server push callback */
+ CURLOPT(CURLMOPT_PUSHDATA, CURLOPTTYPE_OBJECTPOINT, 15),
+
+ /* maximum number of concurrent streams to support on a connection */
+ CURLOPT(CURLMOPT_MAX_CONCURRENT_STREAMS, CURLOPTTYPE_LONG, 16),
+
+ CURLMOPT_LASTENTRY /* the last unused */
+} CURLMoption;
+
+
+/*
+ * Name: curl_multi_setopt()
+ *
+ * Desc: Sets options for the multi handle.
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_setopt(CURLM *multi_handle,
+ CURLMoption option, ...);
+
+
+/*
+ * Name: curl_multi_assign()
+ *
+ * Desc: This function sets an association in the multi handle between the
+ * given socket and a private pointer of the application. This is
+ * (only) useful for curl_multi_socket uses.
+ *
+ * Returns: CURLM error code.
+ */
+CURL_EXTERN CURLMcode curl_multi_assign(CURLM *multi_handle,
+ curl_socket_t sockfd, void *sockp);
+
+
+/*
+ * Name: curl_push_callback
+ *
+ * Desc: This callback gets called when a new stream is being pushed by the
+ * server. It approves or denies the new stream. It can also decide
+ * to completely fail the connection.
+ *
+ * Returns: CURL_PUSH_OK, CURL_PUSH_DENY or CURL_PUSH_ERROROUT
+ */
+#define CURL_PUSH_OK 0
+#define CURL_PUSH_DENY 1
+#define CURL_PUSH_ERROROUT 2 /* added in 7.72.0 */
+
+struct curl_pushheaders; /* forward declaration only */
+
+CURL_EXTERN char *curl_pushheader_bynum(struct curl_pushheaders *h,
+ size_t num);
+CURL_EXTERN char *curl_pushheader_byname(struct curl_pushheaders *h,
+ const char *name);
+
+typedef int (*curl_push_callback)(CURL *parent,
+ CURL *easy,
+ size_t num_headers,
+ struct curl_pushheaders *headers,
+ void *userp);
+
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+
+#endif
diff --git a/include/libcurl/include/curl/options.h b/include/libcurl/include/curl/options.h
new file mode 100644
index 00000000..14373b55
--- /dev/null
+++ b/include/libcurl/include/curl/options.h
@@ -0,0 +1,68 @@
+#ifndef CURLINC_OPTIONS_H
+#define CURLINC_OPTIONS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2018 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+ CURLOT_LONG, /* long (a range of values) */
+ CURLOT_VALUES, /* (a defined set or bitmask) */
+ CURLOT_OFF_T, /* curl_off_t (a range of values) */
+ CURLOT_OBJECT, /* pointer (void *) */
+ CURLOT_STRING, /* (char * to zero terminated buffer) */
+ CURLOT_SLIST, /* (struct curl_slist *) */
+ CURLOT_CBPTR, /* (void * passed as-is to a callback) */
+ CURLOT_BLOB, /* blob (struct curl_blob *) */
+ CURLOT_FUNCTION /* function pointer */
+} curl_easytype;
+
+/* Flag bits */
+
+/* "alias" means it is provided for old programs to remain functional,
+ we prefer another name */
+#define CURLOT_FLAG_ALIAS (1<<0)
+
+/* The CURLOPTTYPE_* id ranges can still be used to figure out what type/size
+ to use for curl_easy_setopt() for the given id */
+struct curl_easyoption {
+ const char *name;
+ CURLoption id;
+ curl_easytype type;
+ unsigned int flags;
+};
+
+CURL_EXTERN const struct curl_easyoption *
+curl_easy_option_by_name(const char *name);
+
+CURL_EXTERN const struct curl_easyoption *
+curl_easy_option_by_id (CURLoption id);
+
+CURL_EXTERN const struct curl_easyoption *
+curl_easy_option_next(const struct curl_easyoption *prev);
+
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+#endif /* CURLINC_OPTIONS_H */
diff --git a/include/libcurl/include/curl/stdcheaders.h b/include/libcurl/include/curl/stdcheaders.h
new file mode 100644
index 00000000..60596c75
--- /dev/null
+++ b/include/libcurl/include/curl/stdcheaders.h
@@ -0,0 +1,33 @@
+#ifndef CURLINC_STDCHEADERS_H
+#define CURLINC_STDCHEADERS_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include <sys/types.h>
+
+size_t fread(void *, size_t, size_t, FILE *);
+size_t fwrite(const void *, size_t, size_t, FILE *);
+
+int strcasecmp(const char *, const char *);
+int strncasecmp(const char *, const char *, size_t);
+
+#endif /* CURLINC_STDCHEADERS_H */
diff --git a/include/libcurl/include/curl/system.h b/include/libcurl/include/curl/system.h
new file mode 100644
index 00000000..faf8fcf8
--- /dev/null
+++ b/include/libcurl/include/curl/system.h
@@ -0,0 +1,504 @@
+#ifndef CURLINC_SYSTEM_H
+#define CURLINC_SYSTEM_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2020, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/*
+ * Try to keep one section per platform, compiler and architecture, otherwise,
+ * if an existing section is reused for a different one and later on the
+ * original is adjusted, probably the piggybacking one can be adversely
+ * changed.
+ *
+ * In order to differentiate between platforms/compilers/architectures use
+ * only compiler built in predefined preprocessor symbols.
+ *
+ * curl_off_t
+ * ----------
+ *
+ * For any given platform/compiler curl_off_t must be typedef'ed to a 64-bit
+ * wide signed integral data type. The width of this data type must remain
+ * constant and independent of any possible large file support settings.
+ *
+ * As an exception to the above, curl_off_t shall be typedef'ed to a 32-bit
+ * wide signed integral data type if there is no 64-bit type.
+ *
+ * As a general rule, curl_off_t shall not be mapped to off_t. This rule shall
+ * only be violated if off_t is the only 64-bit data type available and the
+ * size of off_t is independent of large file support settings. Keep your
+ * build on the safe side avoiding an off_t gating. If you have a 64-bit
+ * off_t then take for sure that another 64-bit data type exists, dig deeper
+ * and you will find it.
+ *
+ */
+
+#if defined(__DJGPP__) || defined(__GO32__)
+# if defined(__DJGPP__) && (__DJGPP__ > 1)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__SALFORDC__)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__BORLANDC__)
+# if (__BORLANDC__ < 0x520)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# else
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__TURBOC__)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__WATCOMC__)
+# if defined(__386__)
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__POCC__)
+# if (__POCC__ < 280)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# elif defined(_MSC_VER)
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# else
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__LCC__)
+# if defined(__e2k__) /* MCST eLbrus C Compiler */
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+# else /* Local (or Little) C Compiler */
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+# endif
+
+#elif defined(__SYMBIAN32__)
+# if defined(__EABI__) /* Treat all ARM compilers equally */
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__CW32__)
+# pragma longlong on
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__VC32__)
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
+
+#elif defined(__MWERKS__)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(_WIN32_WCE)
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__MINGW32__)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_WS2TCPIP_H 1
+
+#elif defined(__VMS)
+# if defined(__VAX)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# else
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T unsigned int
+
+#elif defined(__OS400__)
+# if defined(__ILEC400__)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+# endif
+
+#elif defined(__MVS__)
+# if defined(__IBMC__) || defined(__IBMCPP__)
+# if defined(_ILP32)
+# elif defined(_LP64)
+# endif
+# if defined(_LONG_LONG)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(_LP64)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+# endif
+
+#elif defined(__370__)
+# if defined(__IBMC__) || defined(__IBMCPP__)
+# if defined(_ILP32)
+# elif defined(_LP64)
+# endif
+# if defined(_LONG_LONG)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(_LP64)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+# endif
+
+#elif defined(TPF)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+#elif defined(__TINYC__) /* also known as tcc */
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+
+#elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio */
+# if !defined(__LP64) && (defined(__ILP32) || \
+ defined(__i386) || \
+ defined(__sparcv8) || \
+ defined(__sparcv8plus))
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__LP64) || \
+ defined(__amd64) || defined(__sparcv9)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+
+#elif defined(__xlc__) /* IBM xlc compiler */
+# if !defined(_LP64)
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+
+/* ===================================== */
+/* KEEP MSVC THE PENULTIMATE ENTRY */
+/* ===================================== */
+
+#elif defined(_MSC_VER)
+# if (_MSC_VER >= 900) && (_INTEGRAL_MAX_BITS >= 64)
+# define CURL_TYPEOF_CURL_OFF_T __int64
+# define CURL_FORMAT_CURL_OFF_T "I64d"
+# define CURL_FORMAT_CURL_OFF_TU "I64u"
+# define CURL_SUFFIX_CURL_OFF_T i64
+# define CURL_SUFFIX_CURL_OFF_TU ui64
+# else
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+
+/* ===================================== */
+/* KEEP GENERIC GCC THE LAST ENTRY */
+/* ===================================== */
+
+#elif defined(__GNUC__) && !defined(_SCO_DS)
+# if !defined(__LP64__) && \
+ (defined(__ILP32__) || defined(__i386__) || defined(__hppa__) || \
+ defined(__ppc__) || defined(__powerpc__) || defined(__arm__) || \
+ defined(__sparc__) || defined(__mips__) || defined(__sh__) || \
+ defined(__XTENSA__) || \
+ (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 4) || \
+ (defined(__LONG_MAX__) && __LONG_MAX__ == 2147483647L))
+# define CURL_TYPEOF_CURL_OFF_T long long
+# define CURL_FORMAT_CURL_OFF_T "lld"
+# define CURL_FORMAT_CURL_OFF_TU "llu"
+# define CURL_SUFFIX_CURL_OFF_T LL
+# define CURL_SUFFIX_CURL_OFF_TU ULL
+# elif defined(__LP64__) || \
+ defined(__x86_64__) || defined(__ppc64__) || defined(__sparc64__) || \
+ defined(__e2k__) || \
+ (defined(__SIZEOF_LONG__) && __SIZEOF_LONG__ == 8) || \
+ (defined(__LONG_MAX__) && __LONG_MAX__ == 9223372036854775807L)
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# endif
+# define CURL_TYPEOF_CURL_SOCKLEN_T socklen_t
+# define CURL_PULL_SYS_TYPES_H 1
+# define CURL_PULL_SYS_SOCKET_H 1
+
+#else
+/* generic "safe guess" on old 32 bit style */
+# define CURL_TYPEOF_CURL_OFF_T long
+# define CURL_FORMAT_CURL_OFF_T "ld"
+# define CURL_FORMAT_CURL_OFF_TU "lu"
+# define CURL_SUFFIX_CURL_OFF_T L
+# define CURL_SUFFIX_CURL_OFF_TU UL
+# define CURL_TYPEOF_CURL_SOCKLEN_T int
+#endif
+
+#ifdef _AIX
+/* AIX needs <sys/poll.h> */
+#define CURL_PULL_SYS_POLL_H
+#endif
+
+
+/* CURL_PULL_WS2TCPIP_H is defined above when inclusion of header file */
+/* ws2tcpip.h is required here to properly make type definitions below. */
+#ifdef CURL_PULL_WS2TCPIP_H
+# include <winsock2.h>
+# include <windows.h>
+# include <ws2tcpip.h>
+#endif
+
+/* CURL_PULL_SYS_TYPES_H is defined above when inclusion of header file */
+/* sys/types.h is required here to properly make type definitions below. */
+#ifdef CURL_PULL_SYS_TYPES_H
+# include <sys/types.h>
+#endif
+
+/* CURL_PULL_SYS_SOCKET_H is defined above when inclusion of header file */
+/* sys/socket.h is required here to properly make type definitions below. */
+#ifdef CURL_PULL_SYS_SOCKET_H
+# include <sys/socket.h>
+#endif
+
+/* CURL_PULL_SYS_POLL_H is defined above when inclusion of header file */
+/* sys/poll.h is required here to properly make type definitions below. */
+#ifdef CURL_PULL_SYS_POLL_H
+# include <sys/poll.h>
+#endif
+
+/* Data type definition of curl_socklen_t. */
+#ifdef CURL_TYPEOF_CURL_SOCKLEN_T
+ typedef CURL_TYPEOF_CURL_SOCKLEN_T curl_socklen_t;
+#endif
+
+/* Data type definition of curl_off_t. */
+
+#ifdef CURL_TYPEOF_CURL_OFF_T
+ typedef CURL_TYPEOF_CURL_OFF_T curl_off_t;
+#endif
+
+/*
+ * CURL_ISOCPP and CURL_OFF_T_C definitions are done here in order to allow
+ * these to be visible and exported by the external libcurl interface API,
+ * while also making them visible to the library internals, simply including
+ * curl_setup.h, without actually needing to include curl.h internally.
+ * If some day this section would grow big enough, all this should be moved
+ * to its own header file.
+ */
+
+/*
+ * Figure out if we can use the ## preprocessor operator, which is supported
+ * by ISO/ANSI C and C++. Some compilers support it without setting __STDC__
+ * or __cplusplus so we need to carefully check for them too.
+ */
+
+#if defined(__STDC__) || defined(_MSC_VER) || defined(__cplusplus) || \
+ defined(__HP_aCC) || defined(__BORLANDC__) || defined(__LCC__) || \
+ defined(__POCC__) || defined(__SALFORDC__) || defined(__HIGHC__) || \
+ defined(__ILEC400__)
+ /* This compiler is believed to have an ISO compatible preprocessor */
+#define CURL_ISOCPP
+#else
+ /* This compiler is believed NOT to have an ISO compatible preprocessor */
+#undef CURL_ISOCPP
+#endif
+
+/*
+ * Macros for minimum-width signed and unsigned curl_off_t integer constants.
+ */
+
+#if defined(__BORLANDC__) && (__BORLANDC__ == 0x0551)
+# define CURLINC_OFF_T_C_HLPR2(x) x
+# define CURLINC_OFF_T_C_HLPR1(x) CURLINC_OFF_T_C_HLPR2(x)
+# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \
+ CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_T)
+# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val) ## \
+ CURLINC_OFF_T_C_HLPR1(CURL_SUFFIX_CURL_OFF_TU)
+#else
+# ifdef CURL_ISOCPP
+# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val ## Suffix
+# else
+# define CURLINC_OFF_T_C_HLPR2(Val,Suffix) Val/**/Suffix
+# endif
+# define CURLINC_OFF_T_C_HLPR1(Val,Suffix) CURLINC_OFF_T_C_HLPR2(Val,Suffix)
+# define CURL_OFF_T_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_T)
+# define CURL_OFF_TU_C(Val) CURLINC_OFF_T_C_HLPR1(Val,CURL_SUFFIX_CURL_OFF_TU)
+#endif
+
+#endif /* CURLINC_SYSTEM_H */
diff --git a/include/libcurl/include/curl/typecheck-gcc.h b/include/libcurl/include/curl/typecheck-gcc.h
new file mode 100644
index 00000000..9e14d8a3
--- /dev/null
+++ b/include/libcurl/include/curl/typecheck-gcc.h
@@ -0,0 +1,707 @@
+#ifndef CURLINC_TYPECHECK_GCC_H
+#define CURLINC_TYPECHECK_GCC_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 1998 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+/* wraps curl_easy_setopt() with typechecking */
+
+/* To add a new kind of warning, add an
+ * if(curlcheck_sometype_option(_curl_opt))
+ * if(!curlcheck_sometype(value))
+ * _curl_easy_setopt_err_sometype();
+ * block and define curlcheck_sometype_option, curlcheck_sometype and
+ * _curl_easy_setopt_err_sometype below
+ *
+ * NOTE: We use two nested 'if' statements here instead of the && operator, in
+ * order to work around gcc bug #32061. It affects only gcc 4.3.x/4.4.x
+ * when compiling with -Wlogical-op.
+ *
+ * To add an option that uses the same type as an existing option, you'll just
+ * need to extend the appropriate _curl_*_option macro
+ */
+#define curl_easy_setopt(handle, option, value) \
+ __extension__({ \
+ __typeof__(option) _curl_opt = option; \
+ if(__builtin_constant_p(_curl_opt)) { \
+ if(curlcheck_long_option(_curl_opt)) \
+ if(!curlcheck_long(value)) \
+ _curl_easy_setopt_err_long(); \
+ if(curlcheck_off_t_option(_curl_opt)) \
+ if(!curlcheck_off_t(value)) \
+ _curl_easy_setopt_err_curl_off_t(); \
+ if(curlcheck_string_option(_curl_opt)) \
+ if(!curlcheck_string(value)) \
+ _curl_easy_setopt_err_string(); \
+ if(curlcheck_write_cb_option(_curl_opt)) \
+ if(!curlcheck_write_cb(value)) \
+ _curl_easy_setopt_err_write_callback(); \
+ if((_curl_opt) == CURLOPT_RESOLVER_START_FUNCTION) \
+ if(!curlcheck_resolver_start_callback(value)) \
+ _curl_easy_setopt_err_resolver_start_callback(); \
+ if((_curl_opt) == CURLOPT_READFUNCTION) \
+ if(!curlcheck_read_cb(value)) \
+ _curl_easy_setopt_err_read_cb(); \
+ if((_curl_opt) == CURLOPT_IOCTLFUNCTION) \
+ if(!curlcheck_ioctl_cb(value)) \
+ _curl_easy_setopt_err_ioctl_cb(); \
+ if((_curl_opt) == CURLOPT_SOCKOPTFUNCTION) \
+ if(!curlcheck_sockopt_cb(value)) \
+ _curl_easy_setopt_err_sockopt_cb(); \
+ if((_curl_opt) == CURLOPT_OPENSOCKETFUNCTION) \
+ if(!curlcheck_opensocket_cb(value)) \
+ _curl_easy_setopt_err_opensocket_cb(); \
+ if((_curl_opt) == CURLOPT_PROGRESSFUNCTION) \
+ if(!curlcheck_progress_cb(value)) \
+ _curl_easy_setopt_err_progress_cb(); \
+ if((_curl_opt) == CURLOPT_DEBUGFUNCTION) \
+ if(!curlcheck_debug_cb(value)) \
+ _curl_easy_setopt_err_debug_cb(); \
+ if((_curl_opt) == CURLOPT_SSL_CTX_FUNCTION) \
+ if(!curlcheck_ssl_ctx_cb(value)) \
+ _curl_easy_setopt_err_ssl_ctx_cb(); \
+ if(curlcheck_conv_cb_option(_curl_opt)) \
+ if(!curlcheck_conv_cb(value)) \
+ _curl_easy_setopt_err_conv_cb(); \
+ if((_curl_opt) == CURLOPT_SEEKFUNCTION) \
+ if(!curlcheck_seek_cb(value)) \
+ _curl_easy_setopt_err_seek_cb(); \
+ if(curlcheck_cb_data_option(_curl_opt)) \
+ if(!curlcheck_cb_data(value)) \
+ _curl_easy_setopt_err_cb_data(); \
+ if((_curl_opt) == CURLOPT_ERRORBUFFER) \
+ if(!curlcheck_error_buffer(value)) \
+ _curl_easy_setopt_err_error_buffer(); \
+ if((_curl_opt) == CURLOPT_STDERR) \
+ if(!curlcheck_FILE(value)) \
+ _curl_easy_setopt_err_FILE(); \
+ if(curlcheck_postfields_option(_curl_opt)) \
+ if(!curlcheck_postfields(value)) \
+ _curl_easy_setopt_err_postfields(); \
+ if((_curl_opt) == CURLOPT_HTTPPOST) \
+ if(!curlcheck_arr((value), struct curl_httppost)) \
+ _curl_easy_setopt_err_curl_httpost(); \
+ if((_curl_opt) == CURLOPT_MIMEPOST) \
+ if(!curlcheck_ptr((value), curl_mime)) \
+ _curl_easy_setopt_err_curl_mimepost(); \
+ if(curlcheck_slist_option(_curl_opt)) \
+ if(!curlcheck_arr((value), struct curl_slist)) \
+ _curl_easy_setopt_err_curl_slist(); \
+ if((_curl_opt) == CURLOPT_SHARE) \
+ if(!curlcheck_ptr((value), CURLSH)) \
+ _curl_easy_setopt_err_CURLSH(); \
+ } \
+ curl_easy_setopt(handle, _curl_opt, value); \
+ })
+
+/* wraps curl_easy_getinfo() with typechecking */
+#define curl_easy_getinfo(handle, info, arg) \
+ __extension__({ \
+ __typeof__(info) _curl_info = info; \
+ if(__builtin_constant_p(_curl_info)) { \
+ if(curlcheck_string_info(_curl_info)) \
+ if(!curlcheck_arr((arg), char *)) \
+ _curl_easy_getinfo_err_string(); \
+ if(curlcheck_long_info(_curl_info)) \
+ if(!curlcheck_arr((arg), long)) \
+ _curl_easy_getinfo_err_long(); \
+ if(curlcheck_double_info(_curl_info)) \
+ if(!curlcheck_arr((arg), double)) \
+ _curl_easy_getinfo_err_double(); \
+ if(curlcheck_slist_info(_curl_info)) \
+ if(!curlcheck_arr((arg), struct curl_slist *)) \
+ _curl_easy_getinfo_err_curl_slist(); \
+ if(curlcheck_tlssessioninfo_info(_curl_info)) \
+ if(!curlcheck_arr((arg), struct curl_tlssessioninfo *)) \
+ _curl_easy_getinfo_err_curl_tlssesssioninfo(); \
+ if(curlcheck_certinfo_info(_curl_info)) \
+ if(!curlcheck_arr((arg), struct curl_certinfo *)) \
+ _curl_easy_getinfo_err_curl_certinfo(); \
+ if(curlcheck_socket_info(_curl_info)) \
+ if(!curlcheck_arr((arg), curl_socket_t)) \
+ _curl_easy_getinfo_err_curl_socket(); \
+ if(curlcheck_off_t_info(_curl_info)) \
+ if(!curlcheck_arr((arg), curl_off_t)) \
+ _curl_easy_getinfo_err_curl_off_t(); \
+ } \
+ curl_easy_getinfo(handle, _curl_info, arg); \
+ })
+
+/*
+ * For now, just make sure that the functions are called with three arguments
+ */
+#define curl_share_setopt(share,opt,param) curl_share_setopt(share,opt,param)
+#define curl_multi_setopt(handle,opt,param) curl_multi_setopt(handle,opt,param)
+
+
+/* the actual warnings, triggered by calling the _curl_easy_setopt_err*
+ * functions */
+
+/* To define a new warning, use _CURL_WARNING(identifier, "message") */
+#define CURLWARNING(id, message) \
+ static void __attribute__((__warning__(message))) \
+ __attribute__((__unused__)) __attribute__((__noinline__)) \
+ id(void) { __asm__(""); }
+
+CURLWARNING(_curl_easy_setopt_err_long,
+ "curl_easy_setopt expects a long argument for this option")
+CURLWARNING(_curl_easy_setopt_err_curl_off_t,
+ "curl_easy_setopt expects a curl_off_t argument for this option")
+CURLWARNING(_curl_easy_setopt_err_string,
+ "curl_easy_setopt expects a "
+ "string ('char *' or char[]) argument for this option"
+ )
+CURLWARNING(_curl_easy_setopt_err_write_callback,
+ "curl_easy_setopt expects a curl_write_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_resolver_start_callback,
+ "curl_easy_setopt expects a "
+ "curl_resolver_start_callback argument for this option"
+ )
+CURLWARNING(_curl_easy_setopt_err_read_cb,
+ "curl_easy_setopt expects a curl_read_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_ioctl_cb,
+ "curl_easy_setopt expects a curl_ioctl_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_sockopt_cb,
+ "curl_easy_setopt expects a curl_sockopt_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_opensocket_cb,
+ "curl_easy_setopt expects a "
+ "curl_opensocket_callback argument for this option"
+ )
+CURLWARNING(_curl_easy_setopt_err_progress_cb,
+ "curl_easy_setopt expects a curl_progress_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_debug_cb,
+ "curl_easy_setopt expects a curl_debug_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_ssl_ctx_cb,
+ "curl_easy_setopt expects a curl_ssl_ctx_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_conv_cb,
+ "curl_easy_setopt expects a curl_conv_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_seek_cb,
+ "curl_easy_setopt expects a curl_seek_callback argument for this option")
+CURLWARNING(_curl_easy_setopt_err_cb_data,
+ "curl_easy_setopt expects a "
+ "private data pointer as argument for this option")
+CURLWARNING(_curl_easy_setopt_err_error_buffer,
+ "curl_easy_setopt expects a "
+ "char buffer of CURL_ERROR_SIZE as argument for this option")
+CURLWARNING(_curl_easy_setopt_err_FILE,
+ "curl_easy_setopt expects a 'FILE *' argument for this option")
+CURLWARNING(_curl_easy_setopt_err_postfields,
+ "curl_easy_setopt expects a 'void *' or 'char *' argument for this option")
+CURLWARNING(_curl_easy_setopt_err_curl_httpost,
+ "curl_easy_setopt expects a 'struct curl_httppost *' "
+ "argument for this option")
+CURLWARNING(_curl_easy_setopt_err_curl_mimepost,
+ "curl_easy_setopt expects a 'curl_mime *' "
+ "argument for this option")
+CURLWARNING(_curl_easy_setopt_err_curl_slist,
+ "curl_easy_setopt expects a 'struct curl_slist *' argument for this option")
+CURLWARNING(_curl_easy_setopt_err_CURLSH,
+ "curl_easy_setopt expects a CURLSH* argument for this option")
+
+CURLWARNING(_curl_easy_getinfo_err_string,
+ "curl_easy_getinfo expects a pointer to 'char *' for this info")
+CURLWARNING(_curl_easy_getinfo_err_long,
+ "curl_easy_getinfo expects a pointer to long for this info")
+CURLWARNING(_curl_easy_getinfo_err_double,
+ "curl_easy_getinfo expects a pointer to double for this info")
+CURLWARNING(_curl_easy_getinfo_err_curl_slist,
+ "curl_easy_getinfo expects a pointer to 'struct curl_slist *' for this info")
+CURLWARNING(_curl_easy_getinfo_err_curl_tlssesssioninfo,
+ "curl_easy_getinfo expects a pointer to "
+ "'struct curl_tlssessioninfo *' for this info")
+CURLWARNING(_curl_easy_getinfo_err_curl_certinfo,
+ "curl_easy_getinfo expects a pointer to "
+ "'struct curl_certinfo *' for this info")
+CURLWARNING(_curl_easy_getinfo_err_curl_socket,
+ "curl_easy_getinfo expects a pointer to curl_socket_t for this info")
+CURLWARNING(_curl_easy_getinfo_err_curl_off_t,
+ "curl_easy_getinfo expects a pointer to curl_off_t for this info")
+
+/* groups of curl_easy_setops options that take the same type of argument */
+
+/* To add a new option to one of the groups, just add
+ * (option) == CURLOPT_SOMETHING
+ * to the or-expression. If the option takes a long or curl_off_t, you don't
+ * have to do anything
+ */
+
+/* evaluates to true if option takes a long argument */
+#define curlcheck_long_option(option) \
+ (0 < (option) && (option) < CURLOPTTYPE_OBJECTPOINT)
+
+#define curlcheck_off_t_option(option) \
+ (((option) > CURLOPTTYPE_OFF_T) && ((option) < CURLOPTTYPE_BLOB))
+
+/* evaluates to true if option takes a char* argument */
+#define curlcheck_string_option(option) \
+ ((option) == CURLOPT_ABSTRACT_UNIX_SOCKET || \
+ (option) == CURLOPT_ACCEPT_ENCODING || \
+ (option) == CURLOPT_ALTSVC || \
+ (option) == CURLOPT_CAINFO || \
+ (option) == CURLOPT_CAPATH || \
+ (option) == CURLOPT_COOKIE || \
+ (option) == CURLOPT_COOKIEFILE || \
+ (option) == CURLOPT_COOKIEJAR || \
+ (option) == CURLOPT_COOKIELIST || \
+ (option) == CURLOPT_CRLFILE || \
+ (option) == CURLOPT_CUSTOMREQUEST || \
+ (option) == CURLOPT_DEFAULT_PROTOCOL || \
+ (option) == CURLOPT_DNS_INTERFACE || \
+ (option) == CURLOPT_DNS_LOCAL_IP4 || \
+ (option) == CURLOPT_DNS_LOCAL_IP6 || \
+ (option) == CURLOPT_DNS_SERVERS || \
+ (option) == CURLOPT_DOH_URL || \
+ (option) == CURLOPT_EGDSOCKET || \
+ (option) == CURLOPT_FTPPORT || \
+ (option) == CURLOPT_FTP_ACCOUNT || \
+ (option) == CURLOPT_FTP_ALTERNATIVE_TO_USER || \
+ (option) == CURLOPT_HSTS || \
+ (option) == CURLOPT_INTERFACE || \
+ (option) == CURLOPT_ISSUERCERT || \
+ (option) == CURLOPT_KEYPASSWD || \
+ (option) == CURLOPT_KRBLEVEL || \
+ (option) == CURLOPT_LOGIN_OPTIONS || \
+ (option) == CURLOPT_MAIL_AUTH || \
+ (option) == CURLOPT_MAIL_FROM || \
+ (option) == CURLOPT_NETRC_FILE || \
+ (option) == CURLOPT_NOPROXY || \
+ (option) == CURLOPT_PASSWORD || \
+ (option) == CURLOPT_PINNEDPUBLICKEY || \
+ (option) == CURLOPT_PRE_PROXY || \
+ (option) == CURLOPT_PROXY || \
+ (option) == CURLOPT_PROXYPASSWORD || \
+ (option) == CURLOPT_PROXYUSERNAME || \
+ (option) == CURLOPT_PROXYUSERPWD || \
+ (option) == CURLOPT_PROXY_CAINFO || \
+ (option) == CURLOPT_PROXY_CAPATH || \
+ (option) == CURLOPT_PROXY_CRLFILE || \
+ (option) == CURLOPT_PROXY_ISSUERCERT || \
+ (option) == CURLOPT_PROXY_KEYPASSWD || \
+ (option) == CURLOPT_PROXY_PINNEDPUBLICKEY || \
+ (option) == CURLOPT_PROXY_SERVICE_NAME || \
+ (option) == CURLOPT_PROXY_SSLCERT || \
+ (option) == CURLOPT_PROXY_SSLCERTTYPE || \
+ (option) == CURLOPT_PROXY_SSLKEY || \
+ (option) == CURLOPT_PROXY_SSLKEYTYPE || \
+ (option) == CURLOPT_PROXY_SSL_CIPHER_LIST || \
+ (option) == CURLOPT_PROXY_TLS13_CIPHERS || \
+ (option) == CURLOPT_PROXY_TLSAUTH_PASSWORD || \
+ (option) == CURLOPT_PROXY_TLSAUTH_TYPE || \
+ (option) == CURLOPT_PROXY_TLSAUTH_USERNAME || \
+ (option) == CURLOPT_RANDOM_FILE || \
+ (option) == CURLOPT_RANGE || \
+ (option) == CURLOPT_REFERER || \
+ (option) == CURLOPT_REQUEST_TARGET || \
+ (option) == CURLOPT_RTSP_SESSION_ID || \
+ (option) == CURLOPT_RTSP_STREAM_URI || \
+ (option) == CURLOPT_RTSP_TRANSPORT || \
+ (option) == CURLOPT_SASL_AUTHZID || \
+ (option) == CURLOPT_SERVICE_NAME || \
+ (option) == CURLOPT_SOCKS5_GSSAPI_SERVICE || \
+ (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_MD5 || \
+ (option) == CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256 || \
+ (option) == CURLOPT_SSH_KNOWNHOSTS || \
+ (option) == CURLOPT_SSH_PRIVATE_KEYFILE || \
+ (option) == CURLOPT_SSH_PUBLIC_KEYFILE || \
+ (option) == CURLOPT_SSLCERT || \
+ (option) == CURLOPT_SSLCERTTYPE || \
+ (option) == CURLOPT_SSLENGINE || \
+ (option) == CURLOPT_SSLKEY || \
+ (option) == CURLOPT_SSLKEYTYPE || \
+ (option) == CURLOPT_SSL_CIPHER_LIST || \
+ (option) == CURLOPT_TLS13_CIPHERS || \
+ (option) == CURLOPT_TLSAUTH_PASSWORD || \
+ (option) == CURLOPT_TLSAUTH_TYPE || \
+ (option) == CURLOPT_TLSAUTH_USERNAME || \
+ (option) == CURLOPT_UNIX_SOCKET_PATH || \
+ (option) == CURLOPT_URL || \
+ (option) == CURLOPT_USERAGENT || \
+ (option) == CURLOPT_USERNAME || \
+ (option) == CURLOPT_AWS_SIGV4 || \
+ (option) == CURLOPT_USERPWD || \
+ (option) == CURLOPT_XOAUTH2_BEARER || \
+ (option) == CURLOPT_SSL_EC_CURVES || \
+ 0)
+
+/* evaluates to true if option takes a curl_write_callback argument */
+#define curlcheck_write_cb_option(option) \
+ ((option) == CURLOPT_HEADERFUNCTION || \
+ (option) == CURLOPT_WRITEFUNCTION)
+
+/* evaluates to true if option takes a curl_conv_callback argument */
+#define curlcheck_conv_cb_option(option) \
+ ((option) == CURLOPT_CONV_TO_NETWORK_FUNCTION || \
+ (option) == CURLOPT_CONV_FROM_NETWORK_FUNCTION || \
+ (option) == CURLOPT_CONV_FROM_UTF8_FUNCTION)
+
+/* evaluates to true if option takes a data argument to pass to a callback */
+#define curlcheck_cb_data_option(option) \
+ ((option) == CURLOPT_CHUNK_DATA || \
+ (option) == CURLOPT_CLOSESOCKETDATA || \
+ (option) == CURLOPT_DEBUGDATA || \
+ (option) == CURLOPT_FNMATCH_DATA || \
+ (option) == CURLOPT_HEADERDATA || \
+ (option) == CURLOPT_HSTSREADDATA || \
+ (option) == CURLOPT_HSTSWRITEDATA || \
+ (option) == CURLOPT_INTERLEAVEDATA || \
+ (option) == CURLOPT_IOCTLDATA || \
+ (option) == CURLOPT_OPENSOCKETDATA || \
+ (option) == CURLOPT_PREREQDATA || \
+ (option) == CURLOPT_PROGRESSDATA || \
+ (option) == CURLOPT_READDATA || \
+ (option) == CURLOPT_SEEKDATA || \
+ (option) == CURLOPT_SOCKOPTDATA || \
+ (option) == CURLOPT_SSH_KEYDATA || \
+ (option) == CURLOPT_SSL_CTX_DATA || \
+ (option) == CURLOPT_WRITEDATA || \
+ (option) == CURLOPT_RESOLVER_START_DATA || \
+ (option) == CURLOPT_TRAILERDATA || \
+ 0)
+
+/* evaluates to true if option takes a POST data argument (void* or char*) */
+#define curlcheck_postfields_option(option) \
+ ((option) == CURLOPT_POSTFIELDS || \
+ (option) == CURLOPT_COPYPOSTFIELDS || \
+ 0)
+
+/* evaluates to true if option takes a struct curl_slist * argument */
+#define curlcheck_slist_option(option) \
+ ((option) == CURLOPT_HTTP200ALIASES || \
+ (option) == CURLOPT_HTTPHEADER || \
+ (option) == CURLOPT_MAIL_RCPT || \
+ (option) == CURLOPT_POSTQUOTE || \
+ (option) == CURLOPT_PREQUOTE || \
+ (option) == CURLOPT_PROXYHEADER || \
+ (option) == CURLOPT_QUOTE || \
+ (option) == CURLOPT_RESOLVE || \
+ (option) == CURLOPT_TELNETOPTIONS || \
+ (option) == CURLOPT_CONNECT_TO || \
+ 0)
+
+/* groups of curl_easy_getinfo infos that take the same type of argument */
+
+/* evaluates to true if info expects a pointer to char * argument */
+#define curlcheck_string_info(info) \
+ (CURLINFO_STRING < (info) && (info) < CURLINFO_LONG && \
+ (info) != CURLINFO_PRIVATE)
+
+/* evaluates to true if info expects a pointer to long argument */
+#define curlcheck_long_info(info) \
+ (CURLINFO_LONG < (info) && (info) < CURLINFO_DOUBLE)
+
+/* evaluates to true if info expects a pointer to double argument */
+#define curlcheck_double_info(info) \
+ (CURLINFO_DOUBLE < (info) && (info) < CURLINFO_SLIST)
+
+/* true if info expects a pointer to struct curl_slist * argument */
+#define curlcheck_slist_info(info) \
+ (((info) == CURLINFO_SSL_ENGINES) || ((info) == CURLINFO_COOKIELIST))
+
+/* true if info expects a pointer to struct curl_tlssessioninfo * argument */
+#define curlcheck_tlssessioninfo_info(info) \
+ (((info) == CURLINFO_TLS_SSL_PTR) || ((info) == CURLINFO_TLS_SESSION))
+
+/* true if info expects a pointer to struct curl_certinfo * argument */
+#define curlcheck_certinfo_info(info) ((info) == CURLINFO_CERTINFO)
+
+/* true if info expects a pointer to struct curl_socket_t argument */
+#define curlcheck_socket_info(info) \
+ (CURLINFO_SOCKET < (info) && (info) < CURLINFO_OFF_T)
+
+/* true if info expects a pointer to curl_off_t argument */
+#define curlcheck_off_t_info(info) \
+ (CURLINFO_OFF_T < (info))
+
+
+/* typecheck helpers -- check whether given expression has requested type*/
+
+/* For pointers, you can use the curlcheck_ptr/curlcheck_arr macros,
+ * otherwise define a new macro. Search for __builtin_types_compatible_p
+ * in the GCC manual.
+ * NOTE: these macros MUST NOT EVALUATE their arguments! The argument is
+ * the actual expression passed to the curl_easy_setopt macro. This
+ * means that you can only apply the sizeof and __typeof__ operators, no
+ * == or whatsoever.
+ */
+
+/* XXX: should evaluate to true if expr is a pointer */
+#define curlcheck_any_ptr(expr) \
+ (sizeof(expr) == sizeof(void *))
+
+/* evaluates to true if expr is NULL */
+/* XXX: must not evaluate expr, so this check is not accurate */
+#define curlcheck_NULL(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), __typeof__(NULL)))
+
+/* evaluates to true if expr is type*, const type* or NULL */
+#define curlcheck_ptr(expr, type) \
+ (curlcheck_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), type *) || \
+ __builtin_types_compatible_p(__typeof__(expr), const type *))
+
+/* evaluates to true if expr is one of type[], type*, NULL or const type* */
+#define curlcheck_arr(expr, type) \
+ (curlcheck_ptr((expr), type) || \
+ __builtin_types_compatible_p(__typeof__(expr), type []))
+
+/* evaluates to true if expr is a string */
+#define curlcheck_string(expr) \
+ (curlcheck_arr((expr), char) || \
+ curlcheck_arr((expr), signed char) || \
+ curlcheck_arr((expr), unsigned char))
+
+/* evaluates to true if expr is a long (no matter the signedness)
+ * XXX: for now, int is also accepted (and therefore short and char, which
+ * are promoted to int when passed to a variadic function) */
+#define curlcheck_long(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), long) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed long) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned long) || \
+ __builtin_types_compatible_p(__typeof__(expr), int) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed int) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned int) || \
+ __builtin_types_compatible_p(__typeof__(expr), short) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed short) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned short) || \
+ __builtin_types_compatible_p(__typeof__(expr), char) || \
+ __builtin_types_compatible_p(__typeof__(expr), signed char) || \
+ __builtin_types_compatible_p(__typeof__(expr), unsigned char))
+
+/* evaluates to true if expr is of type curl_off_t */
+#define curlcheck_off_t(expr) \
+ (__builtin_types_compatible_p(__typeof__(expr), curl_off_t))
+
+/* evaluates to true if expr is abuffer suitable for CURLOPT_ERRORBUFFER */
+/* XXX: also check size of an char[] array? */
+#define curlcheck_error_buffer(expr) \
+ (curlcheck_NULL(expr) || \
+ __builtin_types_compatible_p(__typeof__(expr), char *) || \
+ __builtin_types_compatible_p(__typeof__(expr), char[]))
+
+/* evaluates to true if expr is of type (const) void* or (const) FILE* */
+#if 0
+#define curlcheck_cb_data(expr) \
+ (curlcheck_ptr((expr), void) || \
+ curlcheck_ptr((expr), FILE))
+#else /* be less strict */
+#define curlcheck_cb_data(expr) \
+ curlcheck_any_ptr(expr)
+#endif
+
+/* evaluates to true if expr is of type FILE* */
+#define curlcheck_FILE(expr) \
+ (curlcheck_NULL(expr) || \
+ (__builtin_types_compatible_p(__typeof__(expr), FILE *)))
+
+/* evaluates to true if expr can be passed as POST data (void* or char*) */
+#define curlcheck_postfields(expr) \
+ (curlcheck_ptr((expr), void) || \
+ curlcheck_arr((expr), char) || \
+ curlcheck_arr((expr), unsigned char))
+
+/* helper: __builtin_types_compatible_p distinguishes between functions and
+ * function pointers, hide it */
+#define curlcheck_cb_compatible(func, type) \
+ (__builtin_types_compatible_p(__typeof__(func), type) || \
+ __builtin_types_compatible_p(__typeof__(func) *, type))
+
+/* evaluates to true if expr is of type curl_resolver_start_callback */
+#define curlcheck_resolver_start_callback(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_resolver_start_callback))
+
+/* evaluates to true if expr is of type curl_read_callback or "similar" */
+#define curlcheck_read_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), __typeof__(fread) *) || \
+ curlcheck_cb_compatible((expr), curl_read_callback) || \
+ curlcheck_cb_compatible((expr), _curl_read_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_read_callback2) || \
+ curlcheck_cb_compatible((expr), _curl_read_callback3) || \
+ curlcheck_cb_compatible((expr), _curl_read_callback4) || \
+ curlcheck_cb_compatible((expr), _curl_read_callback5) || \
+ curlcheck_cb_compatible((expr), _curl_read_callback6))
+typedef size_t (*_curl_read_callback1)(char *, size_t, size_t, void *);
+typedef size_t (*_curl_read_callback2)(char *, size_t, size_t, const void *);
+typedef size_t (*_curl_read_callback3)(char *, size_t, size_t, FILE *);
+typedef size_t (*_curl_read_callback4)(void *, size_t, size_t, void *);
+typedef size_t (*_curl_read_callback5)(void *, size_t, size_t, const void *);
+typedef size_t (*_curl_read_callback6)(void *, size_t, size_t, FILE *);
+
+/* evaluates to true if expr is of type curl_write_callback or "similar" */
+#define curlcheck_write_cb(expr) \
+ (curlcheck_read_cb(expr) || \
+ curlcheck_cb_compatible((expr), __typeof__(fwrite) *) || \
+ curlcheck_cb_compatible((expr), curl_write_callback) || \
+ curlcheck_cb_compatible((expr), _curl_write_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_write_callback2) || \
+ curlcheck_cb_compatible((expr), _curl_write_callback3) || \
+ curlcheck_cb_compatible((expr), _curl_write_callback4) || \
+ curlcheck_cb_compatible((expr), _curl_write_callback5) || \
+ curlcheck_cb_compatible((expr), _curl_write_callback6))
+typedef size_t (*_curl_write_callback1)(const char *, size_t, size_t, void *);
+typedef size_t (*_curl_write_callback2)(const char *, size_t, size_t,
+ const void *);
+typedef size_t (*_curl_write_callback3)(const char *, size_t, size_t, FILE *);
+typedef size_t (*_curl_write_callback4)(const void *, size_t, size_t, void *);
+typedef size_t (*_curl_write_callback5)(const void *, size_t, size_t,
+ const void *);
+typedef size_t (*_curl_write_callback6)(const void *, size_t, size_t, FILE *);
+
+/* evaluates to true if expr is of type curl_ioctl_callback or "similar" */
+#define curlcheck_ioctl_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_ioctl_callback) || \
+ curlcheck_cb_compatible((expr), _curl_ioctl_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_ioctl_callback2) || \
+ curlcheck_cb_compatible((expr), _curl_ioctl_callback3) || \
+ curlcheck_cb_compatible((expr), _curl_ioctl_callback4))
+typedef curlioerr (*_curl_ioctl_callback1)(CURL *, int, void *);
+typedef curlioerr (*_curl_ioctl_callback2)(CURL *, int, const void *);
+typedef curlioerr (*_curl_ioctl_callback3)(CURL *, curliocmd, void *);
+typedef curlioerr (*_curl_ioctl_callback4)(CURL *, curliocmd, const void *);
+
+/* evaluates to true if expr is of type curl_sockopt_callback or "similar" */
+#define curlcheck_sockopt_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_sockopt_callback) || \
+ curlcheck_cb_compatible((expr), _curl_sockopt_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_sockopt_callback2))
+typedef int (*_curl_sockopt_callback1)(void *, curl_socket_t, curlsocktype);
+typedef int (*_curl_sockopt_callback2)(const void *, curl_socket_t,
+ curlsocktype);
+
+/* evaluates to true if expr is of type curl_opensocket_callback or
+ "similar" */
+#define curlcheck_opensocket_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_opensocket_callback) || \
+ curlcheck_cb_compatible((expr), _curl_opensocket_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_opensocket_callback2) || \
+ curlcheck_cb_compatible((expr), _curl_opensocket_callback3) || \
+ curlcheck_cb_compatible((expr), _curl_opensocket_callback4))
+typedef curl_socket_t (*_curl_opensocket_callback1)
+ (void *, curlsocktype, struct curl_sockaddr *);
+typedef curl_socket_t (*_curl_opensocket_callback2)
+ (void *, curlsocktype, const struct curl_sockaddr *);
+typedef curl_socket_t (*_curl_opensocket_callback3)
+ (const void *, curlsocktype, struct curl_sockaddr *);
+typedef curl_socket_t (*_curl_opensocket_callback4)
+ (const void *, curlsocktype, const struct curl_sockaddr *);
+
+/* evaluates to true if expr is of type curl_progress_callback or "similar" */
+#define curlcheck_progress_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_progress_callback) || \
+ curlcheck_cb_compatible((expr), _curl_progress_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_progress_callback2))
+typedef int (*_curl_progress_callback1)(void *,
+ double, double, double, double);
+typedef int (*_curl_progress_callback2)(const void *,
+ double, double, double, double);
+
+/* evaluates to true if expr is of type curl_debug_callback or "similar" */
+#define curlcheck_debug_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_debug_callback) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback2) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback3) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback4) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback5) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback6) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback7) || \
+ curlcheck_cb_compatible((expr), _curl_debug_callback8))
+typedef int (*_curl_debug_callback1) (CURL *,
+ curl_infotype, char *, size_t, void *);
+typedef int (*_curl_debug_callback2) (CURL *,
+ curl_infotype, char *, size_t, const void *);
+typedef int (*_curl_debug_callback3) (CURL *,
+ curl_infotype, const char *, size_t, void *);
+typedef int (*_curl_debug_callback4) (CURL *,
+ curl_infotype, const char *, size_t, const void *);
+typedef int (*_curl_debug_callback5) (CURL *,
+ curl_infotype, unsigned char *, size_t, void *);
+typedef int (*_curl_debug_callback6) (CURL *,
+ curl_infotype, unsigned char *, size_t, const void *);
+typedef int (*_curl_debug_callback7) (CURL *,
+ curl_infotype, const unsigned char *, size_t, void *);
+typedef int (*_curl_debug_callback8) (CURL *,
+ curl_infotype, const unsigned char *, size_t, const void *);
+
+/* evaluates to true if expr is of type curl_ssl_ctx_callback or "similar" */
+/* this is getting even messier... */
+#define curlcheck_ssl_ctx_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_ssl_ctx_callback) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback2) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback3) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback4) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback5) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback6) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback7) || \
+ curlcheck_cb_compatible((expr), _curl_ssl_ctx_callback8))
+typedef CURLcode (*_curl_ssl_ctx_callback1)(CURL *, void *, void *);
+typedef CURLcode (*_curl_ssl_ctx_callback2)(CURL *, void *, const void *);
+typedef CURLcode (*_curl_ssl_ctx_callback3)(CURL *, const void *, void *);
+typedef CURLcode (*_curl_ssl_ctx_callback4)(CURL *, const void *,
+ const void *);
+#ifdef HEADER_SSL_H
+/* hack: if we included OpenSSL's ssl.h, we know about SSL_CTX
+ * this will of course break if we're included before OpenSSL headers...
+ */
+typedef CURLcode (*_curl_ssl_ctx_callback5)(CURL *, SSL_CTX *, void *);
+typedef CURLcode (*_curl_ssl_ctx_callback6)(CURL *, SSL_CTX *, const void *);
+typedef CURLcode (*_curl_ssl_ctx_callback7)(CURL *, const SSL_CTX *, void *);
+typedef CURLcode (*_curl_ssl_ctx_callback8)(CURL *, const SSL_CTX *,
+ const void *);
+#else
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback5;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback6;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback7;
+typedef _curl_ssl_ctx_callback1 _curl_ssl_ctx_callback8;
+#endif
+
+/* evaluates to true if expr is of type curl_conv_callback or "similar" */
+#define curlcheck_conv_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_conv_callback) || \
+ curlcheck_cb_compatible((expr), _curl_conv_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_conv_callback2) || \
+ curlcheck_cb_compatible((expr), _curl_conv_callback3) || \
+ curlcheck_cb_compatible((expr), _curl_conv_callback4))
+typedef CURLcode (*_curl_conv_callback1)(char *, size_t length);
+typedef CURLcode (*_curl_conv_callback2)(const char *, size_t length);
+typedef CURLcode (*_curl_conv_callback3)(void *, size_t length);
+typedef CURLcode (*_curl_conv_callback4)(const void *, size_t length);
+
+/* evaluates to true if expr is of type curl_seek_callback or "similar" */
+#define curlcheck_seek_cb(expr) \
+ (curlcheck_NULL(expr) || \
+ curlcheck_cb_compatible((expr), curl_seek_callback) || \
+ curlcheck_cb_compatible((expr), _curl_seek_callback1) || \
+ curlcheck_cb_compatible((expr), _curl_seek_callback2))
+typedef CURLcode (*_curl_seek_callback1)(void *, curl_off_t, int);
+typedef CURLcode (*_curl_seek_callback2)(const void *, curl_off_t, int);
+
+
+#endif /* CURLINC_TYPECHECK_GCC_H */
diff --git a/include/libcurl/include/curl/urlapi.h b/include/libcurl/include/curl/urlapi.h
new file mode 100644
index 00000000..a475f91b
--- /dev/null
+++ b/include/libcurl/include/curl/urlapi.h
@@ -0,0 +1,145 @@
+#ifndef CURLINC_URLAPI_H
+#define CURLINC_URLAPI_H
+/***************************************************************************
+ * _ _ ____ _
+ * Project ___| | | | _ \| |
+ * / __| | | | |_) | |
+ * | (__| |_| | _ <| |___
+ * \___|\___/|_| \_\_____|
+ *
+ * Copyright (C) 2018 - 2021, Daniel Stenberg, <daniel@haxx.se>, et al.
+ *
+ * This software is licensed as described in the file COPYING, which
+ * you should have received as part of this distribution. The terms
+ * are also available at https://curl.se/docs/copyright.html.
+ *
+ * You may opt to use, copy, modify, merge, publish, distribute and/or sell
+ * copies of the Software, and permit persons to whom the Software is
+ * furnished to do so, under the terms of the COPYING file.
+ *
+ * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
+ * KIND, either express or implied.
+ *
+ ***************************************************************************/
+
+#include "curl.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* the error codes for the URL API */
+typedef enum {
+ CURLUE_OK,
+ CURLUE_BAD_HANDLE, /* 1 */
+ CURLUE_BAD_PARTPOINTER, /* 2 */
+ CURLUE_MALFORMED_INPUT, /* 3 */
+ CURLUE_BAD_PORT_NUMBER, /* 4 */
+ CURLUE_UNSUPPORTED_SCHEME, /* 5 */
+ CURLUE_URLDECODE, /* 6 */
+ CURLUE_OUT_OF_MEMORY, /* 7 */
+ CURLUE_USER_NOT_ALLOWED, /* 8 */
+ CURLUE_UNKNOWN_PART, /* 9 */
+ CURLUE_NO_SCHEME, /* 10 */
+ CURLUE_NO_USER, /* 11 */
+ CURLUE_NO_PASSWORD, /* 12 */
+ CURLUE_NO_OPTIONS, /* 13 */
+ CURLUE_NO_HOST, /* 14 */
+ CURLUE_NO_PORT, /* 15 */
+ CURLUE_NO_QUERY, /* 16 */
+ CURLUE_NO_FRAGMENT, /* 17 */
+ CURLUE_NO_ZONEID, /* 18 */
+ CURLUE_BAD_FILE_URL, /* 19 */
+ CURLUE_BAD_FRAGMENT, /* 20 */
+ CURLUE_BAD_HOSTNAME, /* 21 */
+ CURLUE_BAD_IPV6, /* 22 */
+ CURLUE_BAD_LOGIN, /* 23 */
+ CURLUE_BAD_PASSWORD, /* 24 */
+ CURLUE_BAD_PATH, /* 25 */
+ CURLUE_BAD_QUERY, /* 26 */
+ CURLUE_BAD_SCHEME, /* 27 */
+ CURLUE_BAD_SLASHES, /* 28 */
+ CURLUE_BAD_USER, /* 29 */
+ CURLUE_LAST
+} CURLUcode;
+
+typedef enum {
+ CURLUPART_URL,
+ CURLUPART_SCHEME,
+ CURLUPART_USER,
+ CURLUPART_PASSWORD,
+ CURLUPART_OPTIONS,
+ CURLUPART_HOST,
+ CURLUPART_PORT,
+ CURLUPART_PATH,
+ CURLUPART_QUERY,
+ CURLUPART_FRAGMENT,
+ CURLUPART_ZONEID /* added in 7.65.0 */
+} CURLUPart;
+
+#define CURLU_DEFAULT_PORT (1<<0) /* return default port number */
+#define CURLU_NO_DEFAULT_PORT (1<<1) /* act as if no port number was set,
+ if the port number matches the
+ default for the scheme */
+#define CURLU_DEFAULT_SCHEME (1<<2) /* return default scheme if
+ missing */
+#define CURLU_NON_SUPPORT_SCHEME (1<<3) /* allow non-supported scheme */
+#define CURLU_PATH_AS_IS (1<<4) /* leave dot sequences */
+#define CURLU_DISALLOW_USER (1<<5) /* no user+password allowed */
+#define CURLU_URLDECODE (1<<6) /* URL decode on get */
+#define CURLU_URLENCODE (1<<7) /* URL encode on set */
+#define CURLU_APPENDQUERY (1<<8) /* append a form style part */
+#define CURLU_GUESS_SCHEME (1<<9) /* legacy curl-style guessing */
+#define CURLU_NO_AUTHORITY (1<<10) /* Allow empty authority when the
+ scheme is unknown. */
+#define CURLU_ALLOW_SPACE (1<<11) /* Allow spaces in the URL */
+
+typedef struct Curl_URL CURLU;
+
+/*
+ * curl_url() creates a new CURLU handle and returns a pointer to it.
+ * Must be freed with curl_url_cleanup().
+ */
+CURL_EXTERN CURLU *curl_url(void);
+
+/*
+ * curl_url_cleanup() frees the CURLU handle and related resources used for
+ * the URL parsing. It will not free strings previously returned with the URL
+ * API.
+ */
+CURL_EXTERN void curl_url_cleanup(CURLU *handle);
+
+/*
+ * curl_url_dup() duplicates a CURLU handle and returns a new copy. The new
+ * handle must also be freed with curl_url_cleanup().
+ */
+CURL_EXTERN CURLU *curl_url_dup(CURLU *in);
+
+/*
+ * curl_url_get() extracts a specific part of the URL from a CURLU
+ * handle. Returns error code. The returned pointer MUST be freed with
+ * curl_free() afterwards.
+ */
+CURL_EXTERN CURLUcode curl_url_get(CURLU *handle, CURLUPart what,
+ char **part, unsigned int flags);
+
+/*
+ * curl_url_set() sets a specific part of the URL in a CURLU handle. Returns
+ * error code. The passed in string will be copied. Passing a NULL instead of
+ * a part string, clears that part.
+ */
+CURL_EXTERN CURLUcode curl_url_set(CURLU *handle, CURLUPart what,
+ const char *part, unsigned int flags);
+
+/*
+ * curl_url_strerror() turns a CURLUcode value into the equivalent human
+ * readable error string. This is useful for printing meaningful error
+ * messages.
+ */
+CURL_EXTERN const char *curl_url_strerror(CURLUcode);
+
+#ifdef __cplusplus
+} /* end of extern "C" */
+#endif
+
+#endif /* CURLINC_URLAPI_H */
diff --git a/include/libcurl/lib/libcurl_a.lib b/include/libcurl/lib/libcurl_a.lib
new file mode 100644
index 00000000..32b917c9
--- /dev/null
+++ b/include/libcurl/lib/libcurl_a.lib
Binary files differ
diff --git a/include/libssl_static.lib b/include/libssl_static.lib
new file mode 100644
index 00000000..f7916421
--- /dev/null
+++ b/include/libssl_static.lib
Binary files differ
diff --git a/include/openssl/__DECC_INCLUDE_EPILOGUE.H b/include/openssl/__DECC_INCLUDE_EPILOGUE.H
new file mode 100644
index 00000000..d251d0a0
--- /dev/null
+++ b/include/openssl/__DECC_INCLUDE_EPILOGUE.H
@@ -0,0 +1,22 @@
+/*
+ * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This file is only used by HP C/C++ on VMS, and is included automatically
+ * after each header file from this directory
+ */
+
+/*
+ * The C++ compiler doesn't understand these pragmas, even though it
+ * understands the corresponding command line qualifier.
+ */
+#ifndef __cplusplus
+/* restore state. Must correspond to the save in __decc_include_prologue.h */
+# pragma names restore
+#endif
diff --git a/include/openssl/__DECC_INCLUDE_PROLOGUE.H b/include/openssl/__DECC_INCLUDE_PROLOGUE.H
new file mode 100644
index 00000000..91ac6b33
--- /dev/null
+++ b/include/openssl/__DECC_INCLUDE_PROLOGUE.H
@@ -0,0 +1,26 @@
+/*
+ * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This file is only used by HP C/C++ on VMS, and is included automatically
+ * after each header file from this directory
+ */
+
+/*
+ * The C++ compiler doesn't understand these pragmas, even though it
+ * understands the corresponding command line qualifier.
+ */
+#ifndef __cplusplus
+/* save state */
+# pragma names save
+/* have the compiler shorten symbols larger than 31 chars to 23 chars
+ * followed by a 8 hex char CRC
+ */
+# pragma names as_is,shortened
+#endif
diff --git a/include/openssl/aes.h b/include/openssl/aes.h
new file mode 100644
index 00000000..d0f9dfc6
--- /dev/null
+++ b/include/openssl/aes.h
@@ -0,0 +1,111 @@
+/*
+ * Copyright 2002-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_AES_H
+# define OPENSSL_AES_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_AES_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# include <stddef.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define AES_BLOCK_SIZE 16
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+# define AES_ENCRYPT 1
+# define AES_DECRYPT 0
+
+# define AES_MAXNR 14
+
+
+/* This should be a hidden type, but EVP requires that the size be known */
+struct aes_key_st {
+# ifdef AES_LONG
+ unsigned long rd_key[4 * (AES_MAXNR + 1)];
+# else
+ unsigned int rd_key[4 * (AES_MAXNR + 1)];
+# endif
+ int rounds;
+};
+typedef struct aes_key_st AES_KEY;
+
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *AES_options(void);
+OSSL_DEPRECATEDIN_3_0
+int AES_set_encrypt_key(const unsigned char *userKey, const int bits,
+ AES_KEY *key);
+OSSL_DEPRECATEDIN_3_0
+int AES_set_decrypt_key(const unsigned char *userKey, const int bits,
+ AES_KEY *key);
+OSSL_DEPRECATEDIN_3_0
+void AES_encrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+OSSL_DEPRECATEDIN_3_0
+void AES_decrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key);
+OSSL_DEPRECATEDIN_3_0
+void AES_ecb_encrypt(const unsigned char *in, unsigned char *out,
+ const AES_KEY *key, const int enc);
+OSSL_DEPRECATEDIN_3_0
+void AES_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char *ivec, const int enc);
+OSSL_DEPRECATEDIN_3_0
+void AES_cfb128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char *ivec, int *num, const int enc);
+OSSL_DEPRECATEDIN_3_0
+void AES_cfb1_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char *ivec, int *num, const int enc);
+OSSL_DEPRECATEDIN_3_0
+void AES_cfb8_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char *ivec, int *num, const int enc);
+OSSL_DEPRECATEDIN_3_0
+void AES_ofb128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char *ivec, int *num);
+
+/* NB: the IV is _two_ blocks long */
+OSSL_DEPRECATEDIN_3_0
+void AES_ige_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key,
+ unsigned char *ivec, const int enc);
+/* NB: the IV is _four_ blocks long */
+OSSL_DEPRECATEDIN_3_0
+void AES_bi_ige_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const AES_KEY *key, const AES_KEY *key2,
+ const unsigned char *ivec, const int enc);
+OSSL_DEPRECATEDIN_3_0
+int AES_wrap_key(AES_KEY *key, const unsigned char *iv,
+ unsigned char *out, const unsigned char *in,
+ unsigned int inlen);
+OSSL_DEPRECATEDIN_3_0
+int AES_unwrap_key(AES_KEY *key, const unsigned char *iv,
+ unsigned char *out, const unsigned char *in,
+ unsigned int inlen);
+# endif
+
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/asn1.h b/include/openssl/asn1.h
new file mode 100644
index 00000000..aada23dc
--- /dev/null
+++ b/include/openssl/asn1.h
@@ -0,0 +1,1128 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\asn1.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_ASN1_H
+# define OPENSSL_ASN1_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ASN1_H
+# endif
+
+# include <time.h>
+# include <openssl/e_os2.h>
+# include <openssl/opensslconf.h>
+# include <openssl/bio.h>
+# include <openssl/safestack.h>
+# include <openssl/asn1err.h>
+# include <openssl/symhacks.h>
+
+# include <openssl/types.h>
+# include <openssl/bn.h>
+
+# ifdef OPENSSL_BUILD_SHLIBCRYPTO
+# undef OPENSSL_EXTERN
+# define OPENSSL_EXTERN OPENSSL_EXPORT
+# endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define V_ASN1_UNIVERSAL 0x00
+# define V_ASN1_APPLICATION 0x40
+# define V_ASN1_CONTEXT_SPECIFIC 0x80
+# define V_ASN1_PRIVATE 0xc0
+
+# define V_ASN1_CONSTRUCTED 0x20
+# define V_ASN1_PRIMITIVE_TAG 0x1f
+# define V_ASN1_PRIMATIVE_TAG /*compat*/ V_ASN1_PRIMITIVE_TAG
+
+# define V_ASN1_APP_CHOOSE -2/* let the recipient choose */
+# define V_ASN1_OTHER -3/* used in ASN1_TYPE */
+# define V_ASN1_ANY -4/* used in ASN1 template code */
+
+# define V_ASN1_UNDEF -1
+/* ASN.1 tag values */
+# define V_ASN1_EOC 0
+# define V_ASN1_BOOLEAN 1 /**/
+# define V_ASN1_INTEGER 2
+# define V_ASN1_BIT_STRING 3
+# define V_ASN1_OCTET_STRING 4
+# define V_ASN1_NULL 5
+# define V_ASN1_OBJECT 6
+# define V_ASN1_OBJECT_DESCRIPTOR 7
+# define V_ASN1_EXTERNAL 8
+# define V_ASN1_REAL 9
+# define V_ASN1_ENUMERATED 10
+# define V_ASN1_UTF8STRING 12
+# define V_ASN1_SEQUENCE 16
+# define V_ASN1_SET 17
+# define V_ASN1_NUMERICSTRING 18 /**/
+# define V_ASN1_PRINTABLESTRING 19
+# define V_ASN1_T61STRING 20
+# define V_ASN1_TELETEXSTRING 20/* alias */
+# define V_ASN1_VIDEOTEXSTRING 21 /**/
+# define V_ASN1_IA5STRING 22
+# define V_ASN1_UTCTIME 23
+# define V_ASN1_GENERALIZEDTIME 24 /**/
+# define V_ASN1_GRAPHICSTRING 25 /**/
+# define V_ASN1_ISO64STRING 26 /**/
+# define V_ASN1_VISIBLESTRING 26/* alias */
+# define V_ASN1_GENERALSTRING 27 /**/
+# define V_ASN1_UNIVERSALSTRING 28 /**/
+# define V_ASN1_BMPSTRING 30
+
+/*
+ * NB the constants below are used internally by ASN1_INTEGER
+ * and ASN1_ENUMERATED to indicate the sign. They are *not* on
+ * the wire tag values.
+ */
+
+# define V_ASN1_NEG 0x100
+# define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG)
+# define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG)
+
+/* For use with d2i_ASN1_type_bytes() */
+# define B_ASN1_NUMERICSTRING 0x0001
+# define B_ASN1_PRINTABLESTRING 0x0002
+# define B_ASN1_T61STRING 0x0004
+# define B_ASN1_TELETEXSTRING 0x0004
+# define B_ASN1_VIDEOTEXSTRING 0x0008
+# define B_ASN1_IA5STRING 0x0010
+# define B_ASN1_GRAPHICSTRING 0x0020
+# define B_ASN1_ISO64STRING 0x0040
+# define B_ASN1_VISIBLESTRING 0x0040
+# define B_ASN1_GENERALSTRING 0x0080
+# define B_ASN1_UNIVERSALSTRING 0x0100
+# define B_ASN1_OCTET_STRING 0x0200
+# define B_ASN1_BIT_STRING 0x0400
+# define B_ASN1_BMPSTRING 0x0800
+# define B_ASN1_UNKNOWN 0x1000
+# define B_ASN1_UTF8STRING 0x2000
+# define B_ASN1_UTCTIME 0x4000
+# define B_ASN1_GENERALIZEDTIME 0x8000
+# define B_ASN1_SEQUENCE 0x10000
+/* For use with ASN1_mbstring_copy() */
+# define MBSTRING_FLAG 0x1000
+# define MBSTRING_UTF8 (MBSTRING_FLAG)
+# define MBSTRING_ASC (MBSTRING_FLAG|1)
+# define MBSTRING_BMP (MBSTRING_FLAG|2)
+# define MBSTRING_UNIV (MBSTRING_FLAG|4)
+# define SMIME_OLDMIME 0x400
+# define SMIME_CRLFEOL 0x800
+# define SMIME_STREAM 0x1000
+
+/* Stacks for types not otherwise defined in this header */
+SKM_DEFINE_STACK_OF_INTERNAL(X509_ALGOR, X509_ALGOR, X509_ALGOR)
+#define sk_X509_ALGOR_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ALGOR_sk_type(sk))
+#define sk_X509_ALGOR_value(sk, idx) ((X509_ALGOR *)OPENSSL_sk_value(ossl_check_const_X509_ALGOR_sk_type(sk), (idx)))
+#define sk_X509_ALGOR_new(cmp) ((STACK_OF(X509_ALGOR) *)OPENSSL_sk_new(ossl_check_X509_ALGOR_compfunc_type(cmp)))
+#define sk_X509_ALGOR_new_null() ((STACK_OF(X509_ALGOR) *)OPENSSL_sk_new_null())
+#define sk_X509_ALGOR_new_reserve(cmp, n) ((STACK_OF(X509_ALGOR) *)OPENSSL_sk_new_reserve(ossl_check_X509_ALGOR_compfunc_type(cmp), (n)))
+#define sk_X509_ALGOR_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ALGOR_sk_type(sk), (n))
+#define sk_X509_ALGOR_free(sk) OPENSSL_sk_free(ossl_check_X509_ALGOR_sk_type(sk))
+#define sk_X509_ALGOR_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ALGOR_sk_type(sk))
+#define sk_X509_ALGOR_delete(sk, i) ((X509_ALGOR *)OPENSSL_sk_delete(ossl_check_X509_ALGOR_sk_type(sk), (i)))
+#define sk_X509_ALGOR_delete_ptr(sk, ptr) ((X509_ALGOR *)OPENSSL_sk_delete_ptr(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_type(ptr)))
+#define sk_X509_ALGOR_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_type(ptr))
+#define sk_X509_ALGOR_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_type(ptr))
+#define sk_X509_ALGOR_pop(sk) ((X509_ALGOR *)OPENSSL_sk_pop(ossl_check_X509_ALGOR_sk_type(sk)))
+#define sk_X509_ALGOR_shift(sk) ((X509_ALGOR *)OPENSSL_sk_shift(ossl_check_X509_ALGOR_sk_type(sk)))
+#define sk_X509_ALGOR_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ALGOR_sk_type(sk),ossl_check_X509_ALGOR_freefunc_type(freefunc))
+#define sk_X509_ALGOR_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_type(ptr), (idx))
+#define sk_X509_ALGOR_set(sk, idx, ptr) ((X509_ALGOR *)OPENSSL_sk_set(ossl_check_X509_ALGOR_sk_type(sk), (idx), ossl_check_X509_ALGOR_type(ptr)))
+#define sk_X509_ALGOR_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_type(ptr))
+#define sk_X509_ALGOR_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_type(ptr))
+#define sk_X509_ALGOR_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_type(ptr), pnum)
+#define sk_X509_ALGOR_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ALGOR_sk_type(sk))
+#define sk_X509_ALGOR_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ALGOR_sk_type(sk))
+#define sk_X509_ALGOR_dup(sk) ((STACK_OF(X509_ALGOR) *)OPENSSL_sk_dup(ossl_check_const_X509_ALGOR_sk_type(sk)))
+#define sk_X509_ALGOR_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ALGOR) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_copyfunc_type(copyfunc), ossl_check_X509_ALGOR_freefunc_type(freefunc)))
+#define sk_X509_ALGOR_set_cmp_func(sk, cmp) ((sk_X509_ALGOR_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ALGOR_sk_type(sk), ossl_check_X509_ALGOR_compfunc_type(cmp)))
+
+
+
+# define ASN1_STRING_FLAG_BITS_LEFT 0x08/* Set if 0x07 has bits left value */
+/*
+ * This indicates that the ASN1_STRING is not a real value but just a place
+ * holder for the location where indefinite length constructed data should be
+ * inserted in the memory buffer
+ */
+# define ASN1_STRING_FLAG_NDEF 0x010
+
+/*
+ * This flag is used by the CMS code to indicate that a string is not
+ * complete and is a place holder for content when it had all been accessed.
+ * The flag will be reset when content has been written to it.
+ */
+
+# define ASN1_STRING_FLAG_CONT 0x020
+/*
+ * This flag is used by ASN1 code to indicate an ASN1_STRING is an MSTRING
+ * type.
+ */
+# define ASN1_STRING_FLAG_MSTRING 0x040
+/* String is embedded and only content should be freed */
+# define ASN1_STRING_FLAG_EMBED 0x080
+/* String should be parsed in RFC 5280's time format */
+# define ASN1_STRING_FLAG_X509_TIME 0x100
+/* This is the base type that holds just about everything :-) */
+struct asn1_string_st {
+ int length;
+ int type;
+ unsigned char *data;
+ /*
+ * The value of the following field depends on the type being held. It
+ * is mostly being used for BIT_STRING so if the input data has a
+ * non-zero 'unused bits' value, it will be handled correctly
+ */
+ long flags;
+};
+
+/*
+ * ASN1_ENCODING structure: this is used to save the received encoding of an
+ * ASN1 type. This is useful to get round problems with invalid encodings
+ * which can break signatures.
+ */
+
+typedef struct ASN1_ENCODING_st {
+ unsigned char *enc; /* DER encoding */
+ long len; /* Length of encoding */
+ int modified; /* set to 1 if 'enc' is invalid */
+} ASN1_ENCODING;
+
+/* Used with ASN1 LONG type: if a long is set to this it is omitted */
+# define ASN1_LONG_UNDEF 0x7fffffffL
+
+# define STABLE_FLAGS_MALLOC 0x01
+/*
+ * A zero passed to ASN1_STRING_TABLE_new_add for the flags is interpreted
+ * as "don't change" and STABLE_FLAGS_MALLOC is always set. By setting
+ * STABLE_FLAGS_MALLOC only we can clear the existing value. Use the alias
+ * STABLE_FLAGS_CLEAR to reflect this.
+ */
+# define STABLE_FLAGS_CLEAR STABLE_FLAGS_MALLOC
+# define STABLE_NO_MASK 0x02
+# define DIRSTRING_TYPE \
+ (B_ASN1_PRINTABLESTRING|B_ASN1_T61STRING|B_ASN1_BMPSTRING|B_ASN1_UTF8STRING)
+# define PKCS9STRING_TYPE (DIRSTRING_TYPE|B_ASN1_IA5STRING)
+
+struct asn1_string_table_st {
+ int nid;
+ long minsize;
+ long maxsize;
+ unsigned long mask;
+ unsigned long flags;
+};
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_STRING_TABLE, ASN1_STRING_TABLE, ASN1_STRING_TABLE)
+#define sk_ASN1_STRING_TABLE_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_STRING_TABLE_sk_type(sk))
+#define sk_ASN1_STRING_TABLE_value(sk, idx) ((ASN1_STRING_TABLE *)OPENSSL_sk_value(ossl_check_const_ASN1_STRING_TABLE_sk_type(sk), (idx)))
+#define sk_ASN1_STRING_TABLE_new(cmp) ((STACK_OF(ASN1_STRING_TABLE) *)OPENSSL_sk_new(ossl_check_ASN1_STRING_TABLE_compfunc_type(cmp)))
+#define sk_ASN1_STRING_TABLE_new_null() ((STACK_OF(ASN1_STRING_TABLE) *)OPENSSL_sk_new_null())
+#define sk_ASN1_STRING_TABLE_new_reserve(cmp, n) ((STACK_OF(ASN1_STRING_TABLE) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_STRING_TABLE_compfunc_type(cmp), (n)))
+#define sk_ASN1_STRING_TABLE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_STRING_TABLE_sk_type(sk), (n))
+#define sk_ASN1_STRING_TABLE_free(sk) OPENSSL_sk_free(ossl_check_ASN1_STRING_TABLE_sk_type(sk))
+#define sk_ASN1_STRING_TABLE_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_STRING_TABLE_sk_type(sk))
+#define sk_ASN1_STRING_TABLE_delete(sk, i) ((ASN1_STRING_TABLE *)OPENSSL_sk_delete(ossl_check_ASN1_STRING_TABLE_sk_type(sk), (i)))
+#define sk_ASN1_STRING_TABLE_delete_ptr(sk, ptr) ((ASN1_STRING_TABLE *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_type(ptr)))
+#define sk_ASN1_STRING_TABLE_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_type(ptr))
+#define sk_ASN1_STRING_TABLE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_type(ptr))
+#define sk_ASN1_STRING_TABLE_pop(sk) ((ASN1_STRING_TABLE *)OPENSSL_sk_pop(ossl_check_ASN1_STRING_TABLE_sk_type(sk)))
+#define sk_ASN1_STRING_TABLE_shift(sk) ((ASN1_STRING_TABLE *)OPENSSL_sk_shift(ossl_check_ASN1_STRING_TABLE_sk_type(sk)))
+#define sk_ASN1_STRING_TABLE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_STRING_TABLE_sk_type(sk),ossl_check_ASN1_STRING_TABLE_freefunc_type(freefunc))
+#define sk_ASN1_STRING_TABLE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_type(ptr), (idx))
+#define sk_ASN1_STRING_TABLE_set(sk, idx, ptr) ((ASN1_STRING_TABLE *)OPENSSL_sk_set(ossl_check_ASN1_STRING_TABLE_sk_type(sk), (idx), ossl_check_ASN1_STRING_TABLE_type(ptr)))
+#define sk_ASN1_STRING_TABLE_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_type(ptr))
+#define sk_ASN1_STRING_TABLE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_type(ptr))
+#define sk_ASN1_STRING_TABLE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_type(ptr), pnum)
+#define sk_ASN1_STRING_TABLE_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_STRING_TABLE_sk_type(sk))
+#define sk_ASN1_STRING_TABLE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_STRING_TABLE_sk_type(sk))
+#define sk_ASN1_STRING_TABLE_dup(sk) ((STACK_OF(ASN1_STRING_TABLE) *)OPENSSL_sk_dup(ossl_check_const_ASN1_STRING_TABLE_sk_type(sk)))
+#define sk_ASN1_STRING_TABLE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_STRING_TABLE) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_copyfunc_type(copyfunc), ossl_check_ASN1_STRING_TABLE_freefunc_type(freefunc)))
+#define sk_ASN1_STRING_TABLE_set_cmp_func(sk, cmp) ((sk_ASN1_STRING_TABLE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_STRING_TABLE_sk_type(sk), ossl_check_ASN1_STRING_TABLE_compfunc_type(cmp)))
+
+
+/* size limits: this stuff is taken straight from RFC2459 */
+
+# define ub_name 32768
+# define ub_common_name 64
+# define ub_locality_name 128
+# define ub_state_name 128
+# define ub_organization_name 64
+# define ub_organization_unit_name 64
+# define ub_title 64
+# define ub_email_address 128
+
+/*
+ * Declarations for template structures: for full definitions see asn1t.h
+ */
+typedef struct ASN1_TEMPLATE_st ASN1_TEMPLATE;
+typedef struct ASN1_TLC_st ASN1_TLC;
+/* This is just an opaque pointer */
+typedef struct ASN1_VALUE_st ASN1_VALUE;
+
+/* Declare ASN1 functions: the implement macro in in asn1t.h */
+
+/*
+ * The mysterious 'extern' that's passed to some macros is innocuous,
+ * and is there to quiet pre-C99 compilers that may complain about empty
+ * arguments in macro calls.
+ */
+
+# define DECLARE_ASN1_FUNCTIONS_attr(attr, type) \
+ DECLARE_ASN1_FUNCTIONS_name_attr(attr, type, type)
+# define DECLARE_ASN1_FUNCTIONS(type) \
+ DECLARE_ASN1_FUNCTIONS_attr(extern, type)
+
+# define DECLARE_ASN1_ALLOC_FUNCTIONS_attr(attr, type) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(attr, type, type)
+# define DECLARE_ASN1_ALLOC_FUNCTIONS(type) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_attr(extern, type)
+
+# define DECLARE_ASN1_FUNCTIONS_name_attr(attr, type, name) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(attr, type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(attr, type, name)
+# define DECLARE_ASN1_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_FUNCTIONS_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_attr(attr, type, itname, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(attr, type, name) \
+ DECLARE_ASN1_ITEM_attr(attr, itname)
+# define DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_attr(extern, type, itname, name)
+
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(attr, type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_attr(attr, type, name, name)
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(attr, type, name) \
+ attr type *d2i_##name(type **a, const unsigned char **in, long len); \
+ attr int i2d_##name(const type *a, unsigned char **out);
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_only(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(extern, type, name)
+
+# define DECLARE_ASN1_NDEF_FUNCTION_attr(attr, name) \
+ attr int i2d_##name##_NDEF(const name *a, unsigned char **out);
+# define DECLARE_ASN1_NDEF_FUNCTION(name) \
+ DECLARE_ASN1_NDEF_FUNCTION_attr(extern, name)
+
+# define DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(attr, type, name) \
+ attr type *name##_new(void); \
+ attr void name##_free(type *a);
+# define DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_DUP_FUNCTION_attr(attr, type) \
+ DECLARE_ASN1_DUP_FUNCTION_name_attr(attr, type, type)
+# define DECLARE_ASN1_DUP_FUNCTION(type) \
+ DECLARE_ASN1_DUP_FUNCTION_attr(extern, type)
+
+# define DECLARE_ASN1_DUP_FUNCTION_name_attr(attr, type, name) \
+ attr type *name##_dup(const type *a);
+# define DECLARE_ASN1_DUP_FUNCTION_name(type, name) \
+ DECLARE_ASN1_DUP_FUNCTION_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_PRINT_FUNCTION_attr(attr, stname) \
+ DECLARE_ASN1_PRINT_FUNCTION_fname_attr(attr, stname, stname)
+# define DECLARE_ASN1_PRINT_FUNCTION(stname) \
+ DECLARE_ASN1_PRINT_FUNCTION_attr(extern, stname)
+
+# define DECLARE_ASN1_PRINT_FUNCTION_fname_attr(attr, stname, fname) \
+ attr int fname##_print_ctx(BIO *out, const stname *x, int indent, \
+ const ASN1_PCTX *pctx);
+# define DECLARE_ASN1_PRINT_FUNCTION_fname(stname, fname) \
+ DECLARE_ASN1_PRINT_FUNCTION_fname_attr(extern, stname, fname)
+
+# define D2I_OF(type) type *(*)(type **,const unsigned char **,long)
+# define I2D_OF(type) int (*)(const type *,unsigned char **)
+
+# define CHECKED_D2I_OF(type, d2i) \
+ ((d2i_of_void*) (1 ? d2i : ((D2I_OF(type))0)))
+# define CHECKED_I2D_OF(type, i2d) \
+ ((i2d_of_void*) (1 ? i2d : ((I2D_OF(type))0)))
+# define CHECKED_NEW_OF(type, xnew) \
+ ((void *(*)(void)) (1 ? xnew : ((type *(*)(void))0)))
+# define CHECKED_PTR_OF(type, p) \
+ ((void*) (1 ? p : (type*)0))
+# define CHECKED_PPTR_OF(type, p) \
+ ((void**) (1 ? p : (type**)0))
+
+# define TYPEDEF_D2I_OF(type) typedef type *d2i_of_##type(type **,const unsigned char **,long)
+# define TYPEDEF_I2D_OF(type) typedef int i2d_of_##type(const type *,unsigned char **)
+# define TYPEDEF_D2I2D_OF(type) TYPEDEF_D2I_OF(type); TYPEDEF_I2D_OF(type)
+
+typedef void *d2i_of_void(void **, const unsigned char **, long);
+typedef int i2d_of_void(const void *, unsigned char **);
+
+/*-
+ * The following macros and typedefs allow an ASN1_ITEM
+ * to be embedded in a structure and referenced. Since
+ * the ASN1_ITEM pointers need to be globally accessible
+ * (possibly from shared libraries) they may exist in
+ * different forms. On platforms that support it the
+ * ASN1_ITEM structure itself will be globally exported.
+ * Other platforms will export a function that returns
+ * an ASN1_ITEM pointer.
+ *
+ * To handle both cases transparently the macros below
+ * should be used instead of hard coding an ASN1_ITEM
+ * pointer in a structure.
+ *
+ * The structure will look like this:
+ *
+ * typedef struct SOMETHING_st {
+ * ...
+ * ASN1_ITEM_EXP *iptr;
+ * ...
+ * } SOMETHING;
+ *
+ * It would be initialised as e.g.:
+ *
+ * SOMETHING somevar = {...,ASN1_ITEM_ref(X509),...};
+ *
+ * and the actual pointer extracted with:
+ *
+ * const ASN1_ITEM *it = ASN1_ITEM_ptr(somevar.iptr);
+ *
+ * Finally an ASN1_ITEM pointer can be extracted from an
+ * appropriate reference with: ASN1_ITEM_rptr(X509). This
+ * would be used when a function takes an ASN1_ITEM * argument.
+ *
+ */
+
+
+/*
+ * Platforms that can't easily handle shared global variables are declared as
+ * functions returning ASN1_ITEM pointers.
+ */
+
+/* ASN1_ITEM pointer exported type */
+typedef const ASN1_ITEM *ASN1_ITEM_EXP (void);
+
+/* Macro to obtain ASN1_ITEM pointer from exported type */
+# define ASN1_ITEM_ptr(iptr) (iptr())
+
+/* Macro to include ASN1_ITEM pointer from base type */
+# define ASN1_ITEM_ref(iptr) (iptr##_it)
+
+# define ASN1_ITEM_rptr(ref) (ref##_it())
+
+# define DECLARE_ASN1_ITEM_attr(attr, name) \
+ attr const ASN1_ITEM * name##_it(void);
+# define DECLARE_ASN1_ITEM(name) \
+ DECLARE_ASN1_ITEM_attr(extern, name)
+
+/* Parameters used by ASN1_STRING_print_ex() */
+
+/*
+ * These determine which characters to escape: RFC2253 special characters,
+ * control characters and MSB set characters
+ */
+
+# define ASN1_STRFLGS_ESC_2253 1
+# define ASN1_STRFLGS_ESC_CTRL 2
+# define ASN1_STRFLGS_ESC_MSB 4
+
+/* Lower 8 bits are reserved as an output type specifier */
+# define ASN1_DTFLGS_TYPE_MASK 0x0FUL
+# define ASN1_DTFLGS_RFC822 0x00UL
+# define ASN1_DTFLGS_ISO8601 0x01UL
+
+/*
+ * This flag determines how we do escaping: normally RC2253 backslash only,
+ * set this to use backslash and quote.
+ */
+
+# define ASN1_STRFLGS_ESC_QUOTE 8
+
+/* These three flags are internal use only. */
+
+/* Character is a valid PrintableString character */
+# define CHARTYPE_PRINTABLESTRING 0x10
+/* Character needs escaping if it is the first character */
+# define CHARTYPE_FIRST_ESC_2253 0x20
+/* Character needs escaping if it is the last character */
+# define CHARTYPE_LAST_ESC_2253 0x40
+
+/*
+ * NB the internal flags are safely reused below by flags handled at the top
+ * level.
+ */
+
+/*
+ * If this is set we convert all character strings to UTF8 first
+ */
+
+# define ASN1_STRFLGS_UTF8_CONVERT 0x10
+
+/*
+ * If this is set we don't attempt to interpret content: just assume all
+ * strings are 1 byte per character. This will produce some pretty odd
+ * looking output!
+ */
+
+# define ASN1_STRFLGS_IGNORE_TYPE 0x20
+
+/* If this is set we include the string type in the output */
+# define ASN1_STRFLGS_SHOW_TYPE 0x40
+
+/*
+ * This determines which strings to display and which to 'dump' (hex dump of
+ * content octets or DER encoding). We can only dump non character strings or
+ * everything. If we don't dump 'unknown' they are interpreted as character
+ * strings with 1 octet per character and are subject to the usual escaping
+ * options.
+ */
+
+# define ASN1_STRFLGS_DUMP_ALL 0x80
+# define ASN1_STRFLGS_DUMP_UNKNOWN 0x100
+
+/*
+ * These determine what 'dumping' does, we can dump the content octets or the
+ * DER encoding: both use the RFC2253 #XXXXX notation.
+ */
+
+# define ASN1_STRFLGS_DUMP_DER 0x200
+
+/*
+ * This flag specifies that RC2254 escaping shall be performed.
+ */
+#define ASN1_STRFLGS_ESC_2254 0x400
+
+/*
+ * All the string flags consistent with RFC2253, escaping control characters
+ * isn't essential in RFC2253 but it is advisable anyway.
+ */
+
+# define ASN1_STRFLGS_RFC2253 (ASN1_STRFLGS_ESC_2253 | \
+ ASN1_STRFLGS_ESC_CTRL | \
+ ASN1_STRFLGS_ESC_MSB | \
+ ASN1_STRFLGS_UTF8_CONVERT | \
+ ASN1_STRFLGS_DUMP_UNKNOWN | \
+ ASN1_STRFLGS_DUMP_DER)
+
+
+struct asn1_type_st {
+ int type;
+ union {
+ char *ptr;
+ ASN1_BOOLEAN boolean;
+ ASN1_STRING *asn1_string;
+ ASN1_OBJECT *object;
+ ASN1_INTEGER *integer;
+ ASN1_ENUMERATED *enumerated;
+ ASN1_BIT_STRING *bit_string;
+ ASN1_OCTET_STRING *octet_string;
+ ASN1_PRINTABLESTRING *printablestring;
+ ASN1_T61STRING *t61string;
+ ASN1_IA5STRING *ia5string;
+ ASN1_GENERALSTRING *generalstring;
+ ASN1_BMPSTRING *bmpstring;
+ ASN1_UNIVERSALSTRING *universalstring;
+ ASN1_UTCTIME *utctime;
+ ASN1_GENERALIZEDTIME *generalizedtime;
+ ASN1_VISIBLESTRING *visiblestring;
+ ASN1_UTF8STRING *utf8string;
+ /*
+ * set and sequence are left complete and still contain the set or
+ * sequence bytes
+ */
+ ASN1_STRING *set;
+ ASN1_STRING *sequence;
+ ASN1_VALUE *asn1_value;
+ } value;
+};
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_TYPE, ASN1_TYPE, ASN1_TYPE)
+#define sk_ASN1_TYPE_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_TYPE_sk_type(sk))
+#define sk_ASN1_TYPE_value(sk, idx) ((ASN1_TYPE *)OPENSSL_sk_value(ossl_check_const_ASN1_TYPE_sk_type(sk), (idx)))
+#define sk_ASN1_TYPE_new(cmp) ((STACK_OF(ASN1_TYPE) *)OPENSSL_sk_new(ossl_check_ASN1_TYPE_compfunc_type(cmp)))
+#define sk_ASN1_TYPE_new_null() ((STACK_OF(ASN1_TYPE) *)OPENSSL_sk_new_null())
+#define sk_ASN1_TYPE_new_reserve(cmp, n) ((STACK_OF(ASN1_TYPE) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_TYPE_compfunc_type(cmp), (n)))
+#define sk_ASN1_TYPE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_TYPE_sk_type(sk), (n))
+#define sk_ASN1_TYPE_free(sk) OPENSSL_sk_free(ossl_check_ASN1_TYPE_sk_type(sk))
+#define sk_ASN1_TYPE_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_TYPE_sk_type(sk))
+#define sk_ASN1_TYPE_delete(sk, i) ((ASN1_TYPE *)OPENSSL_sk_delete(ossl_check_ASN1_TYPE_sk_type(sk), (i)))
+#define sk_ASN1_TYPE_delete_ptr(sk, ptr) ((ASN1_TYPE *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_type(ptr)))
+#define sk_ASN1_TYPE_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_type(ptr))
+#define sk_ASN1_TYPE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_type(ptr))
+#define sk_ASN1_TYPE_pop(sk) ((ASN1_TYPE *)OPENSSL_sk_pop(ossl_check_ASN1_TYPE_sk_type(sk)))
+#define sk_ASN1_TYPE_shift(sk) ((ASN1_TYPE *)OPENSSL_sk_shift(ossl_check_ASN1_TYPE_sk_type(sk)))
+#define sk_ASN1_TYPE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_TYPE_sk_type(sk),ossl_check_ASN1_TYPE_freefunc_type(freefunc))
+#define sk_ASN1_TYPE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_type(ptr), (idx))
+#define sk_ASN1_TYPE_set(sk, idx, ptr) ((ASN1_TYPE *)OPENSSL_sk_set(ossl_check_ASN1_TYPE_sk_type(sk), (idx), ossl_check_ASN1_TYPE_type(ptr)))
+#define sk_ASN1_TYPE_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_type(ptr))
+#define sk_ASN1_TYPE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_type(ptr))
+#define sk_ASN1_TYPE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_type(ptr), pnum)
+#define sk_ASN1_TYPE_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_TYPE_sk_type(sk))
+#define sk_ASN1_TYPE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_TYPE_sk_type(sk))
+#define sk_ASN1_TYPE_dup(sk) ((STACK_OF(ASN1_TYPE) *)OPENSSL_sk_dup(ossl_check_const_ASN1_TYPE_sk_type(sk)))
+#define sk_ASN1_TYPE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_TYPE) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_copyfunc_type(copyfunc), ossl_check_ASN1_TYPE_freefunc_type(freefunc)))
+#define sk_ASN1_TYPE_set_cmp_func(sk, cmp) ((sk_ASN1_TYPE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_TYPE_sk_type(sk), ossl_check_ASN1_TYPE_compfunc_type(cmp)))
+
+
+typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY;
+
+DECLARE_ASN1_ENCODE_FUNCTIONS_name(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY)
+DECLARE_ASN1_ENCODE_FUNCTIONS_name(ASN1_SEQUENCE_ANY, ASN1_SET_ANY)
+
+/* This is used to contain a list of bit names */
+typedef struct BIT_STRING_BITNAME_st {
+ int bitnum;
+ const char *lname;
+ const char *sname;
+} BIT_STRING_BITNAME;
+
+# define B_ASN1_TIME \
+ B_ASN1_UTCTIME | \
+ B_ASN1_GENERALIZEDTIME
+
+# define B_ASN1_PRINTABLE \
+ B_ASN1_NUMERICSTRING| \
+ B_ASN1_PRINTABLESTRING| \
+ B_ASN1_T61STRING| \
+ B_ASN1_IA5STRING| \
+ B_ASN1_BIT_STRING| \
+ B_ASN1_UNIVERSALSTRING|\
+ B_ASN1_BMPSTRING|\
+ B_ASN1_UTF8STRING|\
+ B_ASN1_SEQUENCE|\
+ B_ASN1_UNKNOWN
+
+# define B_ASN1_DIRECTORYSTRING \
+ B_ASN1_PRINTABLESTRING| \
+ B_ASN1_TELETEXSTRING|\
+ B_ASN1_BMPSTRING|\
+ B_ASN1_UNIVERSALSTRING|\
+ B_ASN1_UTF8STRING
+
+# define B_ASN1_DISPLAYTEXT \
+ B_ASN1_IA5STRING| \
+ B_ASN1_VISIBLESTRING| \
+ B_ASN1_BMPSTRING|\
+ B_ASN1_UTF8STRING
+
+DECLARE_ASN1_ALLOC_FUNCTIONS_name(ASN1_TYPE, ASN1_TYPE)
+DECLARE_ASN1_ENCODE_FUNCTIONS(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
+
+int ASN1_TYPE_get(const ASN1_TYPE *a);
+void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value);
+int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value);
+int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b);
+
+ASN1_TYPE *ASN1_TYPE_pack_sequence(const ASN1_ITEM *it, void *s, ASN1_TYPE **t);
+void *ASN1_TYPE_unpack_sequence(const ASN1_ITEM *it, const ASN1_TYPE *t);
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_OBJECT, ASN1_OBJECT, ASN1_OBJECT)
+#define sk_ASN1_OBJECT_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_OBJECT_sk_type(sk))
+#define sk_ASN1_OBJECT_value(sk, idx) ((ASN1_OBJECT *)OPENSSL_sk_value(ossl_check_const_ASN1_OBJECT_sk_type(sk), (idx)))
+#define sk_ASN1_OBJECT_new(cmp) ((STACK_OF(ASN1_OBJECT) *)OPENSSL_sk_new(ossl_check_ASN1_OBJECT_compfunc_type(cmp)))
+#define sk_ASN1_OBJECT_new_null() ((STACK_OF(ASN1_OBJECT) *)OPENSSL_sk_new_null())
+#define sk_ASN1_OBJECT_new_reserve(cmp, n) ((STACK_OF(ASN1_OBJECT) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_OBJECT_compfunc_type(cmp), (n)))
+#define sk_ASN1_OBJECT_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_OBJECT_sk_type(sk), (n))
+#define sk_ASN1_OBJECT_free(sk) OPENSSL_sk_free(ossl_check_ASN1_OBJECT_sk_type(sk))
+#define sk_ASN1_OBJECT_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_OBJECT_sk_type(sk))
+#define sk_ASN1_OBJECT_delete(sk, i) ((ASN1_OBJECT *)OPENSSL_sk_delete(ossl_check_ASN1_OBJECT_sk_type(sk), (i)))
+#define sk_ASN1_OBJECT_delete_ptr(sk, ptr) ((ASN1_OBJECT *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_type(ptr)))
+#define sk_ASN1_OBJECT_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_type(ptr))
+#define sk_ASN1_OBJECT_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_type(ptr))
+#define sk_ASN1_OBJECT_pop(sk) ((ASN1_OBJECT *)OPENSSL_sk_pop(ossl_check_ASN1_OBJECT_sk_type(sk)))
+#define sk_ASN1_OBJECT_shift(sk) ((ASN1_OBJECT *)OPENSSL_sk_shift(ossl_check_ASN1_OBJECT_sk_type(sk)))
+#define sk_ASN1_OBJECT_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_OBJECT_sk_type(sk),ossl_check_ASN1_OBJECT_freefunc_type(freefunc))
+#define sk_ASN1_OBJECT_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_type(ptr), (idx))
+#define sk_ASN1_OBJECT_set(sk, idx, ptr) ((ASN1_OBJECT *)OPENSSL_sk_set(ossl_check_ASN1_OBJECT_sk_type(sk), (idx), ossl_check_ASN1_OBJECT_type(ptr)))
+#define sk_ASN1_OBJECT_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_type(ptr))
+#define sk_ASN1_OBJECT_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_type(ptr))
+#define sk_ASN1_OBJECT_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_type(ptr), pnum)
+#define sk_ASN1_OBJECT_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_OBJECT_sk_type(sk))
+#define sk_ASN1_OBJECT_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_OBJECT_sk_type(sk))
+#define sk_ASN1_OBJECT_dup(sk) ((STACK_OF(ASN1_OBJECT) *)OPENSSL_sk_dup(ossl_check_const_ASN1_OBJECT_sk_type(sk)))
+#define sk_ASN1_OBJECT_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_OBJECT) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_copyfunc_type(copyfunc), ossl_check_ASN1_OBJECT_freefunc_type(freefunc)))
+#define sk_ASN1_OBJECT_set_cmp_func(sk, cmp) ((sk_ASN1_OBJECT_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_OBJECT_sk_type(sk), ossl_check_ASN1_OBJECT_compfunc_type(cmp)))
+
+
+DECLARE_ASN1_FUNCTIONS(ASN1_OBJECT)
+
+ASN1_STRING *ASN1_STRING_new(void);
+void ASN1_STRING_free(ASN1_STRING *a);
+void ASN1_STRING_clear_free(ASN1_STRING *a);
+int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str);
+DECLARE_ASN1_DUP_FUNCTION(ASN1_STRING)
+ASN1_STRING *ASN1_STRING_type_new(int type);
+int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b);
+ /*
+ * Since this is used to store all sorts of things, via macros, for now,
+ * make its data void *
+ */
+int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len);
+void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len);
+int ASN1_STRING_length(const ASN1_STRING *x);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void ASN1_STRING_length_set(ASN1_STRING *x, int n);
+# endif
+int ASN1_STRING_type(const ASN1_STRING *x);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 unsigned char *ASN1_STRING_data(ASN1_STRING *x);
+# endif
+const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x);
+
+DECLARE_ASN1_FUNCTIONS(ASN1_BIT_STRING)
+int ASN1_BIT_STRING_set(ASN1_BIT_STRING *a, unsigned char *d, int length);
+int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value);
+int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n);
+int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
+ const unsigned char *flags, int flags_len);
+
+int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs,
+ BIT_STRING_BITNAME *tbl, int indent);
+int ASN1_BIT_STRING_num_asc(const char *name, BIT_STRING_BITNAME *tbl);
+int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, const char *name, int value,
+ BIT_STRING_BITNAME *tbl);
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_INTEGER, ASN1_INTEGER, ASN1_INTEGER)
+#define sk_ASN1_INTEGER_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_INTEGER_sk_type(sk))
+#define sk_ASN1_INTEGER_value(sk, idx) ((ASN1_INTEGER *)OPENSSL_sk_value(ossl_check_const_ASN1_INTEGER_sk_type(sk), (idx)))
+#define sk_ASN1_INTEGER_new(cmp) ((STACK_OF(ASN1_INTEGER) *)OPENSSL_sk_new(ossl_check_ASN1_INTEGER_compfunc_type(cmp)))
+#define sk_ASN1_INTEGER_new_null() ((STACK_OF(ASN1_INTEGER) *)OPENSSL_sk_new_null())
+#define sk_ASN1_INTEGER_new_reserve(cmp, n) ((STACK_OF(ASN1_INTEGER) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_INTEGER_compfunc_type(cmp), (n)))
+#define sk_ASN1_INTEGER_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_INTEGER_sk_type(sk), (n))
+#define sk_ASN1_INTEGER_free(sk) OPENSSL_sk_free(ossl_check_ASN1_INTEGER_sk_type(sk))
+#define sk_ASN1_INTEGER_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_INTEGER_sk_type(sk))
+#define sk_ASN1_INTEGER_delete(sk, i) ((ASN1_INTEGER *)OPENSSL_sk_delete(ossl_check_ASN1_INTEGER_sk_type(sk), (i)))
+#define sk_ASN1_INTEGER_delete_ptr(sk, ptr) ((ASN1_INTEGER *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_type(ptr)))
+#define sk_ASN1_INTEGER_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_type(ptr))
+#define sk_ASN1_INTEGER_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_type(ptr))
+#define sk_ASN1_INTEGER_pop(sk) ((ASN1_INTEGER *)OPENSSL_sk_pop(ossl_check_ASN1_INTEGER_sk_type(sk)))
+#define sk_ASN1_INTEGER_shift(sk) ((ASN1_INTEGER *)OPENSSL_sk_shift(ossl_check_ASN1_INTEGER_sk_type(sk)))
+#define sk_ASN1_INTEGER_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_INTEGER_sk_type(sk),ossl_check_ASN1_INTEGER_freefunc_type(freefunc))
+#define sk_ASN1_INTEGER_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_type(ptr), (idx))
+#define sk_ASN1_INTEGER_set(sk, idx, ptr) ((ASN1_INTEGER *)OPENSSL_sk_set(ossl_check_ASN1_INTEGER_sk_type(sk), (idx), ossl_check_ASN1_INTEGER_type(ptr)))
+#define sk_ASN1_INTEGER_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_type(ptr))
+#define sk_ASN1_INTEGER_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_type(ptr))
+#define sk_ASN1_INTEGER_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_type(ptr), pnum)
+#define sk_ASN1_INTEGER_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_INTEGER_sk_type(sk))
+#define sk_ASN1_INTEGER_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_INTEGER_sk_type(sk))
+#define sk_ASN1_INTEGER_dup(sk) ((STACK_OF(ASN1_INTEGER) *)OPENSSL_sk_dup(ossl_check_const_ASN1_INTEGER_sk_type(sk)))
+#define sk_ASN1_INTEGER_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_INTEGER) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_copyfunc_type(copyfunc), ossl_check_ASN1_INTEGER_freefunc_type(freefunc)))
+#define sk_ASN1_INTEGER_set_cmp_func(sk, cmp) ((sk_ASN1_INTEGER_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_INTEGER_sk_type(sk), ossl_check_ASN1_INTEGER_compfunc_type(cmp)))
+
+
+
+DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER)
+ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
+ long length);
+DECLARE_ASN1_DUP_FUNCTION(ASN1_INTEGER)
+int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y);
+
+DECLARE_ASN1_FUNCTIONS(ASN1_ENUMERATED)
+
+int ASN1_UTCTIME_check(const ASN1_UTCTIME *a);
+ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t);
+ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
+ int offset_day, long offset_sec);
+int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str);
+int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t);
+
+int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *a);
+ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
+ time_t t);
+ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
+ time_t t, int offset_day,
+ long offset_sec);
+int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str);
+
+int ASN1_TIME_diff(int *pday, int *psec,
+ const ASN1_TIME *from, const ASN1_TIME *to);
+
+DECLARE_ASN1_FUNCTIONS(ASN1_OCTET_STRING)
+DECLARE_ASN1_DUP_FUNCTION(ASN1_OCTET_STRING)
+int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a,
+ const ASN1_OCTET_STRING *b);
+int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, const unsigned char *data,
+ int len);
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_UTF8STRING, ASN1_UTF8STRING, ASN1_UTF8STRING)
+#define sk_ASN1_UTF8STRING_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_UTF8STRING_sk_type(sk))
+#define sk_ASN1_UTF8STRING_value(sk, idx) ((ASN1_UTF8STRING *)OPENSSL_sk_value(ossl_check_const_ASN1_UTF8STRING_sk_type(sk), (idx)))
+#define sk_ASN1_UTF8STRING_new(cmp) ((STACK_OF(ASN1_UTF8STRING) *)OPENSSL_sk_new(ossl_check_ASN1_UTF8STRING_compfunc_type(cmp)))
+#define sk_ASN1_UTF8STRING_new_null() ((STACK_OF(ASN1_UTF8STRING) *)OPENSSL_sk_new_null())
+#define sk_ASN1_UTF8STRING_new_reserve(cmp, n) ((STACK_OF(ASN1_UTF8STRING) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_UTF8STRING_compfunc_type(cmp), (n)))
+#define sk_ASN1_UTF8STRING_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_UTF8STRING_sk_type(sk), (n))
+#define sk_ASN1_UTF8STRING_free(sk) OPENSSL_sk_free(ossl_check_ASN1_UTF8STRING_sk_type(sk))
+#define sk_ASN1_UTF8STRING_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_UTF8STRING_sk_type(sk))
+#define sk_ASN1_UTF8STRING_delete(sk, i) ((ASN1_UTF8STRING *)OPENSSL_sk_delete(ossl_check_ASN1_UTF8STRING_sk_type(sk), (i)))
+#define sk_ASN1_UTF8STRING_delete_ptr(sk, ptr) ((ASN1_UTF8STRING *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_type(ptr)))
+#define sk_ASN1_UTF8STRING_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_type(ptr))
+#define sk_ASN1_UTF8STRING_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_type(ptr))
+#define sk_ASN1_UTF8STRING_pop(sk) ((ASN1_UTF8STRING *)OPENSSL_sk_pop(ossl_check_ASN1_UTF8STRING_sk_type(sk)))
+#define sk_ASN1_UTF8STRING_shift(sk) ((ASN1_UTF8STRING *)OPENSSL_sk_shift(ossl_check_ASN1_UTF8STRING_sk_type(sk)))
+#define sk_ASN1_UTF8STRING_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_UTF8STRING_sk_type(sk),ossl_check_ASN1_UTF8STRING_freefunc_type(freefunc))
+#define sk_ASN1_UTF8STRING_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_type(ptr), (idx))
+#define sk_ASN1_UTF8STRING_set(sk, idx, ptr) ((ASN1_UTF8STRING *)OPENSSL_sk_set(ossl_check_ASN1_UTF8STRING_sk_type(sk), (idx), ossl_check_ASN1_UTF8STRING_type(ptr)))
+#define sk_ASN1_UTF8STRING_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_type(ptr))
+#define sk_ASN1_UTF8STRING_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_type(ptr))
+#define sk_ASN1_UTF8STRING_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_type(ptr), pnum)
+#define sk_ASN1_UTF8STRING_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_UTF8STRING_sk_type(sk))
+#define sk_ASN1_UTF8STRING_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_UTF8STRING_sk_type(sk))
+#define sk_ASN1_UTF8STRING_dup(sk) ((STACK_OF(ASN1_UTF8STRING) *)OPENSSL_sk_dup(ossl_check_const_ASN1_UTF8STRING_sk_type(sk)))
+#define sk_ASN1_UTF8STRING_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_UTF8STRING) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_copyfunc_type(copyfunc), ossl_check_ASN1_UTF8STRING_freefunc_type(freefunc)))
+#define sk_ASN1_UTF8STRING_set_cmp_func(sk, cmp) ((sk_ASN1_UTF8STRING_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_UTF8STRING_sk_type(sk), ossl_check_ASN1_UTF8STRING_compfunc_type(cmp)))
+
+
+DECLARE_ASN1_FUNCTIONS(ASN1_VISIBLESTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_UNIVERSALSTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_UTF8STRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_NULL)
+DECLARE_ASN1_FUNCTIONS(ASN1_BMPSTRING)
+
+int UTF8_getc(const unsigned char *str, int len, unsigned long *val);
+int UTF8_putc(unsigned char *str, int len, unsigned long value);
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_GENERALSTRING, ASN1_GENERALSTRING, ASN1_GENERALSTRING)
+#define sk_ASN1_GENERALSTRING_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_GENERALSTRING_sk_type(sk))
+#define sk_ASN1_GENERALSTRING_value(sk, idx) ((ASN1_GENERALSTRING *)OPENSSL_sk_value(ossl_check_const_ASN1_GENERALSTRING_sk_type(sk), (idx)))
+#define sk_ASN1_GENERALSTRING_new(cmp) ((STACK_OF(ASN1_GENERALSTRING) *)OPENSSL_sk_new(ossl_check_ASN1_GENERALSTRING_compfunc_type(cmp)))
+#define sk_ASN1_GENERALSTRING_new_null() ((STACK_OF(ASN1_GENERALSTRING) *)OPENSSL_sk_new_null())
+#define sk_ASN1_GENERALSTRING_new_reserve(cmp, n) ((STACK_OF(ASN1_GENERALSTRING) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_GENERALSTRING_compfunc_type(cmp), (n)))
+#define sk_ASN1_GENERALSTRING_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_GENERALSTRING_sk_type(sk), (n))
+#define sk_ASN1_GENERALSTRING_free(sk) OPENSSL_sk_free(ossl_check_ASN1_GENERALSTRING_sk_type(sk))
+#define sk_ASN1_GENERALSTRING_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_GENERALSTRING_sk_type(sk))
+#define sk_ASN1_GENERALSTRING_delete(sk, i) ((ASN1_GENERALSTRING *)OPENSSL_sk_delete(ossl_check_ASN1_GENERALSTRING_sk_type(sk), (i)))
+#define sk_ASN1_GENERALSTRING_delete_ptr(sk, ptr) ((ASN1_GENERALSTRING *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_type(ptr)))
+#define sk_ASN1_GENERALSTRING_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_type(ptr))
+#define sk_ASN1_GENERALSTRING_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_type(ptr))
+#define sk_ASN1_GENERALSTRING_pop(sk) ((ASN1_GENERALSTRING *)OPENSSL_sk_pop(ossl_check_ASN1_GENERALSTRING_sk_type(sk)))
+#define sk_ASN1_GENERALSTRING_shift(sk) ((ASN1_GENERALSTRING *)OPENSSL_sk_shift(ossl_check_ASN1_GENERALSTRING_sk_type(sk)))
+#define sk_ASN1_GENERALSTRING_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_GENERALSTRING_sk_type(sk),ossl_check_ASN1_GENERALSTRING_freefunc_type(freefunc))
+#define sk_ASN1_GENERALSTRING_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_type(ptr), (idx))
+#define sk_ASN1_GENERALSTRING_set(sk, idx, ptr) ((ASN1_GENERALSTRING *)OPENSSL_sk_set(ossl_check_ASN1_GENERALSTRING_sk_type(sk), (idx), ossl_check_ASN1_GENERALSTRING_type(ptr)))
+#define sk_ASN1_GENERALSTRING_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_type(ptr))
+#define sk_ASN1_GENERALSTRING_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_type(ptr))
+#define sk_ASN1_GENERALSTRING_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_type(ptr), pnum)
+#define sk_ASN1_GENERALSTRING_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_GENERALSTRING_sk_type(sk))
+#define sk_ASN1_GENERALSTRING_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_GENERALSTRING_sk_type(sk))
+#define sk_ASN1_GENERALSTRING_dup(sk) ((STACK_OF(ASN1_GENERALSTRING) *)OPENSSL_sk_dup(ossl_check_const_ASN1_GENERALSTRING_sk_type(sk)))
+#define sk_ASN1_GENERALSTRING_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_GENERALSTRING) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_copyfunc_type(copyfunc), ossl_check_ASN1_GENERALSTRING_freefunc_type(freefunc)))
+#define sk_ASN1_GENERALSTRING_set_cmp_func(sk, cmp) ((sk_ASN1_GENERALSTRING_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_GENERALSTRING_sk_type(sk), ossl_check_ASN1_GENERALSTRING_compfunc_type(cmp)))
+
+
+DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE)
+
+DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING)
+DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT)
+DECLARE_ASN1_FUNCTIONS(ASN1_PRINTABLESTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_T61STRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_IA5STRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_GENERALSTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_UTCTIME)
+DECLARE_ASN1_FUNCTIONS(ASN1_GENERALIZEDTIME)
+DECLARE_ASN1_FUNCTIONS(ASN1_TIME)
+
+DECLARE_ASN1_DUP_FUNCTION(ASN1_TIME)
+DECLARE_ASN1_DUP_FUNCTION(ASN1_UTCTIME)
+DECLARE_ASN1_DUP_FUNCTION(ASN1_GENERALIZEDTIME)
+
+DECLARE_ASN1_ITEM(ASN1_OCTET_STRING_NDEF)
+
+ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t);
+ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
+ int offset_day, long offset_sec);
+int ASN1_TIME_check(const ASN1_TIME *t);
+ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
+ ASN1_GENERALIZEDTIME **out);
+int ASN1_TIME_set_string(ASN1_TIME *s, const char *str);
+int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str);
+int ASN1_TIME_to_tm(const ASN1_TIME *s, struct tm *tm);
+int ASN1_TIME_normalize(ASN1_TIME *s);
+int ASN1_TIME_cmp_time_t(const ASN1_TIME *s, time_t t);
+int ASN1_TIME_compare(const ASN1_TIME *a, const ASN1_TIME *b);
+
+int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a);
+int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size);
+int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a);
+int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size);
+int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a);
+int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size);
+int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type);
+int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a);
+
+int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num);
+ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
+ const char *sn, const char *ln);
+
+int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a);
+int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r);
+int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a);
+int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r);
+
+int ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
+long ASN1_INTEGER_get(const ASN1_INTEGER *a);
+ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai);
+BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn);
+
+int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a);
+int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r);
+
+
+int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v);
+long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a);
+ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai);
+BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn);
+
+/* General */
+/* given a string, return the correct type, max is the maximum length */
+int ASN1_PRINTABLE_type(const unsigned char *s, int max);
+
+unsigned long ASN1_tag2bit(int tag);
+
+/* SPECIALS */
+int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
+ int *pclass, long omax);
+int ASN1_check_infinite_end(unsigned char **p, long len);
+int ASN1_const_check_infinite_end(const unsigned char **p, long len);
+void ASN1_put_object(unsigned char **pp, int constructed, int length,
+ int tag, int xclass);
+int ASN1_put_eoc(unsigned char **pp);
+int ASN1_object_size(int constructed, int length, int tag);
+
+/* Used to implement other functions */
+void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, const void *x);
+
+# define ASN1_dup_of(type,i2d,d2i,x) \
+ ((type*)ASN1_dup(CHECKED_I2D_OF(type, i2d), \
+ CHECKED_D2I_OF(type, d2i), \
+ CHECKED_PTR_OF(const type, x)))
+
+void *ASN1_item_dup(const ASN1_ITEM *it, const void *x);
+int ASN1_item_sign_ex(const ASN1_ITEM *it, X509_ALGOR *algor1,
+ X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
+ const void *data, const ASN1_OCTET_STRING *id,
+ EVP_PKEY *pkey, const EVP_MD *md, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int ASN1_item_verify_ex(const ASN1_ITEM *it, const X509_ALGOR *alg,
+ const ASN1_BIT_STRING *signature, const void *data,
+ const ASN1_OCTET_STRING *id, EVP_PKEY *pkey,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+/* ASN1 alloc/free macros for when a type is only used internally */
+
+# define M_ASN1_new_of(type) (type *)ASN1_item_new(ASN1_ITEM_rptr(type))
+# define M_ASN1_free_of(x, type) \
+ ASN1_item_free(CHECKED_PTR_OF(type, x), ASN1_ITEM_rptr(type))
+
+# ifndef OPENSSL_NO_STDIO
+void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x);
+
+# define ASN1_d2i_fp_of(type,xnew,d2i,in,x) \
+ ((type*)ASN1_d2i_fp(CHECKED_NEW_OF(type, xnew), \
+ CHECKED_D2I_OF(type, d2i), \
+ in, \
+ CHECKED_PPTR_OF(type, x)))
+
+void *ASN1_item_d2i_fp_ex(const ASN1_ITEM *it, FILE *in, void *x,
+ OSSL_LIB_CTX *libctx, const char *propq);
+void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x);
+int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, const void *x);
+
+# define ASN1_i2d_fp_of(type,i2d,out,x) \
+ (ASN1_i2d_fp(CHECKED_I2D_OF(type, i2d), \
+ out, \
+ CHECKED_PTR_OF(const type, x)))
+
+int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, const void *x);
+int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags);
+# endif
+
+int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in);
+
+void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x);
+
+# define ASN1_d2i_bio_of(type,xnew,d2i,in,x) \
+ ((type*)ASN1_d2i_bio( CHECKED_NEW_OF(type, xnew), \
+ CHECKED_D2I_OF(type, d2i), \
+ in, \
+ CHECKED_PPTR_OF(type, x)))
+
+void *ASN1_item_d2i_bio_ex(const ASN1_ITEM *it, BIO *in, void *pval,
+ OSSL_LIB_CTX *libctx, const char *propq);
+void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *pval);
+int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, const void *x);
+
+# define ASN1_i2d_bio_of(type,i2d,out,x) \
+ (ASN1_i2d_bio(CHECKED_I2D_OF(type, i2d), \
+ out, \
+ CHECKED_PTR_OF(const type, x)))
+
+int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, const void *x);
+BIO *ASN1_item_i2d_mem_bio(const ASN1_ITEM *it, const ASN1_VALUE *val);
+int ASN1_UTCTIME_print(BIO *fp, const ASN1_UTCTIME *a);
+int ASN1_GENERALIZEDTIME_print(BIO *fp, const ASN1_GENERALIZEDTIME *a);
+int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm);
+int ASN1_TIME_print_ex(BIO *bp, const ASN1_TIME *tm, unsigned long flags);
+int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v);
+int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags);
+int ASN1_buf_print(BIO *bp, const unsigned char *buf, size_t buflen, int off);
+int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num,
+ unsigned char *buf, int off);
+int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent);
+int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent,
+ int dump);
+const char *ASN1_tag2str(int tag);
+
+/* Used to load and write Netscape format cert */
+
+int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s);
+
+int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len);
+int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_len);
+int ASN1_TYPE_set_int_octetstring(ASN1_TYPE *a, long num,
+ unsigned char *data, int len);
+int ASN1_TYPE_get_int_octetstring(const ASN1_TYPE *a, long *num,
+ unsigned char *data, int max_len);
+
+void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it);
+
+ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it,
+ ASN1_OCTET_STRING **oct);
+
+void ASN1_STRING_set_default_mask(unsigned long mask);
+int ASN1_STRING_set_default_mask_asc(const char *p);
+unsigned long ASN1_STRING_get_default_mask(void);
+int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len,
+ int inform, unsigned long mask);
+int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
+ int inform, unsigned long mask,
+ long minsize, long maxsize);
+
+ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
+ const unsigned char *in, int inlen,
+ int inform, int nid);
+ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid);
+int ASN1_STRING_TABLE_add(int, long, long, unsigned long, unsigned long);
+void ASN1_STRING_TABLE_cleanup(void);
+
+/* ASN1 template functions */
+
+/* Old API compatible functions */
+ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it);
+ASN1_VALUE *ASN1_item_new_ex(const ASN1_ITEM *it, OSSL_LIB_CTX *libctx,
+ const char *propq);
+void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it);
+ASN1_VALUE *ASN1_item_d2i_ex(ASN1_VALUE **val, const unsigned char **in,
+ long len, const ASN1_ITEM *it,
+ OSSL_LIB_CTX *libctx, const char *propq);
+ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **val, const unsigned char **in,
+ long len, const ASN1_ITEM *it);
+int ASN1_item_i2d(const ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it);
+int ASN1_item_ndef_i2d(const ASN1_VALUE *val, unsigned char **out,
+ const ASN1_ITEM *it);
+
+void ASN1_add_oid_module(void);
+void ASN1_add_stable_module(void);
+
+ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf);
+ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf);
+int ASN1_str2mask(const char *str, unsigned long *pmask);
+
+/* ASN1 Print flags */
+
+/* Indicate missing OPTIONAL fields */
+# define ASN1_PCTX_FLAGS_SHOW_ABSENT 0x001
+/* Mark start and end of SEQUENCE */
+# define ASN1_PCTX_FLAGS_SHOW_SEQUENCE 0x002
+/* Mark start and end of SEQUENCE/SET OF */
+# define ASN1_PCTX_FLAGS_SHOW_SSOF 0x004
+/* Show the ASN1 type of primitives */
+# define ASN1_PCTX_FLAGS_SHOW_TYPE 0x008
+/* Don't show ASN1 type of ANY */
+# define ASN1_PCTX_FLAGS_NO_ANY_TYPE 0x010
+/* Don't show ASN1 type of MSTRINGs */
+# define ASN1_PCTX_FLAGS_NO_MSTRING_TYPE 0x020
+/* Don't show field names in SEQUENCE */
+# define ASN1_PCTX_FLAGS_NO_FIELD_NAME 0x040
+/* Show structure names of each SEQUENCE field */
+# define ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME 0x080
+/* Don't show structure name even at top level */
+# define ASN1_PCTX_FLAGS_NO_STRUCT_NAME 0x100
+
+int ASN1_item_print(BIO *out, const ASN1_VALUE *ifld, int indent,
+ const ASN1_ITEM *it, const ASN1_PCTX *pctx);
+ASN1_PCTX *ASN1_PCTX_new(void);
+void ASN1_PCTX_free(ASN1_PCTX *p);
+unsigned long ASN1_PCTX_get_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_nm_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_cert_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_oid_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_str_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags);
+
+ASN1_SCTX *ASN1_SCTX_new(int (*scan_cb) (ASN1_SCTX *ctx));
+void ASN1_SCTX_free(ASN1_SCTX *p);
+const ASN1_ITEM *ASN1_SCTX_get_item(ASN1_SCTX *p);
+const ASN1_TEMPLATE *ASN1_SCTX_get_template(ASN1_SCTX *p);
+unsigned long ASN1_SCTX_get_flags(ASN1_SCTX *p);
+void ASN1_SCTX_set_app_data(ASN1_SCTX *p, void *data);
+void *ASN1_SCTX_get_app_data(ASN1_SCTX *p);
+
+const BIO_METHOD *BIO_f_asn1(void);
+
+/* cannot constify val because of CMS_stream() */
+BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it);
+
+int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
+ const ASN1_ITEM *it);
+int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
+ const char *hdr, const ASN1_ITEM *it);
+/* cannot constify val because of CMS_dataFinal() */
+int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
+ int ctype_nid, int econt_nid,
+ STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it);
+int SMIME_write_ASN1_ex(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
+ int ctype_nid, int econt_nid,
+ STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it,
+ OSSL_LIB_CTX *libctx, const char *propq);
+ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it);
+ASN1_VALUE *SMIME_read_ASN1_ex(BIO *bio, int flags, BIO **bcont,
+ const ASN1_ITEM *it, ASN1_VALUE **x,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int SMIME_crlf_copy(BIO *in, BIO *out, int flags);
+int SMIME_text(BIO *in, BIO *out);
+
+const ASN1_ITEM *ASN1_ITEM_lookup(const char *name);
+const ASN1_ITEM *ASN1_ITEM_get(size_t i);
+
+/* Legacy compatibility */
+# define DECLARE_ASN1_FUNCTIONS_fname(type, itname, name) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name)
+# define DECLARE_ASN1_FUNCTIONS_const(type) DECLARE_ASN1_FUNCTIONS(type)
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_const(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS(type, name)
+# define I2D_OF_const(type) I2D_OF(type)
+# define ASN1_dup_of_const(type,i2d,d2i,x) ASN1_dup_of(type,i2d,d2i,x)
+# define ASN1_i2d_fp_of_const(type,i2d,out,x) ASN1_i2d_fp_of(type,i2d,out,x)
+# define ASN1_i2d_bio_of_const(type,i2d,out,x) ASN1_i2d_bio_of(type,i2d,out,x)
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/asn1.h.in b/include/openssl/asn1.h.in
new file mode 100644
index 00000000..6d5094a3
--- /dev/null
+++ b/include/openssl/asn1.h.in
@@ -0,0 +1,961 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_ASN1_H
+# define OPENSSL_ASN1_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ASN1_H
+# endif
+
+# include <time.h>
+# include <openssl/e_os2.h>
+# include <openssl/opensslconf.h>
+# include <openssl/bio.h>
+# include <openssl/safestack.h>
+# include <openssl/asn1err.h>
+# include <openssl/symhacks.h>
+
+# include <openssl/types.h>
+# include <openssl/bn.h>
+
+# ifdef OPENSSL_BUILD_SHLIBCRYPTO
+# undef OPENSSL_EXTERN
+# define OPENSSL_EXTERN OPENSSL_EXPORT
+# endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define V_ASN1_UNIVERSAL 0x00
+# define V_ASN1_APPLICATION 0x40
+# define V_ASN1_CONTEXT_SPECIFIC 0x80
+# define V_ASN1_PRIVATE 0xc0
+
+# define V_ASN1_CONSTRUCTED 0x20
+# define V_ASN1_PRIMITIVE_TAG 0x1f
+# define V_ASN1_PRIMATIVE_TAG /*compat*/ V_ASN1_PRIMITIVE_TAG
+
+# define V_ASN1_APP_CHOOSE -2/* let the recipient choose */
+# define V_ASN1_OTHER -3/* used in ASN1_TYPE */
+# define V_ASN1_ANY -4/* used in ASN1 template code */
+
+# define V_ASN1_UNDEF -1
+/* ASN.1 tag values */
+# define V_ASN1_EOC 0
+# define V_ASN1_BOOLEAN 1 /**/
+# define V_ASN1_INTEGER 2
+# define V_ASN1_BIT_STRING 3
+# define V_ASN1_OCTET_STRING 4
+# define V_ASN1_NULL 5
+# define V_ASN1_OBJECT 6
+# define V_ASN1_OBJECT_DESCRIPTOR 7
+# define V_ASN1_EXTERNAL 8
+# define V_ASN1_REAL 9
+# define V_ASN1_ENUMERATED 10
+# define V_ASN1_UTF8STRING 12
+# define V_ASN1_SEQUENCE 16
+# define V_ASN1_SET 17
+# define V_ASN1_NUMERICSTRING 18 /**/
+# define V_ASN1_PRINTABLESTRING 19
+# define V_ASN1_T61STRING 20
+# define V_ASN1_TELETEXSTRING 20/* alias */
+# define V_ASN1_VIDEOTEXSTRING 21 /**/
+# define V_ASN1_IA5STRING 22
+# define V_ASN1_UTCTIME 23
+# define V_ASN1_GENERALIZEDTIME 24 /**/
+# define V_ASN1_GRAPHICSTRING 25 /**/
+# define V_ASN1_ISO64STRING 26 /**/
+# define V_ASN1_VISIBLESTRING 26/* alias */
+# define V_ASN1_GENERALSTRING 27 /**/
+# define V_ASN1_UNIVERSALSTRING 28 /**/
+# define V_ASN1_BMPSTRING 30
+
+/*
+ * NB the constants below are used internally by ASN1_INTEGER
+ * and ASN1_ENUMERATED to indicate the sign. They are *not* on
+ * the wire tag values.
+ */
+
+# define V_ASN1_NEG 0x100
+# define V_ASN1_NEG_INTEGER (2 | V_ASN1_NEG)
+# define V_ASN1_NEG_ENUMERATED (10 | V_ASN1_NEG)
+
+/* For use with d2i_ASN1_type_bytes() */
+# define B_ASN1_NUMERICSTRING 0x0001
+# define B_ASN1_PRINTABLESTRING 0x0002
+# define B_ASN1_T61STRING 0x0004
+# define B_ASN1_TELETEXSTRING 0x0004
+# define B_ASN1_VIDEOTEXSTRING 0x0008
+# define B_ASN1_IA5STRING 0x0010
+# define B_ASN1_GRAPHICSTRING 0x0020
+# define B_ASN1_ISO64STRING 0x0040
+# define B_ASN1_VISIBLESTRING 0x0040
+# define B_ASN1_GENERALSTRING 0x0080
+# define B_ASN1_UNIVERSALSTRING 0x0100
+# define B_ASN1_OCTET_STRING 0x0200
+# define B_ASN1_BIT_STRING 0x0400
+# define B_ASN1_BMPSTRING 0x0800
+# define B_ASN1_UNKNOWN 0x1000
+# define B_ASN1_UTF8STRING 0x2000
+# define B_ASN1_UTCTIME 0x4000
+# define B_ASN1_GENERALIZEDTIME 0x8000
+# define B_ASN1_SEQUENCE 0x10000
+/* For use with ASN1_mbstring_copy() */
+# define MBSTRING_FLAG 0x1000
+# define MBSTRING_UTF8 (MBSTRING_FLAG)
+# define MBSTRING_ASC (MBSTRING_FLAG|1)
+# define MBSTRING_BMP (MBSTRING_FLAG|2)
+# define MBSTRING_UNIV (MBSTRING_FLAG|4)
+# define SMIME_OLDMIME 0x400
+# define SMIME_CRLFEOL 0x800
+# define SMIME_STREAM 0x1000
+
+/* Stacks for types not otherwise defined in this header */
+{-
+ generate_stack_macros("X509_ALGOR");
+-}
+
+
+# define ASN1_STRING_FLAG_BITS_LEFT 0x08/* Set if 0x07 has bits left value */
+/*
+ * This indicates that the ASN1_STRING is not a real value but just a place
+ * holder for the location where indefinite length constructed data should be
+ * inserted in the memory buffer
+ */
+# define ASN1_STRING_FLAG_NDEF 0x010
+
+/*
+ * This flag is used by the CMS code to indicate that a string is not
+ * complete and is a place holder for content when it had all been accessed.
+ * The flag will be reset when content has been written to it.
+ */
+
+# define ASN1_STRING_FLAG_CONT 0x020
+/*
+ * This flag is used by ASN1 code to indicate an ASN1_STRING is an MSTRING
+ * type.
+ */
+# define ASN1_STRING_FLAG_MSTRING 0x040
+/* String is embedded and only content should be freed */
+# define ASN1_STRING_FLAG_EMBED 0x080
+/* String should be parsed in RFC 5280's time format */
+# define ASN1_STRING_FLAG_X509_TIME 0x100
+/* This is the base type that holds just about everything :-) */
+struct asn1_string_st {
+ int length;
+ int type;
+ unsigned char *data;
+ /*
+ * The value of the following field depends on the type being held. It
+ * is mostly being used for BIT_STRING so if the input data has a
+ * non-zero 'unused bits' value, it will be handled correctly
+ */
+ long flags;
+};
+
+/*
+ * ASN1_ENCODING structure: this is used to save the received encoding of an
+ * ASN1 type. This is useful to get round problems with invalid encodings
+ * which can break signatures.
+ */
+
+typedef struct ASN1_ENCODING_st {
+ unsigned char *enc; /* DER encoding */
+ long len; /* Length of encoding */
+ int modified; /* set to 1 if 'enc' is invalid */
+} ASN1_ENCODING;
+
+/* Used with ASN1 LONG type: if a long is set to this it is omitted */
+# define ASN1_LONG_UNDEF 0x7fffffffL
+
+# define STABLE_FLAGS_MALLOC 0x01
+/*
+ * A zero passed to ASN1_STRING_TABLE_new_add for the flags is interpreted
+ * as "don't change" and STABLE_FLAGS_MALLOC is always set. By setting
+ * STABLE_FLAGS_MALLOC only we can clear the existing value. Use the alias
+ * STABLE_FLAGS_CLEAR to reflect this.
+ */
+# define STABLE_FLAGS_CLEAR STABLE_FLAGS_MALLOC
+# define STABLE_NO_MASK 0x02
+# define DIRSTRING_TYPE \
+ (B_ASN1_PRINTABLESTRING|B_ASN1_T61STRING|B_ASN1_BMPSTRING|B_ASN1_UTF8STRING)
+# define PKCS9STRING_TYPE (DIRSTRING_TYPE|B_ASN1_IA5STRING)
+
+struct asn1_string_table_st {
+ int nid;
+ long minsize;
+ long maxsize;
+ unsigned long mask;
+ unsigned long flags;
+};
+
+{-
+ generate_stack_macros("ASN1_STRING_TABLE");
+-}
+
+/* size limits: this stuff is taken straight from RFC2459 */
+
+# define ub_name 32768
+# define ub_common_name 64
+# define ub_locality_name 128
+# define ub_state_name 128
+# define ub_organization_name 64
+# define ub_organization_unit_name 64
+# define ub_title 64
+# define ub_email_address 128
+
+/*
+ * Declarations for template structures: for full definitions see asn1t.h
+ */
+typedef struct ASN1_TEMPLATE_st ASN1_TEMPLATE;
+typedef struct ASN1_TLC_st ASN1_TLC;
+/* This is just an opaque pointer */
+typedef struct ASN1_VALUE_st ASN1_VALUE;
+
+/* Declare ASN1 functions: the implement macro in in asn1t.h */
+
+/*
+ * The mysterious 'extern' that's passed to some macros is innocuous,
+ * and is there to quiet pre-C99 compilers that may complain about empty
+ * arguments in macro calls.
+ */
+
+# define DECLARE_ASN1_FUNCTIONS_attr(attr, type) \
+ DECLARE_ASN1_FUNCTIONS_name_attr(attr, type, type)
+# define DECLARE_ASN1_FUNCTIONS(type) \
+ DECLARE_ASN1_FUNCTIONS_attr(extern, type)
+
+# define DECLARE_ASN1_ALLOC_FUNCTIONS_attr(attr, type) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(attr, type, type)
+# define DECLARE_ASN1_ALLOC_FUNCTIONS(type) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_attr(extern, type)
+
+# define DECLARE_ASN1_FUNCTIONS_name_attr(attr, type, name) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(attr, type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(attr, type, name)
+# define DECLARE_ASN1_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_FUNCTIONS_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_attr(attr, type, itname, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(attr, type, name) \
+ DECLARE_ASN1_ITEM_attr(attr, itname)
+# define DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_attr(extern, type, itname, name)
+
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(attr, type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_attr(attr, type, name, name)
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(attr, type, name) \
+ attr type *d2i_##name(type **a, const unsigned char **in, long len); \
+ attr int i2d_##name(const type *a, unsigned char **out);
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_only(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(extern, type, name)
+
+# define DECLARE_ASN1_NDEF_FUNCTION_attr(attr, name) \
+ attr int i2d_##name##_NDEF(const name *a, unsigned char **out);
+# define DECLARE_ASN1_NDEF_FUNCTION(name) \
+ DECLARE_ASN1_NDEF_FUNCTION_attr(extern, name)
+
+# define DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(attr, type, name) \
+ attr type *name##_new(void); \
+ attr void name##_free(type *a);
+# define DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_DUP_FUNCTION_attr(attr, type) \
+ DECLARE_ASN1_DUP_FUNCTION_name_attr(attr, type, type)
+# define DECLARE_ASN1_DUP_FUNCTION(type) \
+ DECLARE_ASN1_DUP_FUNCTION_attr(extern, type)
+
+# define DECLARE_ASN1_DUP_FUNCTION_name_attr(attr, type, name) \
+ attr type *name##_dup(const type *a);
+# define DECLARE_ASN1_DUP_FUNCTION_name(type, name) \
+ DECLARE_ASN1_DUP_FUNCTION_name_attr(extern, type, name)
+
+# define DECLARE_ASN1_PRINT_FUNCTION_attr(attr, stname) \
+ DECLARE_ASN1_PRINT_FUNCTION_fname_attr(attr, stname, stname)
+# define DECLARE_ASN1_PRINT_FUNCTION(stname) \
+ DECLARE_ASN1_PRINT_FUNCTION_attr(extern, stname)
+
+# define DECLARE_ASN1_PRINT_FUNCTION_fname_attr(attr, stname, fname) \
+ attr int fname##_print_ctx(BIO *out, const stname *x, int indent, \
+ const ASN1_PCTX *pctx);
+# define DECLARE_ASN1_PRINT_FUNCTION_fname(stname, fname) \
+ DECLARE_ASN1_PRINT_FUNCTION_fname_attr(extern, stname, fname)
+
+# define D2I_OF(type) type *(*)(type **,const unsigned char **,long)
+# define I2D_OF(type) int (*)(const type *,unsigned char **)
+
+# define CHECKED_D2I_OF(type, d2i) \
+ ((d2i_of_void*) (1 ? d2i : ((D2I_OF(type))0)))
+# define CHECKED_I2D_OF(type, i2d) \
+ ((i2d_of_void*) (1 ? i2d : ((I2D_OF(type))0)))
+# define CHECKED_NEW_OF(type, xnew) \
+ ((void *(*)(void)) (1 ? xnew : ((type *(*)(void))0)))
+# define CHECKED_PTR_OF(type, p) \
+ ((void*) (1 ? p : (type*)0))
+# define CHECKED_PPTR_OF(type, p) \
+ ((void**) (1 ? p : (type**)0))
+
+# define TYPEDEF_D2I_OF(type) typedef type *d2i_of_##type(type **,const unsigned char **,long)
+# define TYPEDEF_I2D_OF(type) typedef int i2d_of_##type(const type *,unsigned char **)
+# define TYPEDEF_D2I2D_OF(type) TYPEDEF_D2I_OF(type); TYPEDEF_I2D_OF(type)
+
+typedef void *d2i_of_void(void **, const unsigned char **, long);
+typedef int i2d_of_void(const void *, unsigned char **);
+
+/*-
+ * The following macros and typedefs allow an ASN1_ITEM
+ * to be embedded in a structure and referenced. Since
+ * the ASN1_ITEM pointers need to be globally accessible
+ * (possibly from shared libraries) they may exist in
+ * different forms. On platforms that support it the
+ * ASN1_ITEM structure itself will be globally exported.
+ * Other platforms will export a function that returns
+ * an ASN1_ITEM pointer.
+ *
+ * To handle both cases transparently the macros below
+ * should be used instead of hard coding an ASN1_ITEM
+ * pointer in a structure.
+ *
+ * The structure will look like this:
+ *
+ * typedef struct SOMETHING_st {
+ * ...
+ * ASN1_ITEM_EXP *iptr;
+ * ...
+ * } SOMETHING;
+ *
+ * It would be initialised as e.g.:
+ *
+ * SOMETHING somevar = {...,ASN1_ITEM_ref(X509),...};
+ *
+ * and the actual pointer extracted with:
+ *
+ * const ASN1_ITEM *it = ASN1_ITEM_ptr(somevar.iptr);
+ *
+ * Finally an ASN1_ITEM pointer can be extracted from an
+ * appropriate reference with: ASN1_ITEM_rptr(X509). This
+ * would be used when a function takes an ASN1_ITEM * argument.
+ *
+ */
+
+
+/*
+ * Platforms that can't easily handle shared global variables are declared as
+ * functions returning ASN1_ITEM pointers.
+ */
+
+/* ASN1_ITEM pointer exported type */
+typedef const ASN1_ITEM *ASN1_ITEM_EXP (void);
+
+/* Macro to obtain ASN1_ITEM pointer from exported type */
+# define ASN1_ITEM_ptr(iptr) (iptr())
+
+/* Macro to include ASN1_ITEM pointer from base type */
+# define ASN1_ITEM_ref(iptr) (iptr##_it)
+
+# define ASN1_ITEM_rptr(ref) (ref##_it())
+
+# define DECLARE_ASN1_ITEM_attr(attr, name) \
+ attr const ASN1_ITEM * name##_it(void);
+# define DECLARE_ASN1_ITEM(name) \
+ DECLARE_ASN1_ITEM_attr(extern, name)
+
+/* Parameters used by ASN1_STRING_print_ex() */
+
+/*
+ * These determine which characters to escape: RFC2253 special characters,
+ * control characters and MSB set characters
+ */
+
+# define ASN1_STRFLGS_ESC_2253 1
+# define ASN1_STRFLGS_ESC_CTRL 2
+# define ASN1_STRFLGS_ESC_MSB 4
+
+/* Lower 8 bits are reserved as an output type specifier */
+# define ASN1_DTFLGS_TYPE_MASK 0x0FUL
+# define ASN1_DTFLGS_RFC822 0x00UL
+# define ASN1_DTFLGS_ISO8601 0x01UL
+
+/*
+ * This flag determines how we do escaping: normally RC2253 backslash only,
+ * set this to use backslash and quote.
+ */
+
+# define ASN1_STRFLGS_ESC_QUOTE 8
+
+/* These three flags are internal use only. */
+
+/* Character is a valid PrintableString character */
+# define CHARTYPE_PRINTABLESTRING 0x10
+/* Character needs escaping if it is the first character */
+# define CHARTYPE_FIRST_ESC_2253 0x20
+/* Character needs escaping if it is the last character */
+# define CHARTYPE_LAST_ESC_2253 0x40
+
+/*
+ * NB the internal flags are safely reused below by flags handled at the top
+ * level.
+ */
+
+/*
+ * If this is set we convert all character strings to UTF8 first
+ */
+
+# define ASN1_STRFLGS_UTF8_CONVERT 0x10
+
+/*
+ * If this is set we don't attempt to interpret content: just assume all
+ * strings are 1 byte per character. This will produce some pretty odd
+ * looking output!
+ */
+
+# define ASN1_STRFLGS_IGNORE_TYPE 0x20
+
+/* If this is set we include the string type in the output */
+# define ASN1_STRFLGS_SHOW_TYPE 0x40
+
+/*
+ * This determines which strings to display and which to 'dump' (hex dump of
+ * content octets or DER encoding). We can only dump non character strings or
+ * everything. If we don't dump 'unknown' they are interpreted as character
+ * strings with 1 octet per character and are subject to the usual escaping
+ * options.
+ */
+
+# define ASN1_STRFLGS_DUMP_ALL 0x80
+# define ASN1_STRFLGS_DUMP_UNKNOWN 0x100
+
+/*
+ * These determine what 'dumping' does, we can dump the content octets or the
+ * DER encoding: both use the RFC2253 #XXXXX notation.
+ */
+
+# define ASN1_STRFLGS_DUMP_DER 0x200
+
+/*
+ * This flag specifies that RC2254 escaping shall be performed.
+ */
+#define ASN1_STRFLGS_ESC_2254 0x400
+
+/*
+ * All the string flags consistent with RFC2253, escaping control characters
+ * isn't essential in RFC2253 but it is advisable anyway.
+ */
+
+# define ASN1_STRFLGS_RFC2253 (ASN1_STRFLGS_ESC_2253 | \
+ ASN1_STRFLGS_ESC_CTRL | \
+ ASN1_STRFLGS_ESC_MSB | \
+ ASN1_STRFLGS_UTF8_CONVERT | \
+ ASN1_STRFLGS_DUMP_UNKNOWN | \
+ ASN1_STRFLGS_DUMP_DER)
+
+
+struct asn1_type_st {
+ int type;
+ union {
+ char *ptr;
+ ASN1_BOOLEAN boolean;
+ ASN1_STRING *asn1_string;
+ ASN1_OBJECT *object;
+ ASN1_INTEGER *integer;
+ ASN1_ENUMERATED *enumerated;
+ ASN1_BIT_STRING *bit_string;
+ ASN1_OCTET_STRING *octet_string;
+ ASN1_PRINTABLESTRING *printablestring;
+ ASN1_T61STRING *t61string;
+ ASN1_IA5STRING *ia5string;
+ ASN1_GENERALSTRING *generalstring;
+ ASN1_BMPSTRING *bmpstring;
+ ASN1_UNIVERSALSTRING *universalstring;
+ ASN1_UTCTIME *utctime;
+ ASN1_GENERALIZEDTIME *generalizedtime;
+ ASN1_VISIBLESTRING *visiblestring;
+ ASN1_UTF8STRING *utf8string;
+ /*
+ * set and sequence are left complete and still contain the set or
+ * sequence bytes
+ */
+ ASN1_STRING *set;
+ ASN1_STRING *sequence;
+ ASN1_VALUE *asn1_value;
+ } value;
+};
+
+{-
+ generate_stack_macros("ASN1_TYPE");
+-}
+
+typedef STACK_OF(ASN1_TYPE) ASN1_SEQUENCE_ANY;
+
+DECLARE_ASN1_ENCODE_FUNCTIONS_name(ASN1_SEQUENCE_ANY, ASN1_SEQUENCE_ANY)
+DECLARE_ASN1_ENCODE_FUNCTIONS_name(ASN1_SEQUENCE_ANY, ASN1_SET_ANY)
+
+/* This is used to contain a list of bit names */
+typedef struct BIT_STRING_BITNAME_st {
+ int bitnum;
+ const char *lname;
+ const char *sname;
+} BIT_STRING_BITNAME;
+
+# define B_ASN1_TIME \
+ B_ASN1_UTCTIME | \
+ B_ASN1_GENERALIZEDTIME
+
+# define B_ASN1_PRINTABLE \
+ B_ASN1_NUMERICSTRING| \
+ B_ASN1_PRINTABLESTRING| \
+ B_ASN1_T61STRING| \
+ B_ASN1_IA5STRING| \
+ B_ASN1_BIT_STRING| \
+ B_ASN1_UNIVERSALSTRING|\
+ B_ASN1_BMPSTRING|\
+ B_ASN1_UTF8STRING|\
+ B_ASN1_SEQUENCE|\
+ B_ASN1_UNKNOWN
+
+# define B_ASN1_DIRECTORYSTRING \
+ B_ASN1_PRINTABLESTRING| \
+ B_ASN1_TELETEXSTRING|\
+ B_ASN1_BMPSTRING|\
+ B_ASN1_UNIVERSALSTRING|\
+ B_ASN1_UTF8STRING
+
+# define B_ASN1_DISPLAYTEXT \
+ B_ASN1_IA5STRING| \
+ B_ASN1_VISIBLESTRING| \
+ B_ASN1_BMPSTRING|\
+ B_ASN1_UTF8STRING
+
+DECLARE_ASN1_ALLOC_FUNCTIONS_name(ASN1_TYPE, ASN1_TYPE)
+DECLARE_ASN1_ENCODE_FUNCTIONS(ASN1_TYPE, ASN1_ANY, ASN1_TYPE)
+
+int ASN1_TYPE_get(const ASN1_TYPE *a);
+void ASN1_TYPE_set(ASN1_TYPE *a, int type, void *value);
+int ASN1_TYPE_set1(ASN1_TYPE *a, int type, const void *value);
+int ASN1_TYPE_cmp(const ASN1_TYPE *a, const ASN1_TYPE *b);
+
+ASN1_TYPE *ASN1_TYPE_pack_sequence(const ASN1_ITEM *it, void *s, ASN1_TYPE **t);
+void *ASN1_TYPE_unpack_sequence(const ASN1_ITEM *it, const ASN1_TYPE *t);
+
+{-
+ generate_stack_macros("ASN1_OBJECT");
+-}
+
+DECLARE_ASN1_FUNCTIONS(ASN1_OBJECT)
+
+ASN1_STRING *ASN1_STRING_new(void);
+void ASN1_STRING_free(ASN1_STRING *a);
+void ASN1_STRING_clear_free(ASN1_STRING *a);
+int ASN1_STRING_copy(ASN1_STRING *dst, const ASN1_STRING *str);
+DECLARE_ASN1_DUP_FUNCTION(ASN1_STRING)
+ASN1_STRING *ASN1_STRING_type_new(int type);
+int ASN1_STRING_cmp(const ASN1_STRING *a, const ASN1_STRING *b);
+ /*
+ * Since this is used to store all sorts of things, via macros, for now,
+ * make its data void *
+ */
+int ASN1_STRING_set(ASN1_STRING *str, const void *data, int len);
+void ASN1_STRING_set0(ASN1_STRING *str, void *data, int len);
+int ASN1_STRING_length(const ASN1_STRING *x);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void ASN1_STRING_length_set(ASN1_STRING *x, int n);
+# endif
+int ASN1_STRING_type(const ASN1_STRING *x);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 unsigned char *ASN1_STRING_data(ASN1_STRING *x);
+# endif
+const unsigned char *ASN1_STRING_get0_data(const ASN1_STRING *x);
+
+DECLARE_ASN1_FUNCTIONS(ASN1_BIT_STRING)
+int ASN1_BIT_STRING_set(ASN1_BIT_STRING *a, unsigned char *d, int length);
+int ASN1_BIT_STRING_set_bit(ASN1_BIT_STRING *a, int n, int value);
+int ASN1_BIT_STRING_get_bit(const ASN1_BIT_STRING *a, int n);
+int ASN1_BIT_STRING_check(const ASN1_BIT_STRING *a,
+ const unsigned char *flags, int flags_len);
+
+int ASN1_BIT_STRING_name_print(BIO *out, ASN1_BIT_STRING *bs,
+ BIT_STRING_BITNAME *tbl, int indent);
+int ASN1_BIT_STRING_num_asc(const char *name, BIT_STRING_BITNAME *tbl);
+int ASN1_BIT_STRING_set_asc(ASN1_BIT_STRING *bs, const char *name, int value,
+ BIT_STRING_BITNAME *tbl);
+
+{-
+ generate_stack_macros("ASN1_INTEGER");
+-}
+
+
+DECLARE_ASN1_FUNCTIONS(ASN1_INTEGER)
+ASN1_INTEGER *d2i_ASN1_UINTEGER(ASN1_INTEGER **a, const unsigned char **pp,
+ long length);
+DECLARE_ASN1_DUP_FUNCTION(ASN1_INTEGER)
+int ASN1_INTEGER_cmp(const ASN1_INTEGER *x, const ASN1_INTEGER *y);
+
+DECLARE_ASN1_FUNCTIONS(ASN1_ENUMERATED)
+
+int ASN1_UTCTIME_check(const ASN1_UTCTIME *a);
+ASN1_UTCTIME *ASN1_UTCTIME_set(ASN1_UTCTIME *s, time_t t);
+ASN1_UTCTIME *ASN1_UTCTIME_adj(ASN1_UTCTIME *s, time_t t,
+ int offset_day, long offset_sec);
+int ASN1_UTCTIME_set_string(ASN1_UTCTIME *s, const char *str);
+int ASN1_UTCTIME_cmp_time_t(const ASN1_UTCTIME *s, time_t t);
+
+int ASN1_GENERALIZEDTIME_check(const ASN1_GENERALIZEDTIME *a);
+ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_set(ASN1_GENERALIZEDTIME *s,
+ time_t t);
+ASN1_GENERALIZEDTIME *ASN1_GENERALIZEDTIME_adj(ASN1_GENERALIZEDTIME *s,
+ time_t t, int offset_day,
+ long offset_sec);
+int ASN1_GENERALIZEDTIME_set_string(ASN1_GENERALIZEDTIME *s, const char *str);
+
+int ASN1_TIME_diff(int *pday, int *psec,
+ const ASN1_TIME *from, const ASN1_TIME *to);
+
+DECLARE_ASN1_FUNCTIONS(ASN1_OCTET_STRING)
+DECLARE_ASN1_DUP_FUNCTION(ASN1_OCTET_STRING)
+int ASN1_OCTET_STRING_cmp(const ASN1_OCTET_STRING *a,
+ const ASN1_OCTET_STRING *b);
+int ASN1_OCTET_STRING_set(ASN1_OCTET_STRING *str, const unsigned char *data,
+ int len);
+
+{-
+ generate_stack_macros("ASN1_UTF8STRING");
+-}
+
+DECLARE_ASN1_FUNCTIONS(ASN1_VISIBLESTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_UNIVERSALSTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_UTF8STRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_NULL)
+DECLARE_ASN1_FUNCTIONS(ASN1_BMPSTRING)
+
+int UTF8_getc(const unsigned char *str, int len, unsigned long *val);
+int UTF8_putc(unsigned char *str, int len, unsigned long value);
+
+{-
+ generate_stack_macros("ASN1_GENERALSTRING");
+-}
+
+DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, ASN1_PRINTABLE)
+
+DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DIRECTORYSTRING)
+DECLARE_ASN1_FUNCTIONS_name(ASN1_STRING, DISPLAYTEXT)
+DECLARE_ASN1_FUNCTIONS(ASN1_PRINTABLESTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_T61STRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_IA5STRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_GENERALSTRING)
+DECLARE_ASN1_FUNCTIONS(ASN1_UTCTIME)
+DECLARE_ASN1_FUNCTIONS(ASN1_GENERALIZEDTIME)
+DECLARE_ASN1_FUNCTIONS(ASN1_TIME)
+
+DECLARE_ASN1_DUP_FUNCTION(ASN1_TIME)
+DECLARE_ASN1_DUP_FUNCTION(ASN1_UTCTIME)
+DECLARE_ASN1_DUP_FUNCTION(ASN1_GENERALIZEDTIME)
+
+DECLARE_ASN1_ITEM(ASN1_OCTET_STRING_NDEF)
+
+ASN1_TIME *ASN1_TIME_set(ASN1_TIME *s, time_t t);
+ASN1_TIME *ASN1_TIME_adj(ASN1_TIME *s, time_t t,
+ int offset_day, long offset_sec);
+int ASN1_TIME_check(const ASN1_TIME *t);
+ASN1_GENERALIZEDTIME *ASN1_TIME_to_generalizedtime(const ASN1_TIME *t,
+ ASN1_GENERALIZEDTIME **out);
+int ASN1_TIME_set_string(ASN1_TIME *s, const char *str);
+int ASN1_TIME_set_string_X509(ASN1_TIME *s, const char *str);
+int ASN1_TIME_to_tm(const ASN1_TIME *s, struct tm *tm);
+int ASN1_TIME_normalize(ASN1_TIME *s);
+int ASN1_TIME_cmp_time_t(const ASN1_TIME *s, time_t t);
+int ASN1_TIME_compare(const ASN1_TIME *a, const ASN1_TIME *b);
+
+int i2a_ASN1_INTEGER(BIO *bp, const ASN1_INTEGER *a);
+int a2i_ASN1_INTEGER(BIO *bp, ASN1_INTEGER *bs, char *buf, int size);
+int i2a_ASN1_ENUMERATED(BIO *bp, const ASN1_ENUMERATED *a);
+int a2i_ASN1_ENUMERATED(BIO *bp, ASN1_ENUMERATED *bs, char *buf, int size);
+int i2a_ASN1_OBJECT(BIO *bp, const ASN1_OBJECT *a);
+int a2i_ASN1_STRING(BIO *bp, ASN1_STRING *bs, char *buf, int size);
+int i2a_ASN1_STRING(BIO *bp, const ASN1_STRING *a, int type);
+int i2t_ASN1_OBJECT(char *buf, int buf_len, const ASN1_OBJECT *a);
+
+int a2d_ASN1_OBJECT(unsigned char *out, int olen, const char *buf, int num);
+ASN1_OBJECT *ASN1_OBJECT_create(int nid, unsigned char *data, int len,
+ const char *sn, const char *ln);
+
+int ASN1_INTEGER_get_int64(int64_t *pr, const ASN1_INTEGER *a);
+int ASN1_INTEGER_set_int64(ASN1_INTEGER *a, int64_t r);
+int ASN1_INTEGER_get_uint64(uint64_t *pr, const ASN1_INTEGER *a);
+int ASN1_INTEGER_set_uint64(ASN1_INTEGER *a, uint64_t r);
+
+int ASN1_INTEGER_set(ASN1_INTEGER *a, long v);
+long ASN1_INTEGER_get(const ASN1_INTEGER *a);
+ASN1_INTEGER *BN_to_ASN1_INTEGER(const BIGNUM *bn, ASN1_INTEGER *ai);
+BIGNUM *ASN1_INTEGER_to_BN(const ASN1_INTEGER *ai, BIGNUM *bn);
+
+int ASN1_ENUMERATED_get_int64(int64_t *pr, const ASN1_ENUMERATED *a);
+int ASN1_ENUMERATED_set_int64(ASN1_ENUMERATED *a, int64_t r);
+
+
+int ASN1_ENUMERATED_set(ASN1_ENUMERATED *a, long v);
+long ASN1_ENUMERATED_get(const ASN1_ENUMERATED *a);
+ASN1_ENUMERATED *BN_to_ASN1_ENUMERATED(const BIGNUM *bn, ASN1_ENUMERATED *ai);
+BIGNUM *ASN1_ENUMERATED_to_BN(const ASN1_ENUMERATED *ai, BIGNUM *bn);
+
+/* General */
+/* given a string, return the correct type, max is the maximum length */
+int ASN1_PRINTABLE_type(const unsigned char *s, int max);
+
+unsigned long ASN1_tag2bit(int tag);
+
+/* SPECIALS */
+int ASN1_get_object(const unsigned char **pp, long *plength, int *ptag,
+ int *pclass, long omax);
+int ASN1_check_infinite_end(unsigned char **p, long len);
+int ASN1_const_check_infinite_end(const unsigned char **p, long len);
+void ASN1_put_object(unsigned char **pp, int constructed, int length,
+ int tag, int xclass);
+int ASN1_put_eoc(unsigned char **pp);
+int ASN1_object_size(int constructed, int length, int tag);
+
+/* Used to implement other functions */
+void *ASN1_dup(i2d_of_void *i2d, d2i_of_void *d2i, const void *x);
+
+# define ASN1_dup_of(type,i2d,d2i,x) \
+ ((type*)ASN1_dup(CHECKED_I2D_OF(type, i2d), \
+ CHECKED_D2I_OF(type, d2i), \
+ CHECKED_PTR_OF(const type, x)))
+
+void *ASN1_item_dup(const ASN1_ITEM *it, const void *x);
+int ASN1_item_sign_ex(const ASN1_ITEM *it, X509_ALGOR *algor1,
+ X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
+ const void *data, const ASN1_OCTET_STRING *id,
+ EVP_PKEY *pkey, const EVP_MD *md, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int ASN1_item_verify_ex(const ASN1_ITEM *it, const X509_ALGOR *alg,
+ const ASN1_BIT_STRING *signature, const void *data,
+ const ASN1_OCTET_STRING *id, EVP_PKEY *pkey,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+/* ASN1 alloc/free macros for when a type is only used internally */
+
+# define M_ASN1_new_of(type) (type *)ASN1_item_new(ASN1_ITEM_rptr(type))
+# define M_ASN1_free_of(x, type) \
+ ASN1_item_free(CHECKED_PTR_OF(type, x), ASN1_ITEM_rptr(type))
+
+# ifndef OPENSSL_NO_STDIO
+void *ASN1_d2i_fp(void *(*xnew) (void), d2i_of_void *d2i, FILE *in, void **x);
+
+# define ASN1_d2i_fp_of(type,xnew,d2i,in,x) \
+ ((type*)ASN1_d2i_fp(CHECKED_NEW_OF(type, xnew), \
+ CHECKED_D2I_OF(type, d2i), \
+ in, \
+ CHECKED_PPTR_OF(type, x)))
+
+void *ASN1_item_d2i_fp_ex(const ASN1_ITEM *it, FILE *in, void *x,
+ OSSL_LIB_CTX *libctx, const char *propq);
+void *ASN1_item_d2i_fp(const ASN1_ITEM *it, FILE *in, void *x);
+int ASN1_i2d_fp(i2d_of_void *i2d, FILE *out, const void *x);
+
+# define ASN1_i2d_fp_of(type,i2d,out,x) \
+ (ASN1_i2d_fp(CHECKED_I2D_OF(type, i2d), \
+ out, \
+ CHECKED_PTR_OF(const type, x)))
+
+int ASN1_item_i2d_fp(const ASN1_ITEM *it, FILE *out, const void *x);
+int ASN1_STRING_print_ex_fp(FILE *fp, const ASN1_STRING *str, unsigned long flags);
+# endif
+
+int ASN1_STRING_to_UTF8(unsigned char **out, const ASN1_STRING *in);
+
+void *ASN1_d2i_bio(void *(*xnew) (void), d2i_of_void *d2i, BIO *in, void **x);
+
+# define ASN1_d2i_bio_of(type,xnew,d2i,in,x) \
+ ((type*)ASN1_d2i_bio( CHECKED_NEW_OF(type, xnew), \
+ CHECKED_D2I_OF(type, d2i), \
+ in, \
+ CHECKED_PPTR_OF(type, x)))
+
+void *ASN1_item_d2i_bio_ex(const ASN1_ITEM *it, BIO *in, void *pval,
+ OSSL_LIB_CTX *libctx, const char *propq);
+void *ASN1_item_d2i_bio(const ASN1_ITEM *it, BIO *in, void *pval);
+int ASN1_i2d_bio(i2d_of_void *i2d, BIO *out, const void *x);
+
+# define ASN1_i2d_bio_of(type,i2d,out,x) \
+ (ASN1_i2d_bio(CHECKED_I2D_OF(type, i2d), \
+ out, \
+ CHECKED_PTR_OF(const type, x)))
+
+int ASN1_item_i2d_bio(const ASN1_ITEM *it, BIO *out, const void *x);
+BIO *ASN1_item_i2d_mem_bio(const ASN1_ITEM *it, const ASN1_VALUE *val);
+int ASN1_UTCTIME_print(BIO *fp, const ASN1_UTCTIME *a);
+int ASN1_GENERALIZEDTIME_print(BIO *fp, const ASN1_GENERALIZEDTIME *a);
+int ASN1_TIME_print(BIO *bp, const ASN1_TIME *tm);
+int ASN1_TIME_print_ex(BIO *bp, const ASN1_TIME *tm, unsigned long flags);
+int ASN1_STRING_print(BIO *bp, const ASN1_STRING *v);
+int ASN1_STRING_print_ex(BIO *out, const ASN1_STRING *str, unsigned long flags);
+int ASN1_buf_print(BIO *bp, const unsigned char *buf, size_t buflen, int off);
+int ASN1_bn_print(BIO *bp, const char *number, const BIGNUM *num,
+ unsigned char *buf, int off);
+int ASN1_parse(BIO *bp, const unsigned char *pp, long len, int indent);
+int ASN1_parse_dump(BIO *bp, const unsigned char *pp, long len, int indent,
+ int dump);
+const char *ASN1_tag2str(int tag);
+
+/* Used to load and write Netscape format cert */
+
+int ASN1_UNIVERSALSTRING_to_string(ASN1_UNIVERSALSTRING *s);
+
+int ASN1_TYPE_set_octetstring(ASN1_TYPE *a, unsigned char *data, int len);
+int ASN1_TYPE_get_octetstring(const ASN1_TYPE *a, unsigned char *data, int max_len);
+int ASN1_TYPE_set_int_octetstring(ASN1_TYPE *a, long num,
+ unsigned char *data, int len);
+int ASN1_TYPE_get_int_octetstring(const ASN1_TYPE *a, long *num,
+ unsigned char *data, int max_len);
+
+void *ASN1_item_unpack(const ASN1_STRING *oct, const ASN1_ITEM *it);
+
+ASN1_STRING *ASN1_item_pack(void *obj, const ASN1_ITEM *it,
+ ASN1_OCTET_STRING **oct);
+
+void ASN1_STRING_set_default_mask(unsigned long mask);
+int ASN1_STRING_set_default_mask_asc(const char *p);
+unsigned long ASN1_STRING_get_default_mask(void);
+int ASN1_mbstring_copy(ASN1_STRING **out, const unsigned char *in, int len,
+ int inform, unsigned long mask);
+int ASN1_mbstring_ncopy(ASN1_STRING **out, const unsigned char *in, int len,
+ int inform, unsigned long mask,
+ long minsize, long maxsize);
+
+ASN1_STRING *ASN1_STRING_set_by_NID(ASN1_STRING **out,
+ const unsigned char *in, int inlen,
+ int inform, int nid);
+ASN1_STRING_TABLE *ASN1_STRING_TABLE_get(int nid);
+int ASN1_STRING_TABLE_add(int, long, long, unsigned long, unsigned long);
+void ASN1_STRING_TABLE_cleanup(void);
+
+/* ASN1 template functions */
+
+/* Old API compatible functions */
+ASN1_VALUE *ASN1_item_new(const ASN1_ITEM *it);
+ASN1_VALUE *ASN1_item_new_ex(const ASN1_ITEM *it, OSSL_LIB_CTX *libctx,
+ const char *propq);
+void ASN1_item_free(ASN1_VALUE *val, const ASN1_ITEM *it);
+ASN1_VALUE *ASN1_item_d2i_ex(ASN1_VALUE **val, const unsigned char **in,
+ long len, const ASN1_ITEM *it,
+ OSSL_LIB_CTX *libctx, const char *propq);
+ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **val, const unsigned char **in,
+ long len, const ASN1_ITEM *it);
+int ASN1_item_i2d(const ASN1_VALUE *val, unsigned char **out, const ASN1_ITEM *it);
+int ASN1_item_ndef_i2d(const ASN1_VALUE *val, unsigned char **out,
+ const ASN1_ITEM *it);
+
+void ASN1_add_oid_module(void);
+void ASN1_add_stable_module(void);
+
+ASN1_TYPE *ASN1_generate_nconf(const char *str, CONF *nconf);
+ASN1_TYPE *ASN1_generate_v3(const char *str, X509V3_CTX *cnf);
+int ASN1_str2mask(const char *str, unsigned long *pmask);
+
+/* ASN1 Print flags */
+
+/* Indicate missing OPTIONAL fields */
+# define ASN1_PCTX_FLAGS_SHOW_ABSENT 0x001
+/* Mark start and end of SEQUENCE */
+# define ASN1_PCTX_FLAGS_SHOW_SEQUENCE 0x002
+/* Mark start and end of SEQUENCE/SET OF */
+# define ASN1_PCTX_FLAGS_SHOW_SSOF 0x004
+/* Show the ASN1 type of primitives */
+# define ASN1_PCTX_FLAGS_SHOW_TYPE 0x008
+/* Don't show ASN1 type of ANY */
+# define ASN1_PCTX_FLAGS_NO_ANY_TYPE 0x010
+/* Don't show ASN1 type of MSTRINGs */
+# define ASN1_PCTX_FLAGS_NO_MSTRING_TYPE 0x020
+/* Don't show field names in SEQUENCE */
+# define ASN1_PCTX_FLAGS_NO_FIELD_NAME 0x040
+/* Show structure names of each SEQUENCE field */
+# define ASN1_PCTX_FLAGS_SHOW_FIELD_STRUCT_NAME 0x080
+/* Don't show structure name even at top level */
+# define ASN1_PCTX_FLAGS_NO_STRUCT_NAME 0x100
+
+int ASN1_item_print(BIO *out, const ASN1_VALUE *ifld, int indent,
+ const ASN1_ITEM *it, const ASN1_PCTX *pctx);
+ASN1_PCTX *ASN1_PCTX_new(void);
+void ASN1_PCTX_free(ASN1_PCTX *p);
+unsigned long ASN1_PCTX_get_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_nm_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_nm_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_cert_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_cert_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_oid_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_oid_flags(ASN1_PCTX *p, unsigned long flags);
+unsigned long ASN1_PCTX_get_str_flags(const ASN1_PCTX *p);
+void ASN1_PCTX_set_str_flags(ASN1_PCTX *p, unsigned long flags);
+
+ASN1_SCTX *ASN1_SCTX_new(int (*scan_cb) (ASN1_SCTX *ctx));
+void ASN1_SCTX_free(ASN1_SCTX *p);
+const ASN1_ITEM *ASN1_SCTX_get_item(ASN1_SCTX *p);
+const ASN1_TEMPLATE *ASN1_SCTX_get_template(ASN1_SCTX *p);
+unsigned long ASN1_SCTX_get_flags(ASN1_SCTX *p);
+void ASN1_SCTX_set_app_data(ASN1_SCTX *p, void *data);
+void *ASN1_SCTX_get_app_data(ASN1_SCTX *p);
+
+const BIO_METHOD *BIO_f_asn1(void);
+
+/* cannot constify val because of CMS_stream() */
+BIO *BIO_new_NDEF(BIO *out, ASN1_VALUE *val, const ASN1_ITEM *it);
+
+int i2d_ASN1_bio_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
+ const ASN1_ITEM *it);
+int PEM_write_bio_ASN1_stream(BIO *out, ASN1_VALUE *val, BIO *in, int flags,
+ const char *hdr, const ASN1_ITEM *it);
+/* cannot constify val because of CMS_dataFinal() */
+int SMIME_write_ASN1(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
+ int ctype_nid, int econt_nid,
+ STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it);
+int SMIME_write_ASN1_ex(BIO *bio, ASN1_VALUE *val, BIO *data, int flags,
+ int ctype_nid, int econt_nid,
+ STACK_OF(X509_ALGOR) *mdalgs, const ASN1_ITEM *it,
+ OSSL_LIB_CTX *libctx, const char *propq);
+ASN1_VALUE *SMIME_read_ASN1(BIO *bio, BIO **bcont, const ASN1_ITEM *it);
+ASN1_VALUE *SMIME_read_ASN1_ex(BIO *bio, int flags, BIO **bcont,
+ const ASN1_ITEM *it, ASN1_VALUE **x,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int SMIME_crlf_copy(BIO *in, BIO *out, int flags);
+int SMIME_text(BIO *in, BIO *out);
+
+const ASN1_ITEM *ASN1_ITEM_lookup(const char *name);
+const ASN1_ITEM *ASN1_ITEM_get(size_t i);
+
+/* Legacy compatibility */
+# define DECLARE_ASN1_FUNCTIONS_fname(type, itname, name) \
+ DECLARE_ASN1_ALLOC_FUNCTIONS_name(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS(type, itname, name)
+# define DECLARE_ASN1_FUNCTIONS_const(type) DECLARE_ASN1_FUNCTIONS(type)
+# define DECLARE_ASN1_ENCODE_FUNCTIONS_const(type, name) \
+ DECLARE_ASN1_ENCODE_FUNCTIONS(type, name)
+# define I2D_OF_const(type) I2D_OF(type)
+# define ASN1_dup_of_const(type,i2d,d2i,x) ASN1_dup_of(type,i2d,d2i,x)
+# define ASN1_i2d_fp_of_const(type,i2d,out,x) ASN1_i2d_fp_of(type,i2d,out,x)
+# define ASN1_i2d_bio_of_const(type,i2d,out,x) ASN1_i2d_bio_of(type,i2d,out,x)
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/asn1_mac.h b/include/openssl/asn1_mac.h
new file mode 100644
index 00000000..fdcb9836
--- /dev/null
+++ b/include/openssl/asn1_mac.h
@@ -0,0 +1,10 @@
+/*
+ * Copyright 2015-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#error "This file is obsolete; please update your software."
diff --git a/include/openssl/asn1err.h b/include/openssl/asn1err.h
new file mode 100644
index 00000000..d4276220
--- /dev/null
+++ b/include/openssl/asn1err.h
@@ -0,0 +1,140 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ASN1ERR_H
+# define OPENSSL_ASN1ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * ASN1 reason codes.
+ */
+# define ASN1_R_ADDING_OBJECT 171
+# define ASN1_R_ASN1_PARSE_ERROR 203
+# define ASN1_R_ASN1_SIG_PARSE_ERROR 204
+# define ASN1_R_AUX_ERROR 100
+# define ASN1_R_BAD_OBJECT_HEADER 102
+# define ASN1_R_BAD_TEMPLATE 230
+# define ASN1_R_BMPSTRING_IS_WRONG_LENGTH 214
+# define ASN1_R_BN_LIB 105
+# define ASN1_R_BOOLEAN_IS_WRONG_LENGTH 106
+# define ASN1_R_BUFFER_TOO_SMALL 107
+# define ASN1_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER 108
+# define ASN1_R_CONTEXT_NOT_INITIALISED 217
+# define ASN1_R_DATA_IS_WRONG 109
+# define ASN1_R_DECODE_ERROR 110
+# define ASN1_R_DEPTH_EXCEEDED 174
+# define ASN1_R_DIGEST_AND_KEY_TYPE_NOT_SUPPORTED 198
+# define ASN1_R_ENCODE_ERROR 112
+# define ASN1_R_ERROR_GETTING_TIME 173
+# define ASN1_R_ERROR_LOADING_SECTION 172
+# define ASN1_R_ERROR_SETTING_CIPHER_PARAMS 114
+# define ASN1_R_EXPECTING_AN_INTEGER 115
+# define ASN1_R_EXPECTING_AN_OBJECT 116
+# define ASN1_R_EXPLICIT_LENGTH_MISMATCH 119
+# define ASN1_R_EXPLICIT_TAG_NOT_CONSTRUCTED 120
+# define ASN1_R_FIELD_MISSING 121
+# define ASN1_R_FIRST_NUM_TOO_LARGE 122
+# define ASN1_R_HEADER_TOO_LONG 123
+# define ASN1_R_ILLEGAL_BITSTRING_FORMAT 175
+# define ASN1_R_ILLEGAL_BOOLEAN 176
+# define ASN1_R_ILLEGAL_CHARACTERS 124
+# define ASN1_R_ILLEGAL_FORMAT 177
+# define ASN1_R_ILLEGAL_HEX 178
+# define ASN1_R_ILLEGAL_IMPLICIT_TAG 179
+# define ASN1_R_ILLEGAL_INTEGER 180
+# define ASN1_R_ILLEGAL_NEGATIVE_VALUE 226
+# define ASN1_R_ILLEGAL_NESTED_TAGGING 181
+# define ASN1_R_ILLEGAL_NULL 125
+# define ASN1_R_ILLEGAL_NULL_VALUE 182
+# define ASN1_R_ILLEGAL_OBJECT 183
+# define ASN1_R_ILLEGAL_OPTIONAL_ANY 126
+# define ASN1_R_ILLEGAL_OPTIONS_ON_ITEM_TEMPLATE 170
+# define ASN1_R_ILLEGAL_PADDING 221
+# define ASN1_R_ILLEGAL_TAGGED_ANY 127
+# define ASN1_R_ILLEGAL_TIME_VALUE 184
+# define ASN1_R_ILLEGAL_ZERO_CONTENT 222
+# define ASN1_R_INTEGER_NOT_ASCII_FORMAT 185
+# define ASN1_R_INTEGER_TOO_LARGE_FOR_LONG 128
+# define ASN1_R_INVALID_BIT_STRING_BITS_LEFT 220
+# define ASN1_R_INVALID_BMPSTRING_LENGTH 129
+# define ASN1_R_INVALID_DIGIT 130
+# define ASN1_R_INVALID_MIME_TYPE 205
+# define ASN1_R_INVALID_MODIFIER 186
+# define ASN1_R_INVALID_NUMBER 187
+# define ASN1_R_INVALID_OBJECT_ENCODING 216
+# define ASN1_R_INVALID_SCRYPT_PARAMETERS 227
+# define ASN1_R_INVALID_SEPARATOR 131
+# define ASN1_R_INVALID_STRING_TABLE_VALUE 218
+# define ASN1_R_INVALID_UNIVERSALSTRING_LENGTH 133
+# define ASN1_R_INVALID_UTF8STRING 134
+# define ASN1_R_INVALID_VALUE 219
+# define ASN1_R_LENGTH_TOO_LONG 231
+# define ASN1_R_LIST_ERROR 188
+# define ASN1_R_MIME_NO_CONTENT_TYPE 206
+# define ASN1_R_MIME_PARSE_ERROR 207
+# define ASN1_R_MIME_SIG_PARSE_ERROR 208
+# define ASN1_R_MISSING_EOC 137
+# define ASN1_R_MISSING_SECOND_NUMBER 138
+# define ASN1_R_MISSING_VALUE 189
+# define ASN1_R_MSTRING_NOT_UNIVERSAL 139
+# define ASN1_R_MSTRING_WRONG_TAG 140
+# define ASN1_R_NESTED_ASN1_STRING 197
+# define ASN1_R_NESTED_TOO_DEEP 201
+# define ASN1_R_NON_HEX_CHARACTERS 141
+# define ASN1_R_NOT_ASCII_FORMAT 190
+# define ASN1_R_NOT_ENOUGH_DATA 142
+# define ASN1_R_NO_CONTENT_TYPE 209
+# define ASN1_R_NO_MATCHING_CHOICE_TYPE 143
+# define ASN1_R_NO_MULTIPART_BODY_FAILURE 210
+# define ASN1_R_NO_MULTIPART_BOUNDARY 211
+# define ASN1_R_NO_SIG_CONTENT_TYPE 212
+# define ASN1_R_NULL_IS_WRONG_LENGTH 144
+# define ASN1_R_OBJECT_NOT_ASCII_FORMAT 191
+# define ASN1_R_ODD_NUMBER_OF_CHARS 145
+# define ASN1_R_SECOND_NUMBER_TOO_LARGE 147
+# define ASN1_R_SEQUENCE_LENGTH_MISMATCH 148
+# define ASN1_R_SEQUENCE_NOT_CONSTRUCTED 149
+# define ASN1_R_SEQUENCE_OR_SET_NEEDS_CONFIG 192
+# define ASN1_R_SHORT_LINE 150
+# define ASN1_R_SIG_INVALID_MIME_TYPE 213
+# define ASN1_R_STREAMING_NOT_SUPPORTED 202
+# define ASN1_R_STRING_TOO_LONG 151
+# define ASN1_R_STRING_TOO_SHORT 152
+# define ASN1_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD 154
+# define ASN1_R_TIME_NOT_ASCII_FORMAT 193
+# define ASN1_R_TOO_LARGE 223
+# define ASN1_R_TOO_LONG 155
+# define ASN1_R_TOO_SMALL 224
+# define ASN1_R_TYPE_NOT_CONSTRUCTED 156
+# define ASN1_R_TYPE_NOT_PRIMITIVE 195
+# define ASN1_R_UNEXPECTED_EOC 159
+# define ASN1_R_UNIVERSALSTRING_IS_WRONG_LENGTH 215
+# define ASN1_R_UNKNOWN_DIGEST 229
+# define ASN1_R_UNKNOWN_FORMAT 160
+# define ASN1_R_UNKNOWN_MESSAGE_DIGEST_ALGORITHM 161
+# define ASN1_R_UNKNOWN_OBJECT_TYPE 162
+# define ASN1_R_UNKNOWN_PUBLIC_KEY_TYPE 163
+# define ASN1_R_UNKNOWN_SIGNATURE_ALGORITHM 199
+# define ASN1_R_UNKNOWN_TAG 194
+# define ASN1_R_UNSUPPORTED_ANY_DEFINED_BY_TYPE 164
+# define ASN1_R_UNSUPPORTED_CIPHER 228
+# define ASN1_R_UNSUPPORTED_PUBLIC_KEY_TYPE 167
+# define ASN1_R_UNSUPPORTED_TYPE 196
+# define ASN1_R_WRONG_INTEGER_TYPE 225
+# define ASN1_R_WRONG_PUBLIC_KEY_TYPE 200
+# define ASN1_R_WRONG_TAG 168
+
+#endif
diff --git a/include/openssl/asn1t.h b/include/openssl/asn1t.h
new file mode 100644
index 00000000..a725c532
--- /dev/null
+++ b/include/openssl/asn1t.h
@@ -0,0 +1,946 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\asn1t.h.in
+ *
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_ASN1T_H
+# define OPENSSL_ASN1T_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ASN1T_H
+# endif
+
+# include <stddef.h>
+# include <openssl/e_os2.h>
+# include <openssl/asn1.h>
+
+# ifdef OPENSSL_BUILD_SHLIBCRYPTO
+# undef OPENSSL_EXTERN
+# define OPENSSL_EXTERN OPENSSL_EXPORT
+# endif
+
+/* ASN1 template defines, structures and functions */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-
+ * These are the possible values for the itype field of the
+ * ASN1_ITEM structure and determine how it is interpreted.
+ *
+ * For PRIMITIVE types the underlying type
+ * determines the behaviour if items is NULL.
+ *
+ * Otherwise templates must contain a single
+ * template and the type is treated in the
+ * same way as the type specified in the template.
+ *
+ * For SEQUENCE types the templates field points
+ * to the members, the size field is the
+ * structure size.
+ *
+ * For CHOICE types the templates field points
+ * to each possible member (typically a union)
+ * and the 'size' field is the offset of the
+ * selector.
+ *
+ * The 'funcs' field is used for application-specific
+ * data and functions.
+ *
+ * The EXTERN type uses a new style d2i/i2d.
+ * The new style should be used where possible
+ * because it avoids things like the d2i IMPLICIT
+ * hack.
+ *
+ * MSTRING is a multiple string type, it is used
+ * for a CHOICE of character strings where the
+ * actual strings all occupy an ASN1_STRING
+ * structure. In this case the 'utype' field
+ * has a special meaning, it is used as a mask
+ * of acceptable types using the B_ASN1 constants.
+ *
+ * NDEF_SEQUENCE is the same as SEQUENCE except
+ * that it will use indefinite length constructed
+ * encoding if requested.
+ *
+ */
+
+# define ASN1_ITYPE_PRIMITIVE 0x0
+# define ASN1_ITYPE_SEQUENCE 0x1
+# define ASN1_ITYPE_CHOICE 0x2
+/* unused value 0x3 */
+# define ASN1_ITYPE_EXTERN 0x4
+# define ASN1_ITYPE_MSTRING 0x5
+# define ASN1_ITYPE_NDEF_SEQUENCE 0x6
+
+/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */
+# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)((iptr)()))
+
+/* Macros for start and end of ASN1_ITEM definition */
+
+# define ASN1_ITEM_start(itname) \
+ const ASN1_ITEM * itname##_it(void) \
+ { \
+ static const ASN1_ITEM local_it = {
+
+# define static_ASN1_ITEM_start(itname) \
+ static ASN1_ITEM_start(itname)
+
+# define ASN1_ITEM_end(itname) \
+ }; \
+ return &local_it; \
+ }
+
+/* Macros to aid ASN1 template writing */
+
+# define ASN1_ITEM_TEMPLATE(tname) \
+ static const ASN1_TEMPLATE tname##_item_tt
+
+# define ASN1_ITEM_TEMPLATE_END(tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_PRIMITIVE,\
+ -1,\
+ &tname##_item_tt,\
+ 0,\
+ NULL,\
+ 0,\
+ #tname \
+ ASN1_ITEM_end(tname)
+# define static_ASN1_ITEM_TEMPLATE_END(tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_PRIMITIVE,\
+ -1,\
+ &tname##_item_tt,\
+ 0,\
+ NULL,\
+ 0,\
+ #tname \
+ ASN1_ITEM_end(tname)
+
+/* This is a ASN1 type which just embeds a template */
+
+/*-
+ * This pair helps declare a SEQUENCE. We can do:
+ *
+ * ASN1_SEQUENCE(stname) = {
+ * ... SEQUENCE components ...
+ * } ASN1_SEQUENCE_END(stname)
+ *
+ * This will produce an ASN1_ITEM called stname_it
+ * for a structure called stname.
+ *
+ * If you want the same structure but a different
+ * name then use:
+ *
+ * ASN1_SEQUENCE(itname) = {
+ * ... SEQUENCE components ...
+ * } ASN1_SEQUENCE_END_name(stname, itname)
+ *
+ * This will create an item called itname_it using
+ * a structure called stname.
+ */
+
+# define ASN1_SEQUENCE(tname) \
+ static const ASN1_TEMPLATE tname##_seq_tt[]
+
+# define ASN1_SEQUENCE_END(stname) ASN1_SEQUENCE_END_name(stname, stname)
+
+# define static_ASN1_SEQUENCE_END(stname) static_ASN1_SEQUENCE_END_name(stname, stname)
+
+# define ASN1_SEQUENCE_END_name(stname, tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+
+# define static_ASN1_SEQUENCE_END_name(stname, tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define ASN1_NDEF_SEQUENCE(tname) \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_NDEF_SEQUENCE_cb(tname, cb) \
+ ASN1_SEQUENCE_cb(tname, cb)
+
+# define ASN1_SEQUENCE_cb(tname, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0, NULL}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_const_cb(tname, const_cb) \
+ static const ASN1_AUX tname##_aux = \
+ {NULL, ASN1_AFLG_CONST_CB, 0, 0, NULL, 0, const_cb}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_cb_const_cb(tname, cb, const_cb) \
+ static const ASN1_AUX tname##_aux = \
+ {NULL, ASN1_AFLG_CONST_CB, 0, 0, cb, 0, const_cb}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_ref(tname, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_REFCOUNT, offsetof(tname, references), offsetof(tname, lock), cb, 0, NULL}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_enc(tname, enc, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_ENCODING, 0, 0, cb, offsetof(tname, enc), NULL}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_NDEF_SEQUENCE_END(tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_NDEF_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(tname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+# define static_ASN1_NDEF_SEQUENCE_END(tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_NDEF_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(tname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+
+
+# define ASN1_SEQUENCE_END_enc(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
+
+# define ASN1_SEQUENCE_END_cb(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
+# define static_ASN1_SEQUENCE_END_cb(stname, tname) static_ASN1_SEQUENCE_END_ref(stname, tname)
+
+# define ASN1_SEQUENCE_END_ref(stname, tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+# define static_ASN1_SEQUENCE_END_ref(stname, tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define ASN1_NDEF_SEQUENCE_END_cb(stname, tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_NDEF_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+/*-
+ * This pair helps declare a CHOICE type. We can do:
+ *
+ * ASN1_CHOICE(chname) = {
+ * ... CHOICE options ...
+ * ASN1_CHOICE_END(chname)
+ *
+ * This will produce an ASN1_ITEM called chname_it
+ * for a structure called chname. The structure
+ * definition must look like this:
+ * typedef struct {
+ * int type;
+ * union {
+ * ASN1_SOMETHING *opt1;
+ * ASN1_SOMEOTHER *opt2;
+ * } value;
+ * } chname;
+ *
+ * the name of the selector must be 'type'.
+ * to use an alternative selector name use the
+ * ASN1_CHOICE_END_selector() version.
+ */
+
+# define ASN1_CHOICE(tname) \
+ static const ASN1_TEMPLATE tname##_ch_tt[]
+
+# define ASN1_CHOICE_cb(tname, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0, NULL}; \
+ ASN1_CHOICE(tname)
+
+# define ASN1_CHOICE_END(stname) ASN1_CHOICE_END_name(stname, stname)
+
+# define static_ASN1_CHOICE_END(stname) static_ASN1_CHOICE_END_name(stname, stname)
+
+# define ASN1_CHOICE_END_name(stname, tname) ASN1_CHOICE_END_selector(stname, tname, type)
+
+# define static_ASN1_CHOICE_END_name(stname, tname) static_ASN1_CHOICE_END_selector(stname, tname, type)
+
+# define ASN1_CHOICE_END_selector(stname, tname, selname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_CHOICE,\
+ offsetof(stname,selname) ,\
+ tname##_ch_tt,\
+ sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define static_ASN1_CHOICE_END_selector(stname, tname, selname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_CHOICE,\
+ offsetof(stname,selname) ,\
+ tname##_ch_tt,\
+ sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define ASN1_CHOICE_END_cb(stname, tname, selname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_CHOICE,\
+ offsetof(stname,selname) ,\
+ tname##_ch_tt,\
+ sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+/* This helps with the template wrapper form of ASN1_ITEM */
+
+# define ASN1_EX_TEMPLATE_TYPE(flags, tag, name, type) { \
+ (flags), (tag), 0,\
+ #name, ASN1_ITEM_ref(type) }
+
+/* These help with SEQUENCE or CHOICE components */
+
+/* used to declare other types */
+
+# define ASN1_EX_TYPE(flags, tag, stname, field, type) { \
+ (flags), (tag), offsetof(stname, field),\
+ #field, ASN1_ITEM_ref(type) }
+
+/* implicit and explicit helper macros */
+
+# define ASN1_IMP_EX(stname, field, type, tag, ex) \
+ ASN1_EX_TYPE(ASN1_TFLG_IMPLICIT | (ex), tag, stname, field, type)
+
+# define ASN1_EXP_EX(stname, field, type, tag, ex) \
+ ASN1_EX_TYPE(ASN1_TFLG_EXPLICIT | (ex), tag, stname, field, type)
+
+/* Any defined by macros: the field used is in the table itself */
+
+# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, tblname##_adb }
+# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, tblname##_adb }
+
+/* Plain simple type */
+# define ASN1_SIMPLE(stname, field, type) ASN1_EX_TYPE(0,0, stname, field, type)
+/* Embedded simple type */
+# define ASN1_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_EMBED,0, stname, field, type)
+
+/* OPTIONAL simple type */
+# define ASN1_OPT(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL, 0, stname, field, type)
+# define ASN1_OPT_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED, 0, stname, field, type)
+
+/* IMPLICIT tagged simple type */
+# define ASN1_IMP(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, 0)
+# define ASN1_IMP_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
+
+/* IMPLICIT tagged OPTIONAL simple type */
+# define ASN1_IMP_OPT(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
+# define ASN1_IMP_OPT_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
+
+/* Same as above but EXPLICIT */
+
+# define ASN1_EXP(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, 0)
+# define ASN1_EXP_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
+# define ASN1_EXP_OPT(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
+# define ASN1_EXP_OPT_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
+
+/* SEQUENCE OF type */
+# define ASN1_SEQUENCE_OF(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, stname, field, type)
+
+/* OPTIONAL SEQUENCE OF */
+# define ASN1_SEQUENCE_OF_OPT(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
+
+/* Same as above but for SET OF */
+
+# define ASN1_SET_OF(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SET_OF, 0, stname, field, type)
+
+# define ASN1_SET_OF_OPT(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
+
+/* Finally compound types of SEQUENCE, SET, IMPLICIT, EXPLICIT and OPTIONAL */
+
+# define ASN1_IMP_SET_OF(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
+
+# define ASN1_EXP_SET_OF(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
+
+# define ASN1_IMP_SET_OF_OPT(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
+
+# define ASN1_EXP_SET_OF_OPT(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
+
+# define ASN1_IMP_SEQUENCE_OF(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
+
+# define ASN1_IMP_SEQUENCE_OF_OPT(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
+
+# define ASN1_EXP_SEQUENCE_OF(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
+
+# define ASN1_EXP_SEQUENCE_OF_OPT(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
+
+/* EXPLICIT using indefinite length constructed form */
+# define ASN1_NDEF_EXP(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_NDEF)
+
+/* EXPLICIT OPTIONAL using indefinite length constructed form */
+# define ASN1_NDEF_EXP_OPT(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_NDEF)
+
+/* Macros for the ASN1_ADB structure */
+
+# define ASN1_ADB(name) \
+ static const ASN1_ADB_TABLE name##_adbtbl[]
+
+# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \
+ ;\
+ static const ASN1_ITEM *name##_adb(void) \
+ { \
+ static const ASN1_ADB internal_adb = \
+ {\
+ flags,\
+ offsetof(name, field),\
+ adb_cb,\
+ name##_adbtbl,\
+ sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\
+ def,\
+ none\
+ }; \
+ return (const ASN1_ITEM *) &internal_adb; \
+ } \
+ void dummy_function(void)
+
+# define ADB_ENTRY(val, template) {val, template}
+
+# define ASN1_ADB_TEMPLATE(name) \
+ static const ASN1_TEMPLATE name##_tt
+
+/*
+ * This is the ASN1 template structure that defines a wrapper round the
+ * actual type. It determines the actual position of the field in the value
+ * structure, various flags such as OPTIONAL and the field name.
+ */
+
+struct ASN1_TEMPLATE_st {
+ unsigned long flags; /* Various flags */
+ long tag; /* tag, not used if no tagging */
+ unsigned long offset; /* Offset of this field in structure */
+ const char *field_name; /* Field name */
+ ASN1_ITEM_EXP *item; /* Relevant ASN1_ITEM or ASN1_ADB */
+};
+
+/* Macro to extract ASN1_ITEM and ASN1_ADB pointer from ASN1_TEMPLATE */
+
+# define ASN1_TEMPLATE_item(t) (t->item_ptr)
+# define ASN1_TEMPLATE_adb(t) (t->item_ptr)
+
+typedef struct ASN1_ADB_TABLE_st ASN1_ADB_TABLE;
+typedef struct ASN1_ADB_st ASN1_ADB;
+
+struct ASN1_ADB_st {
+ unsigned long flags; /* Various flags */
+ unsigned long offset; /* Offset of selector field */
+ int (*adb_cb)(long *psel); /* Application callback */
+ const ASN1_ADB_TABLE *tbl; /* Table of possible types */
+ long tblcount; /* Number of entries in tbl */
+ const ASN1_TEMPLATE *default_tt; /* Type to use if no match */
+ const ASN1_TEMPLATE *null_tt; /* Type to use if selector is NULL */
+};
+
+struct ASN1_ADB_TABLE_st {
+ long value; /* NID for an object or value for an int */
+ const ASN1_TEMPLATE tt; /* item for this value */
+};
+
+/* template flags */
+
+/* Field is optional */
+# define ASN1_TFLG_OPTIONAL (0x1)
+
+/* Field is a SET OF */
+# define ASN1_TFLG_SET_OF (0x1 << 1)
+
+/* Field is a SEQUENCE OF */
+# define ASN1_TFLG_SEQUENCE_OF (0x2 << 1)
+
+/*
+ * Special case: this refers to a SET OF that will be sorted into DER order
+ * when encoded *and* the corresponding STACK will be modified to match the
+ * new order.
+ */
+# define ASN1_TFLG_SET_ORDER (0x3 << 1)
+
+/* Mask for SET OF or SEQUENCE OF */
+# define ASN1_TFLG_SK_MASK (0x3 << 1)
+
+/*
+ * These flags mean the tag should be taken from the tag field. If EXPLICIT
+ * then the underlying type is used for the inner tag.
+ */
+
+/* IMPLICIT tagging */
+# define ASN1_TFLG_IMPTAG (0x1 << 3)
+
+/* EXPLICIT tagging, inner tag from underlying type */
+# define ASN1_TFLG_EXPTAG (0x2 << 3)
+
+# define ASN1_TFLG_TAG_MASK (0x3 << 3)
+
+/* context specific IMPLICIT */
+# define ASN1_TFLG_IMPLICIT (ASN1_TFLG_IMPTAG|ASN1_TFLG_CONTEXT)
+
+/* context specific EXPLICIT */
+# define ASN1_TFLG_EXPLICIT (ASN1_TFLG_EXPTAG|ASN1_TFLG_CONTEXT)
+
+/*
+ * If tagging is in force these determine the type of tag to use. Otherwise
+ * the tag is determined by the underlying type. These values reflect the
+ * actual octet format.
+ */
+
+/* Universal tag */
+# define ASN1_TFLG_UNIVERSAL (0x0<<6)
+/* Application tag */
+# define ASN1_TFLG_APPLICATION (0x1<<6)
+/* Context specific tag */
+# define ASN1_TFLG_CONTEXT (0x2<<6)
+/* Private tag */
+# define ASN1_TFLG_PRIVATE (0x3<<6)
+
+# define ASN1_TFLG_TAG_CLASS (0x3<<6)
+
+/*
+ * These are for ANY DEFINED BY type. In this case the 'item' field points to
+ * an ASN1_ADB structure which contains a table of values to decode the
+ * relevant type
+ */
+
+# define ASN1_TFLG_ADB_MASK (0x3<<8)
+
+# define ASN1_TFLG_ADB_OID (0x1<<8)
+
+# define ASN1_TFLG_ADB_INT (0x1<<9)
+
+/*
+ * This flag when present in a SEQUENCE OF, SET OF or EXPLICIT causes
+ * indefinite length constructed encoding to be used if required.
+ */
+
+# define ASN1_TFLG_NDEF (0x1<<11)
+
+/* Field is embedded and not a pointer */
+# define ASN1_TFLG_EMBED (0x1 << 12)
+
+/* This is the actual ASN1 item itself */
+
+struct ASN1_ITEM_st {
+ char itype; /* The item type, primitive, SEQUENCE, CHOICE
+ * or extern */
+ long utype; /* underlying type */
+ const ASN1_TEMPLATE *templates; /* If SEQUENCE or CHOICE this contains
+ * the contents */
+ long tcount; /* Number of templates if SEQUENCE or CHOICE */
+ const void *funcs; /* further data and type-specific functions */
+ /* funcs can be ASN1_PRIMITIVE_FUNCS*, ASN1_EXTERN_FUNCS*, or ASN1_AUX* */
+ long size; /* Structure size (usually) */
+ const char *sname; /* Structure name */
+};
+
+/*
+ * Cache for ASN1 tag and length, so we don't keep re-reading it for things
+ * like CHOICE
+ */
+
+struct ASN1_TLC_st {
+ char valid; /* Values below are valid */
+ int ret; /* return value */
+ long plen; /* length */
+ int ptag; /* class value */
+ int pclass; /* class value */
+ int hdrlen; /* header length */
+};
+
+/* Typedefs for ASN1 function pointers */
+typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
+ const ASN1_ITEM *it, int tag, int aclass, char opt,
+ ASN1_TLC *ctx);
+
+typedef int ASN1_ex_d2i_ex(ASN1_VALUE **pval, const unsigned char **in, long len,
+ const ASN1_ITEM *it, int tag, int aclass, char opt,
+ ASN1_TLC *ctx, OSSL_LIB_CTX *libctx,
+ const char *propq);
+typedef int ASN1_ex_i2d(const ASN1_VALUE **pval, unsigned char **out,
+ const ASN1_ITEM *it, int tag, int aclass);
+typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
+typedef int ASN1_ex_new_ex_func(ASN1_VALUE **pval, const ASN1_ITEM *it,
+ OSSL_LIB_CTX *libctx, const char *propq);
+typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
+
+typedef int ASN1_ex_print_func(BIO *out, const ASN1_VALUE **pval,
+ int indent, const char *fname,
+ const ASN1_PCTX *pctx);
+
+typedef int ASN1_primitive_i2c(const ASN1_VALUE **pval, unsigned char *cont,
+ int *putype, const ASN1_ITEM *it);
+typedef int ASN1_primitive_c2i(ASN1_VALUE **pval, const unsigned char *cont,
+ int len, int utype, char *free_cont,
+ const ASN1_ITEM *it);
+typedef int ASN1_primitive_print(BIO *out, const ASN1_VALUE **pval,
+ const ASN1_ITEM *it, int indent,
+ const ASN1_PCTX *pctx);
+
+typedef struct ASN1_EXTERN_FUNCS_st {
+ void *app_data;
+ ASN1_ex_new_func *asn1_ex_new;
+ ASN1_ex_free_func *asn1_ex_free;
+ ASN1_ex_free_func *asn1_ex_clear;
+ ASN1_ex_d2i *asn1_ex_d2i;
+ ASN1_ex_i2d *asn1_ex_i2d;
+ ASN1_ex_print_func *asn1_ex_print;
+ ASN1_ex_new_ex_func *asn1_ex_new_ex;
+ ASN1_ex_d2i_ex *asn1_ex_d2i_ex;
+} ASN1_EXTERN_FUNCS;
+
+typedef struct ASN1_PRIMITIVE_FUNCS_st {
+ void *app_data;
+ unsigned long flags;
+ ASN1_ex_new_func *prim_new;
+ ASN1_ex_free_func *prim_free;
+ ASN1_ex_free_func *prim_clear;
+ ASN1_primitive_c2i *prim_c2i;
+ ASN1_primitive_i2c *prim_i2c;
+ ASN1_primitive_print *prim_print;
+} ASN1_PRIMITIVE_FUNCS;
+
+/*
+ * This is the ASN1_AUX structure: it handles various miscellaneous
+ * requirements. For example the use of reference counts and an informational
+ * callback. The "informational callback" is called at various points during
+ * the ASN1 encoding and decoding. It can be used to provide minor
+ * customisation of the structures used. This is most useful where the
+ * supplied routines *almost* do the right thing but need some extra help at
+ * a few points. If the callback returns zero then it is assumed a fatal
+ * error has occurred and the main operation should be abandoned. If major
+ * changes in the default behaviour are required then an external type is
+ * more appropriate.
+ * For the operations ASN1_OP_I2D_PRE, ASN1_OP_I2D_POST, ASN1_OP_PRINT_PRE, and
+ * ASN1_OP_PRINT_POST, meanwhile a variant of the callback with const parameter
+ * 'in' is provided to make clear statically that its input is not modified. If
+ * and only if this variant is in use the flag ASN1_AFLG_CONST_CB must be set.
+ */
+
+typedef int ASN1_aux_cb(int operation, ASN1_VALUE **in, const ASN1_ITEM *it,
+ void *exarg);
+typedef int ASN1_aux_const_cb(int operation, const ASN1_VALUE **in,
+ const ASN1_ITEM *it, void *exarg);
+
+typedef struct ASN1_AUX_st {
+ void *app_data;
+ int flags;
+ int ref_offset; /* Offset of reference value */
+ int ref_lock; /* Offset of lock value */
+ ASN1_aux_cb *asn1_cb;
+ int enc_offset; /* Offset of ASN1_ENCODING structure */
+ ASN1_aux_const_cb *asn1_const_cb; /* for ASN1_OP_I2D_ and ASN1_OP_PRINT_ */
+} ASN1_AUX;
+
+/* For print related callbacks exarg points to this structure */
+typedef struct ASN1_PRINT_ARG_st {
+ BIO *out;
+ int indent;
+ const ASN1_PCTX *pctx;
+} ASN1_PRINT_ARG;
+
+/* For streaming related callbacks exarg points to this structure */
+typedef struct ASN1_STREAM_ARG_st {
+ /* BIO to stream through */
+ BIO *out;
+ /* BIO with filters appended */
+ BIO *ndef_bio;
+ /* Streaming I/O boundary */
+ unsigned char **boundary;
+} ASN1_STREAM_ARG;
+
+/* Flags in ASN1_AUX */
+
+/* Use a reference count */
+# define ASN1_AFLG_REFCOUNT 1
+/* Save the encoding of structure (useful for signatures) */
+# define ASN1_AFLG_ENCODING 2
+/* The Sequence length is invalid */
+# define ASN1_AFLG_BROKEN 4
+/* Use the new asn1_const_cb */
+# define ASN1_AFLG_CONST_CB 8
+
+/* operation values for asn1_cb */
+
+# define ASN1_OP_NEW_PRE 0
+# define ASN1_OP_NEW_POST 1
+# define ASN1_OP_FREE_PRE 2
+# define ASN1_OP_FREE_POST 3
+# define ASN1_OP_D2I_PRE 4
+# define ASN1_OP_D2I_POST 5
+# define ASN1_OP_I2D_PRE 6
+# define ASN1_OP_I2D_POST 7
+# define ASN1_OP_PRINT_PRE 8
+# define ASN1_OP_PRINT_POST 9
+# define ASN1_OP_STREAM_PRE 10
+# define ASN1_OP_STREAM_POST 11
+# define ASN1_OP_DETACHED_PRE 12
+# define ASN1_OP_DETACHED_POST 13
+# define ASN1_OP_DUP_PRE 14
+# define ASN1_OP_DUP_POST 15
+# define ASN1_OP_GET0_LIBCTX 16
+# define ASN1_OP_GET0_PROPQ 17
+
+/* Macro to implement a primitive type */
+# define IMPLEMENT_ASN1_TYPE(stname) IMPLEMENT_ASN1_TYPE_ex(stname, stname, 0)
+# define IMPLEMENT_ASN1_TYPE_ex(itname, vname, ex) \
+ ASN1_ITEM_start(itname) \
+ ASN1_ITYPE_PRIMITIVE, V_##vname, NULL, 0, NULL, ex, #itname \
+ ASN1_ITEM_end(itname)
+
+/* Macro to implement a multi string type */
+# define IMPLEMENT_ASN1_MSTRING(itname, mask) \
+ ASN1_ITEM_start(itname) \
+ ASN1_ITYPE_MSTRING, mask, NULL, 0, NULL, sizeof(ASN1_STRING), #itname \
+ ASN1_ITEM_end(itname)
+
+# define IMPLEMENT_EXTERN_ASN1(sname, tag, fptrs) \
+ ASN1_ITEM_start(sname) \
+ ASN1_ITYPE_EXTERN, \
+ tag, \
+ NULL, \
+ 0, \
+ &fptrs, \
+ 0, \
+ #sname \
+ ASN1_ITEM_end(sname)
+
+/* Macro to implement standard functions in terms of ASN1_ITEM structures */
+
+# define IMPLEMENT_ASN1_FUNCTIONS(stname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, stname, stname)
+
+# define IMPLEMENT_ASN1_FUNCTIONS_name(stname, itname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, itname)
+
+# define IMPLEMENT_ASN1_FUNCTIONS_ENCODE_name(stname, itname) \
+ IMPLEMENT_ASN1_FUNCTIONS_ENCODE_fname(stname, itname, itname)
+
+# define IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(stname) \
+ IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(static, stname, stname, stname)
+
+# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS(stname) \
+ IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, stname, stname)
+
+# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(pre, stname, itname, fname) \
+ pre stname *fname##_new(void) \
+ { \
+ return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
+ } \
+ pre void fname##_free(stname *a) \
+ { \
+ ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
+ }
+
+# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) \
+ stname *fname##_new(void) \
+ { \
+ return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
+ } \
+ void fname##_free(stname *a) \
+ { \
+ ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
+ }
+
+# define IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, fname) \
+ IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
+ IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname)
+
+# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
+ stname *d2i_##fname(stname **a, const unsigned char **in, long len) \
+ { \
+ return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\
+ } \
+ int i2d_##fname(const stname *a, unsigned char **out) \
+ { \
+ return ASN1_item_i2d((const ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\
+ }
+
+# define IMPLEMENT_ASN1_NDEF_FUNCTION(stname) \
+ int i2d_##stname##_NDEF(const stname *a, unsigned char **out) \
+ { \
+ return ASN1_item_ndef_i2d((const ASN1_VALUE *)a, out, ASN1_ITEM_rptr(stname));\
+ }
+
+# define IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(stname) \
+ static stname *d2i_##stname(stname **a, \
+ const unsigned char **in, long len) \
+ { \
+ return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, \
+ ASN1_ITEM_rptr(stname)); \
+ } \
+ static int i2d_##stname(const stname *a, unsigned char **out) \
+ { \
+ return ASN1_item_i2d((const ASN1_VALUE *)a, out, \
+ ASN1_ITEM_rptr(stname)); \
+ }
+
+# define IMPLEMENT_ASN1_DUP_FUNCTION(stname) \
+ stname * stname##_dup(const stname *x) \
+ { \
+ return ASN1_item_dup(ASN1_ITEM_rptr(stname), x); \
+ }
+
+# define IMPLEMENT_ASN1_PRINT_FUNCTION(stname) \
+ IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, stname, stname)
+
+# define IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, itname, fname) \
+ int fname##_print_ctx(BIO *out, const stname *x, int indent, \
+ const ASN1_PCTX *pctx) \
+ { \
+ return ASN1_item_print(out, (const ASN1_VALUE *)x, indent, \
+ ASN1_ITEM_rptr(itname), pctx); \
+ }
+
+/* external definitions for primitive types */
+
+DECLARE_ASN1_ITEM(ASN1_BOOLEAN)
+DECLARE_ASN1_ITEM(ASN1_TBOOLEAN)
+DECLARE_ASN1_ITEM(ASN1_FBOOLEAN)
+DECLARE_ASN1_ITEM(ASN1_SEQUENCE)
+DECLARE_ASN1_ITEM(CBIGNUM)
+DECLARE_ASN1_ITEM(BIGNUM)
+DECLARE_ASN1_ITEM(INT32)
+DECLARE_ASN1_ITEM(ZINT32)
+DECLARE_ASN1_ITEM(UINT32)
+DECLARE_ASN1_ITEM(ZUINT32)
+DECLARE_ASN1_ITEM(INT64)
+DECLARE_ASN1_ITEM(ZINT64)
+DECLARE_ASN1_ITEM(UINT64)
+DECLARE_ASN1_ITEM(ZUINT64)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/*
+ * LONG and ZLONG are strongly discouraged for use as stored data, as the
+ * underlying C type (long) differs in size depending on the architecture.
+ * They are designed with 32-bit longs in mind.
+ */
+DECLARE_ASN1_ITEM(LONG)
+DECLARE_ASN1_ITEM(ZLONG)
+# endif
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_VALUE, ASN1_VALUE, ASN1_VALUE)
+#define sk_ASN1_VALUE_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_VALUE_sk_type(sk))
+#define sk_ASN1_VALUE_value(sk, idx) ((ASN1_VALUE *)OPENSSL_sk_value(ossl_check_const_ASN1_VALUE_sk_type(sk), (idx)))
+#define sk_ASN1_VALUE_new(cmp) ((STACK_OF(ASN1_VALUE) *)OPENSSL_sk_new(ossl_check_ASN1_VALUE_compfunc_type(cmp)))
+#define sk_ASN1_VALUE_new_null() ((STACK_OF(ASN1_VALUE) *)OPENSSL_sk_new_null())
+#define sk_ASN1_VALUE_new_reserve(cmp, n) ((STACK_OF(ASN1_VALUE) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_VALUE_compfunc_type(cmp), (n)))
+#define sk_ASN1_VALUE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_VALUE_sk_type(sk), (n))
+#define sk_ASN1_VALUE_free(sk) OPENSSL_sk_free(ossl_check_ASN1_VALUE_sk_type(sk))
+#define sk_ASN1_VALUE_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_VALUE_sk_type(sk))
+#define sk_ASN1_VALUE_delete(sk, i) ((ASN1_VALUE *)OPENSSL_sk_delete(ossl_check_ASN1_VALUE_sk_type(sk), (i)))
+#define sk_ASN1_VALUE_delete_ptr(sk, ptr) ((ASN1_VALUE *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_type(ptr)))
+#define sk_ASN1_VALUE_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_type(ptr))
+#define sk_ASN1_VALUE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_type(ptr))
+#define sk_ASN1_VALUE_pop(sk) ((ASN1_VALUE *)OPENSSL_sk_pop(ossl_check_ASN1_VALUE_sk_type(sk)))
+#define sk_ASN1_VALUE_shift(sk) ((ASN1_VALUE *)OPENSSL_sk_shift(ossl_check_ASN1_VALUE_sk_type(sk)))
+#define sk_ASN1_VALUE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_VALUE_sk_type(sk),ossl_check_ASN1_VALUE_freefunc_type(freefunc))
+#define sk_ASN1_VALUE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_type(ptr), (idx))
+#define sk_ASN1_VALUE_set(sk, idx, ptr) ((ASN1_VALUE *)OPENSSL_sk_set(ossl_check_ASN1_VALUE_sk_type(sk), (idx), ossl_check_ASN1_VALUE_type(ptr)))
+#define sk_ASN1_VALUE_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_type(ptr))
+#define sk_ASN1_VALUE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_type(ptr))
+#define sk_ASN1_VALUE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_type(ptr), pnum)
+#define sk_ASN1_VALUE_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_VALUE_sk_type(sk))
+#define sk_ASN1_VALUE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_VALUE_sk_type(sk))
+#define sk_ASN1_VALUE_dup(sk) ((STACK_OF(ASN1_VALUE) *)OPENSSL_sk_dup(ossl_check_const_ASN1_VALUE_sk_type(sk)))
+#define sk_ASN1_VALUE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_VALUE) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_copyfunc_type(copyfunc), ossl_check_ASN1_VALUE_freefunc_type(freefunc)))
+#define sk_ASN1_VALUE_set_cmp_func(sk, cmp) ((sk_ASN1_VALUE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_VALUE_sk_type(sk), ossl_check_ASN1_VALUE_compfunc_type(cmp)))
+
+
+
+/* Functions used internally by the ASN1 code */
+
+int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
+void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
+
+int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
+ const ASN1_ITEM *it, int tag, int aclass, char opt,
+ ASN1_TLC *ctx);
+
+int ASN1_item_ex_i2d(const ASN1_VALUE **pval, unsigned char **out,
+ const ASN1_ITEM *it, int tag, int aclass);
+
+/* Legacy compatibility */
+# define IMPLEMENT_ASN1_FUNCTIONS_const(name) IMPLEMENT_ASN1_FUNCTIONS(name)
+# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \
+ IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname)
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/asn1t.h.in b/include/openssl/asn1t.h.in
new file mode 100644
index 00000000..b536fe51
--- /dev/null
+++ b/include/openssl/asn1t.h.in
@@ -0,0 +1,923 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_ASN1T_H
+# define OPENSSL_ASN1T_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ASN1T_H
+# endif
+
+# include <stddef.h>
+# include <openssl/e_os2.h>
+# include <openssl/asn1.h>
+
+# ifdef OPENSSL_BUILD_SHLIBCRYPTO
+# undef OPENSSL_EXTERN
+# define OPENSSL_EXTERN OPENSSL_EXPORT
+# endif
+
+/* ASN1 template defines, structures and functions */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-
+ * These are the possible values for the itype field of the
+ * ASN1_ITEM structure and determine how it is interpreted.
+ *
+ * For PRIMITIVE types the underlying type
+ * determines the behaviour if items is NULL.
+ *
+ * Otherwise templates must contain a single
+ * template and the type is treated in the
+ * same way as the type specified in the template.
+ *
+ * For SEQUENCE types the templates field points
+ * to the members, the size field is the
+ * structure size.
+ *
+ * For CHOICE types the templates field points
+ * to each possible member (typically a union)
+ * and the 'size' field is the offset of the
+ * selector.
+ *
+ * The 'funcs' field is used for application-specific
+ * data and functions.
+ *
+ * The EXTERN type uses a new style d2i/i2d.
+ * The new style should be used where possible
+ * because it avoids things like the d2i IMPLICIT
+ * hack.
+ *
+ * MSTRING is a multiple string type, it is used
+ * for a CHOICE of character strings where the
+ * actual strings all occupy an ASN1_STRING
+ * structure. In this case the 'utype' field
+ * has a special meaning, it is used as a mask
+ * of acceptable types using the B_ASN1 constants.
+ *
+ * NDEF_SEQUENCE is the same as SEQUENCE except
+ * that it will use indefinite length constructed
+ * encoding if requested.
+ *
+ */
+
+# define ASN1_ITYPE_PRIMITIVE 0x0
+# define ASN1_ITYPE_SEQUENCE 0x1
+# define ASN1_ITYPE_CHOICE 0x2
+/* unused value 0x3 */
+# define ASN1_ITYPE_EXTERN 0x4
+# define ASN1_ITYPE_MSTRING 0x5
+# define ASN1_ITYPE_NDEF_SEQUENCE 0x6
+
+/* Macro to obtain ASN1_ADB pointer from a type (only used internally) */
+# define ASN1_ADB_ptr(iptr) ((const ASN1_ADB *)((iptr)()))
+
+/* Macros for start and end of ASN1_ITEM definition */
+
+# define ASN1_ITEM_start(itname) \
+ const ASN1_ITEM * itname##_it(void) \
+ { \
+ static const ASN1_ITEM local_it = {
+
+# define static_ASN1_ITEM_start(itname) \
+ static ASN1_ITEM_start(itname)
+
+# define ASN1_ITEM_end(itname) \
+ }; \
+ return &local_it; \
+ }
+
+/* Macros to aid ASN1 template writing */
+
+# define ASN1_ITEM_TEMPLATE(tname) \
+ static const ASN1_TEMPLATE tname##_item_tt
+
+# define ASN1_ITEM_TEMPLATE_END(tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_PRIMITIVE,\
+ -1,\
+ &tname##_item_tt,\
+ 0,\
+ NULL,\
+ 0,\
+ #tname \
+ ASN1_ITEM_end(tname)
+# define static_ASN1_ITEM_TEMPLATE_END(tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_PRIMITIVE,\
+ -1,\
+ &tname##_item_tt,\
+ 0,\
+ NULL,\
+ 0,\
+ #tname \
+ ASN1_ITEM_end(tname)
+
+/* This is a ASN1 type which just embeds a template */
+
+/*-
+ * This pair helps declare a SEQUENCE. We can do:
+ *
+ * ASN1_SEQUENCE(stname) = {
+ * ... SEQUENCE components ...
+ * } ASN1_SEQUENCE_END(stname)
+ *
+ * This will produce an ASN1_ITEM called stname_it
+ * for a structure called stname.
+ *
+ * If you want the same structure but a different
+ * name then use:
+ *
+ * ASN1_SEQUENCE(itname) = {
+ * ... SEQUENCE components ...
+ * } ASN1_SEQUENCE_END_name(stname, itname)
+ *
+ * This will create an item called itname_it using
+ * a structure called stname.
+ */
+
+# define ASN1_SEQUENCE(tname) \
+ static const ASN1_TEMPLATE tname##_seq_tt[]
+
+# define ASN1_SEQUENCE_END(stname) ASN1_SEQUENCE_END_name(stname, stname)
+
+# define static_ASN1_SEQUENCE_END(stname) static_ASN1_SEQUENCE_END_name(stname, stname)
+
+# define ASN1_SEQUENCE_END_name(stname, tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+
+# define static_ASN1_SEQUENCE_END_name(stname, tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define ASN1_NDEF_SEQUENCE(tname) \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_NDEF_SEQUENCE_cb(tname, cb) \
+ ASN1_SEQUENCE_cb(tname, cb)
+
+# define ASN1_SEQUENCE_cb(tname, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0, NULL}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_const_cb(tname, const_cb) \
+ static const ASN1_AUX tname##_aux = \
+ {NULL, ASN1_AFLG_CONST_CB, 0, 0, NULL, 0, const_cb}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_cb_const_cb(tname, cb, const_cb) \
+ static const ASN1_AUX tname##_aux = \
+ {NULL, ASN1_AFLG_CONST_CB, 0, 0, cb, 0, const_cb}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_ref(tname, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_REFCOUNT, offsetof(tname, references), offsetof(tname, lock), cb, 0, NULL}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_SEQUENCE_enc(tname, enc, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, ASN1_AFLG_ENCODING, 0, 0, cb, offsetof(tname, enc), NULL}; \
+ ASN1_SEQUENCE(tname)
+
+# define ASN1_NDEF_SEQUENCE_END(tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_NDEF_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(tname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+# define static_ASN1_NDEF_SEQUENCE_END(tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_NDEF_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(tname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+
+
+# define ASN1_SEQUENCE_END_enc(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
+
+# define ASN1_SEQUENCE_END_cb(stname, tname) ASN1_SEQUENCE_END_ref(stname, tname)
+# define static_ASN1_SEQUENCE_END_cb(stname, tname) static_ASN1_SEQUENCE_END_ref(stname, tname)
+
+# define ASN1_SEQUENCE_END_ref(stname, tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #tname \
+ ASN1_ITEM_end(tname)
+# define static_ASN1_SEQUENCE_END_ref(stname, tname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define ASN1_NDEF_SEQUENCE_END_cb(stname, tname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_NDEF_SEQUENCE,\
+ V_ASN1_SEQUENCE,\
+ tname##_seq_tt,\
+ sizeof(tname##_seq_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+/*-
+ * This pair helps declare a CHOICE type. We can do:
+ *
+ * ASN1_CHOICE(chname) = {
+ * ... CHOICE options ...
+ * ASN1_CHOICE_END(chname)
+ *
+ * This will produce an ASN1_ITEM called chname_it
+ * for a structure called chname. The structure
+ * definition must look like this:
+ * typedef struct {
+ * int type;
+ * union {
+ * ASN1_SOMETHING *opt1;
+ * ASN1_SOMEOTHER *opt2;
+ * } value;
+ * } chname;
+ *
+ * the name of the selector must be 'type'.
+ * to use an alternative selector name use the
+ * ASN1_CHOICE_END_selector() version.
+ */
+
+# define ASN1_CHOICE(tname) \
+ static const ASN1_TEMPLATE tname##_ch_tt[]
+
+# define ASN1_CHOICE_cb(tname, cb) \
+ static const ASN1_AUX tname##_aux = {NULL, 0, 0, 0, cb, 0, NULL}; \
+ ASN1_CHOICE(tname)
+
+# define ASN1_CHOICE_END(stname) ASN1_CHOICE_END_name(stname, stname)
+
+# define static_ASN1_CHOICE_END(stname) static_ASN1_CHOICE_END_name(stname, stname)
+
+# define ASN1_CHOICE_END_name(stname, tname) ASN1_CHOICE_END_selector(stname, tname, type)
+
+# define static_ASN1_CHOICE_END_name(stname, tname) static_ASN1_CHOICE_END_selector(stname, tname, type)
+
+# define ASN1_CHOICE_END_selector(stname, tname, selname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_CHOICE,\
+ offsetof(stname,selname) ,\
+ tname##_ch_tt,\
+ sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define static_ASN1_CHOICE_END_selector(stname, tname, selname) \
+ ;\
+ static_ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_CHOICE,\
+ offsetof(stname,selname) ,\
+ tname##_ch_tt,\
+ sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
+ NULL,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+# define ASN1_CHOICE_END_cb(stname, tname, selname) \
+ ;\
+ ASN1_ITEM_start(tname) \
+ ASN1_ITYPE_CHOICE,\
+ offsetof(stname,selname) ,\
+ tname##_ch_tt,\
+ sizeof(tname##_ch_tt) / sizeof(ASN1_TEMPLATE),\
+ &tname##_aux,\
+ sizeof(stname),\
+ #stname \
+ ASN1_ITEM_end(tname)
+
+/* This helps with the template wrapper form of ASN1_ITEM */
+
+# define ASN1_EX_TEMPLATE_TYPE(flags, tag, name, type) { \
+ (flags), (tag), 0,\
+ #name, ASN1_ITEM_ref(type) }
+
+/* These help with SEQUENCE or CHOICE components */
+
+/* used to declare other types */
+
+# define ASN1_EX_TYPE(flags, tag, stname, field, type) { \
+ (flags), (tag), offsetof(stname, field),\
+ #field, ASN1_ITEM_ref(type) }
+
+/* implicit and explicit helper macros */
+
+# define ASN1_IMP_EX(stname, field, type, tag, ex) \
+ ASN1_EX_TYPE(ASN1_TFLG_IMPLICIT | (ex), tag, stname, field, type)
+
+# define ASN1_EXP_EX(stname, field, type, tag, ex) \
+ ASN1_EX_TYPE(ASN1_TFLG_EXPLICIT | (ex), tag, stname, field, type)
+
+/* Any defined by macros: the field used is in the table itself */
+
+# define ASN1_ADB_OBJECT(tblname) { ASN1_TFLG_ADB_OID, -1, 0, #tblname, tblname##_adb }
+# define ASN1_ADB_INTEGER(tblname) { ASN1_TFLG_ADB_INT, -1, 0, #tblname, tblname##_adb }
+
+/* Plain simple type */
+# define ASN1_SIMPLE(stname, field, type) ASN1_EX_TYPE(0,0, stname, field, type)
+/* Embedded simple type */
+# define ASN1_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_EMBED,0, stname, field, type)
+
+/* OPTIONAL simple type */
+# define ASN1_OPT(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL, 0, stname, field, type)
+# define ASN1_OPT_EMBED(stname, field, type) ASN1_EX_TYPE(ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED, 0, stname, field, type)
+
+/* IMPLICIT tagged simple type */
+# define ASN1_IMP(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, 0)
+# define ASN1_IMP_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
+
+/* IMPLICIT tagged OPTIONAL simple type */
+# define ASN1_IMP_OPT(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
+# define ASN1_IMP_OPT_EMBED(stname, field, type, tag) ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
+
+/* Same as above but EXPLICIT */
+
+# define ASN1_EXP(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, 0)
+# define ASN1_EXP_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_EMBED)
+# define ASN1_EXP_OPT(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL)
+# define ASN1_EXP_OPT_EMBED(stname, field, type, tag) ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_EMBED)
+
+/* SEQUENCE OF type */
+# define ASN1_SEQUENCE_OF(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF, 0, stname, field, type)
+
+/* OPTIONAL SEQUENCE OF */
+# define ASN1_SEQUENCE_OF_OPT(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
+
+/* Same as above but for SET OF */
+
+# define ASN1_SET_OF(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SET_OF, 0, stname, field, type)
+
+# define ASN1_SET_OF_OPT(stname, field, type) \
+ ASN1_EX_TYPE(ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL, 0, stname, field, type)
+
+/* Finally compound types of SEQUENCE, SET, IMPLICIT, EXPLICIT and OPTIONAL */
+
+# define ASN1_IMP_SET_OF(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
+
+# define ASN1_EXP_SET_OF(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF)
+
+# define ASN1_IMP_SET_OF_OPT(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
+
+# define ASN1_EXP_SET_OF_OPT(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SET_OF|ASN1_TFLG_OPTIONAL)
+
+# define ASN1_IMP_SEQUENCE_OF(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
+
+# define ASN1_IMP_SEQUENCE_OF_OPT(stname, field, type, tag) \
+ ASN1_IMP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
+
+# define ASN1_EXP_SEQUENCE_OF(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF)
+
+# define ASN1_EXP_SEQUENCE_OF_OPT(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_SEQUENCE_OF|ASN1_TFLG_OPTIONAL)
+
+/* EXPLICIT using indefinite length constructed form */
+# define ASN1_NDEF_EXP(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_NDEF)
+
+/* EXPLICIT OPTIONAL using indefinite length constructed form */
+# define ASN1_NDEF_EXP_OPT(stname, field, type, tag) \
+ ASN1_EXP_EX(stname, field, type, tag, ASN1_TFLG_OPTIONAL|ASN1_TFLG_NDEF)
+
+/* Macros for the ASN1_ADB structure */
+
+# define ASN1_ADB(name) \
+ static const ASN1_ADB_TABLE name##_adbtbl[]
+
+# define ASN1_ADB_END(name, flags, field, adb_cb, def, none) \
+ ;\
+ static const ASN1_ITEM *name##_adb(void) \
+ { \
+ static const ASN1_ADB internal_adb = \
+ {\
+ flags,\
+ offsetof(name, field),\
+ adb_cb,\
+ name##_adbtbl,\
+ sizeof(name##_adbtbl) / sizeof(ASN1_ADB_TABLE),\
+ def,\
+ none\
+ }; \
+ return (const ASN1_ITEM *) &internal_adb; \
+ } \
+ void dummy_function(void)
+
+# define ADB_ENTRY(val, template) {val, template}
+
+# define ASN1_ADB_TEMPLATE(name) \
+ static const ASN1_TEMPLATE name##_tt
+
+/*
+ * This is the ASN1 template structure that defines a wrapper round the
+ * actual type. It determines the actual position of the field in the value
+ * structure, various flags such as OPTIONAL and the field name.
+ */
+
+struct ASN1_TEMPLATE_st {
+ unsigned long flags; /* Various flags */
+ long tag; /* tag, not used if no tagging */
+ unsigned long offset; /* Offset of this field in structure */
+ const char *field_name; /* Field name */
+ ASN1_ITEM_EXP *item; /* Relevant ASN1_ITEM or ASN1_ADB */
+};
+
+/* Macro to extract ASN1_ITEM and ASN1_ADB pointer from ASN1_TEMPLATE */
+
+# define ASN1_TEMPLATE_item(t) (t->item_ptr)
+# define ASN1_TEMPLATE_adb(t) (t->item_ptr)
+
+typedef struct ASN1_ADB_TABLE_st ASN1_ADB_TABLE;
+typedef struct ASN1_ADB_st ASN1_ADB;
+
+struct ASN1_ADB_st {
+ unsigned long flags; /* Various flags */
+ unsigned long offset; /* Offset of selector field */
+ int (*adb_cb)(long *psel); /* Application callback */
+ const ASN1_ADB_TABLE *tbl; /* Table of possible types */
+ long tblcount; /* Number of entries in tbl */
+ const ASN1_TEMPLATE *default_tt; /* Type to use if no match */
+ const ASN1_TEMPLATE *null_tt; /* Type to use if selector is NULL */
+};
+
+struct ASN1_ADB_TABLE_st {
+ long value; /* NID for an object or value for an int */
+ const ASN1_TEMPLATE tt; /* item for this value */
+};
+
+/* template flags */
+
+/* Field is optional */
+# define ASN1_TFLG_OPTIONAL (0x1)
+
+/* Field is a SET OF */
+# define ASN1_TFLG_SET_OF (0x1 << 1)
+
+/* Field is a SEQUENCE OF */
+# define ASN1_TFLG_SEQUENCE_OF (0x2 << 1)
+
+/*
+ * Special case: this refers to a SET OF that will be sorted into DER order
+ * when encoded *and* the corresponding STACK will be modified to match the
+ * new order.
+ */
+# define ASN1_TFLG_SET_ORDER (0x3 << 1)
+
+/* Mask for SET OF or SEQUENCE OF */
+# define ASN1_TFLG_SK_MASK (0x3 << 1)
+
+/*
+ * These flags mean the tag should be taken from the tag field. If EXPLICIT
+ * then the underlying type is used for the inner tag.
+ */
+
+/* IMPLICIT tagging */
+# define ASN1_TFLG_IMPTAG (0x1 << 3)
+
+/* EXPLICIT tagging, inner tag from underlying type */
+# define ASN1_TFLG_EXPTAG (0x2 << 3)
+
+# define ASN1_TFLG_TAG_MASK (0x3 << 3)
+
+/* context specific IMPLICIT */
+# define ASN1_TFLG_IMPLICIT (ASN1_TFLG_IMPTAG|ASN1_TFLG_CONTEXT)
+
+/* context specific EXPLICIT */
+# define ASN1_TFLG_EXPLICIT (ASN1_TFLG_EXPTAG|ASN1_TFLG_CONTEXT)
+
+/*
+ * If tagging is in force these determine the type of tag to use. Otherwise
+ * the tag is determined by the underlying type. These values reflect the
+ * actual octet format.
+ */
+
+/* Universal tag */
+# define ASN1_TFLG_UNIVERSAL (0x0<<6)
+/* Application tag */
+# define ASN1_TFLG_APPLICATION (0x1<<6)
+/* Context specific tag */
+# define ASN1_TFLG_CONTEXT (0x2<<6)
+/* Private tag */
+# define ASN1_TFLG_PRIVATE (0x3<<6)
+
+# define ASN1_TFLG_TAG_CLASS (0x3<<6)
+
+/*
+ * These are for ANY DEFINED BY type. In this case the 'item' field points to
+ * an ASN1_ADB structure which contains a table of values to decode the
+ * relevant type
+ */
+
+# define ASN1_TFLG_ADB_MASK (0x3<<8)
+
+# define ASN1_TFLG_ADB_OID (0x1<<8)
+
+# define ASN1_TFLG_ADB_INT (0x1<<9)
+
+/*
+ * This flag when present in a SEQUENCE OF, SET OF or EXPLICIT causes
+ * indefinite length constructed encoding to be used if required.
+ */
+
+# define ASN1_TFLG_NDEF (0x1<<11)
+
+/* Field is embedded and not a pointer */
+# define ASN1_TFLG_EMBED (0x1 << 12)
+
+/* This is the actual ASN1 item itself */
+
+struct ASN1_ITEM_st {
+ char itype; /* The item type, primitive, SEQUENCE, CHOICE
+ * or extern */
+ long utype; /* underlying type */
+ const ASN1_TEMPLATE *templates; /* If SEQUENCE or CHOICE this contains
+ * the contents */
+ long tcount; /* Number of templates if SEQUENCE or CHOICE */
+ const void *funcs; /* further data and type-specific functions */
+ /* funcs can be ASN1_PRIMITIVE_FUNCS*, ASN1_EXTERN_FUNCS*, or ASN1_AUX* */
+ long size; /* Structure size (usually) */
+ const char *sname; /* Structure name */
+};
+
+/*
+ * Cache for ASN1 tag and length, so we don't keep re-reading it for things
+ * like CHOICE
+ */
+
+struct ASN1_TLC_st {
+ char valid; /* Values below are valid */
+ int ret; /* return value */
+ long plen; /* length */
+ int ptag; /* class value */
+ int pclass; /* class value */
+ int hdrlen; /* header length */
+};
+
+/* Typedefs for ASN1 function pointers */
+typedef int ASN1_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
+ const ASN1_ITEM *it, int tag, int aclass, char opt,
+ ASN1_TLC *ctx);
+
+typedef int ASN1_ex_d2i_ex(ASN1_VALUE **pval, const unsigned char **in, long len,
+ const ASN1_ITEM *it, int tag, int aclass, char opt,
+ ASN1_TLC *ctx, OSSL_LIB_CTX *libctx,
+ const char *propq);
+typedef int ASN1_ex_i2d(const ASN1_VALUE **pval, unsigned char **out,
+ const ASN1_ITEM *it, int tag, int aclass);
+typedef int ASN1_ex_new_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
+typedef int ASN1_ex_new_ex_func(ASN1_VALUE **pval, const ASN1_ITEM *it,
+ OSSL_LIB_CTX *libctx, const char *propq);
+typedef void ASN1_ex_free_func(ASN1_VALUE **pval, const ASN1_ITEM *it);
+
+typedef int ASN1_ex_print_func(BIO *out, const ASN1_VALUE **pval,
+ int indent, const char *fname,
+ const ASN1_PCTX *pctx);
+
+typedef int ASN1_primitive_i2c(const ASN1_VALUE **pval, unsigned char *cont,
+ int *putype, const ASN1_ITEM *it);
+typedef int ASN1_primitive_c2i(ASN1_VALUE **pval, const unsigned char *cont,
+ int len, int utype, char *free_cont,
+ const ASN1_ITEM *it);
+typedef int ASN1_primitive_print(BIO *out, const ASN1_VALUE **pval,
+ const ASN1_ITEM *it, int indent,
+ const ASN1_PCTX *pctx);
+
+typedef struct ASN1_EXTERN_FUNCS_st {
+ void *app_data;
+ ASN1_ex_new_func *asn1_ex_new;
+ ASN1_ex_free_func *asn1_ex_free;
+ ASN1_ex_free_func *asn1_ex_clear;
+ ASN1_ex_d2i *asn1_ex_d2i;
+ ASN1_ex_i2d *asn1_ex_i2d;
+ ASN1_ex_print_func *asn1_ex_print;
+ ASN1_ex_new_ex_func *asn1_ex_new_ex;
+ ASN1_ex_d2i_ex *asn1_ex_d2i_ex;
+} ASN1_EXTERN_FUNCS;
+
+typedef struct ASN1_PRIMITIVE_FUNCS_st {
+ void *app_data;
+ unsigned long flags;
+ ASN1_ex_new_func *prim_new;
+ ASN1_ex_free_func *prim_free;
+ ASN1_ex_free_func *prim_clear;
+ ASN1_primitive_c2i *prim_c2i;
+ ASN1_primitive_i2c *prim_i2c;
+ ASN1_primitive_print *prim_print;
+} ASN1_PRIMITIVE_FUNCS;
+
+/*
+ * This is the ASN1_AUX structure: it handles various miscellaneous
+ * requirements. For example the use of reference counts and an informational
+ * callback. The "informational callback" is called at various points during
+ * the ASN1 encoding and decoding. It can be used to provide minor
+ * customisation of the structures used. This is most useful where the
+ * supplied routines *almost* do the right thing but need some extra help at
+ * a few points. If the callback returns zero then it is assumed a fatal
+ * error has occurred and the main operation should be abandoned. If major
+ * changes in the default behaviour are required then an external type is
+ * more appropriate.
+ * For the operations ASN1_OP_I2D_PRE, ASN1_OP_I2D_POST, ASN1_OP_PRINT_PRE, and
+ * ASN1_OP_PRINT_POST, meanwhile a variant of the callback with const parameter
+ * 'in' is provided to make clear statically that its input is not modified. If
+ * and only if this variant is in use the flag ASN1_AFLG_CONST_CB must be set.
+ */
+
+typedef int ASN1_aux_cb(int operation, ASN1_VALUE **in, const ASN1_ITEM *it,
+ void *exarg);
+typedef int ASN1_aux_const_cb(int operation, const ASN1_VALUE **in,
+ const ASN1_ITEM *it, void *exarg);
+
+typedef struct ASN1_AUX_st {
+ void *app_data;
+ int flags;
+ int ref_offset; /* Offset of reference value */
+ int ref_lock; /* Offset of lock value */
+ ASN1_aux_cb *asn1_cb;
+ int enc_offset; /* Offset of ASN1_ENCODING structure */
+ ASN1_aux_const_cb *asn1_const_cb; /* for ASN1_OP_I2D_ and ASN1_OP_PRINT_ */
+} ASN1_AUX;
+
+/* For print related callbacks exarg points to this structure */
+typedef struct ASN1_PRINT_ARG_st {
+ BIO *out;
+ int indent;
+ const ASN1_PCTX *pctx;
+} ASN1_PRINT_ARG;
+
+/* For streaming related callbacks exarg points to this structure */
+typedef struct ASN1_STREAM_ARG_st {
+ /* BIO to stream through */
+ BIO *out;
+ /* BIO with filters appended */
+ BIO *ndef_bio;
+ /* Streaming I/O boundary */
+ unsigned char **boundary;
+} ASN1_STREAM_ARG;
+
+/* Flags in ASN1_AUX */
+
+/* Use a reference count */
+# define ASN1_AFLG_REFCOUNT 1
+/* Save the encoding of structure (useful for signatures) */
+# define ASN1_AFLG_ENCODING 2
+/* The Sequence length is invalid */
+# define ASN1_AFLG_BROKEN 4
+/* Use the new asn1_const_cb */
+# define ASN1_AFLG_CONST_CB 8
+
+/* operation values for asn1_cb */
+
+# define ASN1_OP_NEW_PRE 0
+# define ASN1_OP_NEW_POST 1
+# define ASN1_OP_FREE_PRE 2
+# define ASN1_OP_FREE_POST 3
+# define ASN1_OP_D2I_PRE 4
+# define ASN1_OP_D2I_POST 5
+# define ASN1_OP_I2D_PRE 6
+# define ASN1_OP_I2D_POST 7
+# define ASN1_OP_PRINT_PRE 8
+# define ASN1_OP_PRINT_POST 9
+# define ASN1_OP_STREAM_PRE 10
+# define ASN1_OP_STREAM_POST 11
+# define ASN1_OP_DETACHED_PRE 12
+# define ASN1_OP_DETACHED_POST 13
+# define ASN1_OP_DUP_PRE 14
+# define ASN1_OP_DUP_POST 15
+# define ASN1_OP_GET0_LIBCTX 16
+# define ASN1_OP_GET0_PROPQ 17
+
+/* Macro to implement a primitive type */
+# define IMPLEMENT_ASN1_TYPE(stname) IMPLEMENT_ASN1_TYPE_ex(stname, stname, 0)
+# define IMPLEMENT_ASN1_TYPE_ex(itname, vname, ex) \
+ ASN1_ITEM_start(itname) \
+ ASN1_ITYPE_PRIMITIVE, V_##vname, NULL, 0, NULL, ex, #itname \
+ ASN1_ITEM_end(itname)
+
+/* Macro to implement a multi string type */
+# define IMPLEMENT_ASN1_MSTRING(itname, mask) \
+ ASN1_ITEM_start(itname) \
+ ASN1_ITYPE_MSTRING, mask, NULL, 0, NULL, sizeof(ASN1_STRING), #itname \
+ ASN1_ITEM_end(itname)
+
+# define IMPLEMENT_EXTERN_ASN1(sname, tag, fptrs) \
+ ASN1_ITEM_start(sname) \
+ ASN1_ITYPE_EXTERN, \
+ tag, \
+ NULL, \
+ 0, \
+ &fptrs, \
+ 0, \
+ #sname \
+ ASN1_ITEM_end(sname)
+
+/* Macro to implement standard functions in terms of ASN1_ITEM structures */
+
+# define IMPLEMENT_ASN1_FUNCTIONS(stname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, stname, stname)
+
+# define IMPLEMENT_ASN1_FUNCTIONS_name(stname, itname) IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, itname)
+
+# define IMPLEMENT_ASN1_FUNCTIONS_ENCODE_name(stname, itname) \
+ IMPLEMENT_ASN1_FUNCTIONS_ENCODE_fname(stname, itname, itname)
+
+# define IMPLEMENT_STATIC_ASN1_ALLOC_FUNCTIONS(stname) \
+ IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(static, stname, stname, stname)
+
+# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS(stname) \
+ IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, stname, stname)
+
+# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_pfname(pre, stname, itname, fname) \
+ pre stname *fname##_new(void) \
+ { \
+ return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
+ } \
+ pre void fname##_free(stname *a) \
+ { \
+ ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
+ }
+
+# define IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname) \
+ stname *fname##_new(void) \
+ { \
+ return (stname *)ASN1_item_new(ASN1_ITEM_rptr(itname)); \
+ } \
+ void fname##_free(stname *a) \
+ { \
+ ASN1_item_free((ASN1_VALUE *)a, ASN1_ITEM_rptr(itname)); \
+ }
+
+# define IMPLEMENT_ASN1_FUNCTIONS_fname(stname, itname, fname) \
+ IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
+ IMPLEMENT_ASN1_ALLOC_FUNCTIONS_fname(stname, itname, fname)
+
+# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname) \
+ stname *d2i_##fname(stname **a, const unsigned char **in, long len) \
+ { \
+ return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, ASN1_ITEM_rptr(itname));\
+ } \
+ int i2d_##fname(const stname *a, unsigned char **out) \
+ { \
+ return ASN1_item_i2d((const ASN1_VALUE *)a, out, ASN1_ITEM_rptr(itname));\
+ }
+
+# define IMPLEMENT_ASN1_NDEF_FUNCTION(stname) \
+ int i2d_##stname##_NDEF(const stname *a, unsigned char **out) \
+ { \
+ return ASN1_item_ndef_i2d((const ASN1_VALUE *)a, out, ASN1_ITEM_rptr(stname));\
+ }
+
+# define IMPLEMENT_STATIC_ASN1_ENCODE_FUNCTIONS(stname) \
+ static stname *d2i_##stname(stname **a, \
+ const unsigned char **in, long len) \
+ { \
+ return (stname *)ASN1_item_d2i((ASN1_VALUE **)a, in, len, \
+ ASN1_ITEM_rptr(stname)); \
+ } \
+ static int i2d_##stname(const stname *a, unsigned char **out) \
+ { \
+ return ASN1_item_i2d((const ASN1_VALUE *)a, out, \
+ ASN1_ITEM_rptr(stname)); \
+ }
+
+# define IMPLEMENT_ASN1_DUP_FUNCTION(stname) \
+ stname * stname##_dup(const stname *x) \
+ { \
+ return ASN1_item_dup(ASN1_ITEM_rptr(stname), x); \
+ }
+
+# define IMPLEMENT_ASN1_PRINT_FUNCTION(stname) \
+ IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, stname, stname)
+
+# define IMPLEMENT_ASN1_PRINT_FUNCTION_fname(stname, itname, fname) \
+ int fname##_print_ctx(BIO *out, const stname *x, int indent, \
+ const ASN1_PCTX *pctx) \
+ { \
+ return ASN1_item_print(out, (const ASN1_VALUE *)x, indent, \
+ ASN1_ITEM_rptr(itname), pctx); \
+ }
+
+/* external definitions for primitive types */
+
+DECLARE_ASN1_ITEM(ASN1_BOOLEAN)
+DECLARE_ASN1_ITEM(ASN1_TBOOLEAN)
+DECLARE_ASN1_ITEM(ASN1_FBOOLEAN)
+DECLARE_ASN1_ITEM(ASN1_SEQUENCE)
+DECLARE_ASN1_ITEM(CBIGNUM)
+DECLARE_ASN1_ITEM(BIGNUM)
+DECLARE_ASN1_ITEM(INT32)
+DECLARE_ASN1_ITEM(ZINT32)
+DECLARE_ASN1_ITEM(UINT32)
+DECLARE_ASN1_ITEM(ZUINT32)
+DECLARE_ASN1_ITEM(INT64)
+DECLARE_ASN1_ITEM(ZINT64)
+DECLARE_ASN1_ITEM(UINT64)
+DECLARE_ASN1_ITEM(ZUINT64)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/*
+ * LONG and ZLONG are strongly discouraged for use as stored data, as the
+ * underlying C type (long) differs in size depending on the architecture.
+ * They are designed with 32-bit longs in mind.
+ */
+DECLARE_ASN1_ITEM(LONG)
+DECLARE_ASN1_ITEM(ZLONG)
+# endif
+
+{-
+ generate_stack_macros("ASN1_VALUE");
+-}
+
+
+/* Functions used internally by the ASN1 code */
+
+int ASN1_item_ex_new(ASN1_VALUE **pval, const ASN1_ITEM *it);
+void ASN1_item_ex_free(ASN1_VALUE **pval, const ASN1_ITEM *it);
+
+int ASN1_item_ex_d2i(ASN1_VALUE **pval, const unsigned char **in, long len,
+ const ASN1_ITEM *it, int tag, int aclass, char opt,
+ ASN1_TLC *ctx);
+
+int ASN1_item_ex_i2d(const ASN1_VALUE **pval, unsigned char **out,
+ const ASN1_ITEM *it, int tag, int aclass);
+
+/* Legacy compatibility */
+# define IMPLEMENT_ASN1_FUNCTIONS_const(name) IMPLEMENT_ASN1_FUNCTIONS(name)
+# define IMPLEMENT_ASN1_ENCODE_FUNCTIONS_const_fname(stname, itname, fname) \
+ IMPLEMENT_ASN1_ENCODE_FUNCTIONS_fname(stname, itname, fname)
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/async.h b/include/openssl/async.h
new file mode 100644
index 00000000..bc27d5db
--- /dev/null
+++ b/include/openssl/async.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <stdlib.h>
+
+#ifndef OPENSSL_ASYNC_H
+# define OPENSSL_ASYNC_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ASYNC_H
+# endif
+
+#if defined(_WIN32)
+# if defined(BASETYPES) || defined(_WINDEF_H)
+/* application has to include <windows.h> to use this */
+#define OSSL_ASYNC_FD HANDLE
+#define OSSL_BAD_ASYNC_FD INVALID_HANDLE_VALUE
+# endif
+#else
+#define OSSL_ASYNC_FD int
+#define OSSL_BAD_ASYNC_FD -1
+#endif
+# include <openssl/asyncerr.h>
+
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+typedef struct async_job_st ASYNC_JOB;
+typedef struct async_wait_ctx_st ASYNC_WAIT_CTX;
+typedef int (*ASYNC_callback_fn)(void *arg);
+
+#define ASYNC_ERR 0
+#define ASYNC_NO_JOBS 1
+#define ASYNC_PAUSE 2
+#define ASYNC_FINISH 3
+
+#define ASYNC_STATUS_UNSUPPORTED 0
+#define ASYNC_STATUS_ERR 1
+#define ASYNC_STATUS_OK 2
+#define ASYNC_STATUS_EAGAIN 3
+
+int ASYNC_init_thread(size_t max_size, size_t init_size);
+void ASYNC_cleanup_thread(void);
+
+#ifdef OSSL_ASYNC_FD
+ASYNC_WAIT_CTX *ASYNC_WAIT_CTX_new(void);
+void ASYNC_WAIT_CTX_free(ASYNC_WAIT_CTX *ctx);
+int ASYNC_WAIT_CTX_set_wait_fd(ASYNC_WAIT_CTX *ctx, const void *key,
+ OSSL_ASYNC_FD fd,
+ void *custom_data,
+ void (*cleanup)(ASYNC_WAIT_CTX *, const void *,
+ OSSL_ASYNC_FD, void *));
+int ASYNC_WAIT_CTX_get_fd(ASYNC_WAIT_CTX *ctx, const void *key,
+ OSSL_ASYNC_FD *fd, void **custom_data);
+int ASYNC_WAIT_CTX_get_all_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *fd,
+ size_t *numfds);
+int ASYNC_WAIT_CTX_get_callback(ASYNC_WAIT_CTX *ctx,
+ ASYNC_callback_fn *callback,
+ void **callback_arg);
+int ASYNC_WAIT_CTX_set_callback(ASYNC_WAIT_CTX *ctx,
+ ASYNC_callback_fn callback,
+ void *callback_arg);
+int ASYNC_WAIT_CTX_set_status(ASYNC_WAIT_CTX *ctx, int status);
+int ASYNC_WAIT_CTX_get_status(ASYNC_WAIT_CTX *ctx);
+int ASYNC_WAIT_CTX_get_changed_fds(ASYNC_WAIT_CTX *ctx, OSSL_ASYNC_FD *addfd,
+ size_t *numaddfds, OSSL_ASYNC_FD *delfd,
+ size_t *numdelfds);
+int ASYNC_WAIT_CTX_clear_fd(ASYNC_WAIT_CTX *ctx, const void *key);
+#endif
+
+int ASYNC_is_capable(void);
+
+int ASYNC_start_job(ASYNC_JOB **job, ASYNC_WAIT_CTX *ctx, int *ret,
+ int (*func)(void *), void *args, size_t size);
+int ASYNC_pause_job(void);
+
+ASYNC_JOB *ASYNC_get_current_job(void);
+ASYNC_WAIT_CTX *ASYNC_get_wait_ctx(ASYNC_JOB *job);
+void ASYNC_block_pause(void);
+void ASYNC_unblock_pause(void);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/asyncerr.h b/include/openssl/asyncerr.h
new file mode 100644
index 00000000..c093f7be
--- /dev/null
+++ b/include/openssl/asyncerr.h
@@ -0,0 +1,29 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ASYNCERR_H
+# define OPENSSL_ASYNCERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * ASYNC reason codes.
+ */
+# define ASYNC_R_FAILED_TO_SET_POOL 101
+# define ASYNC_R_FAILED_TO_SWAP_CONTEXT 102
+# define ASYNC_R_INIT_FAILED 105
+# define ASYNC_R_INVALID_POOL_SIZE 103
+
+#endif
diff --git a/include/openssl/bio.h b/include/openssl/bio.h
new file mode 100644
index 00000000..3ef0cafb
--- /dev/null
+++ b/include/openssl/bio.h
@@ -0,0 +1,884 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\bio.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+#ifndef OPENSSL_BIO_H
+# define OPENSSL_BIO_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_BIO_H
+# endif
+
+# include <openssl/e_os2.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+# include <stdarg.h>
+
+# include <openssl/crypto.h>
+# include <openssl/bioerr.h>
+# include <openssl/core.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* There are the classes of BIOs */
+# define BIO_TYPE_DESCRIPTOR 0x0100 /* socket, fd, connect or accept */
+# define BIO_TYPE_FILTER 0x0200
+# define BIO_TYPE_SOURCE_SINK 0x0400
+
+/* These are the 'types' of BIOs */
+# define BIO_TYPE_NONE 0
+# define BIO_TYPE_MEM ( 1|BIO_TYPE_SOURCE_SINK)
+# define BIO_TYPE_FILE ( 2|BIO_TYPE_SOURCE_SINK)
+
+# define BIO_TYPE_FD ( 4|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_SOCKET ( 5|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_NULL ( 6|BIO_TYPE_SOURCE_SINK)
+# define BIO_TYPE_SSL ( 7|BIO_TYPE_FILTER)
+# define BIO_TYPE_MD ( 8|BIO_TYPE_FILTER)
+# define BIO_TYPE_BUFFER ( 9|BIO_TYPE_FILTER)
+# define BIO_TYPE_CIPHER (10|BIO_TYPE_FILTER)
+# define BIO_TYPE_BASE64 (11|BIO_TYPE_FILTER)
+# define BIO_TYPE_CONNECT (12|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_ACCEPT (13|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+
+# define BIO_TYPE_NBIO_TEST (16|BIO_TYPE_FILTER)/* server proxy BIO */
+# define BIO_TYPE_NULL_FILTER (17|BIO_TYPE_FILTER)
+# define BIO_TYPE_BIO (19|BIO_TYPE_SOURCE_SINK)/* half a BIO pair */
+# define BIO_TYPE_LINEBUFFER (20|BIO_TYPE_FILTER)
+# define BIO_TYPE_DGRAM (21|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_ASN1 (22|BIO_TYPE_FILTER)
+# define BIO_TYPE_COMP (23|BIO_TYPE_FILTER)
+# ifndef OPENSSL_NO_SCTP
+# define BIO_TYPE_DGRAM_SCTP (24|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# endif
+# define BIO_TYPE_CORE_TO_PROV (25|BIO_TYPE_SOURCE_SINK)
+
+#define BIO_TYPE_START 128
+
+/*
+ * BIO_FILENAME_READ|BIO_CLOSE to open or close on free.
+ * BIO_set_fp(in,stdin,BIO_NOCLOSE);
+ */
+# define BIO_NOCLOSE 0x00
+# define BIO_CLOSE 0x01
+
+/*
+ * These are used in the following macros and are passed to BIO_ctrl()
+ */
+# define BIO_CTRL_RESET 1/* opt - rewind/zero etc */
+# define BIO_CTRL_EOF 2/* opt - are we at the eof */
+# define BIO_CTRL_INFO 3/* opt - extra tit-bits */
+# define BIO_CTRL_SET 4/* man - set the 'IO' type */
+# define BIO_CTRL_GET 5/* man - get the 'IO' type */
+# define BIO_CTRL_PUSH 6/* opt - internal, used to signify change */
+# define BIO_CTRL_POP 7/* opt - internal, used to signify change */
+# define BIO_CTRL_GET_CLOSE 8/* man - set the 'close' on free */
+# define BIO_CTRL_SET_CLOSE 9/* man - set the 'close' on free */
+# define BIO_CTRL_PENDING 10/* opt - is their more data buffered */
+# define BIO_CTRL_FLUSH 11/* opt - 'flush' buffered output */
+# define BIO_CTRL_DUP 12/* man - extra stuff for 'duped' BIO */
+# define BIO_CTRL_WPENDING 13/* opt - number of bytes still to write */
+# define BIO_CTRL_SET_CALLBACK 14/* opt - set callback function */
+# define BIO_CTRL_GET_CALLBACK 15/* opt - set callback function */
+
+# define BIO_CTRL_PEEK 29/* BIO_f_buffer special */
+# define BIO_CTRL_SET_FILENAME 30/* BIO_s_file special */
+
+/* dgram BIO stuff */
+# define BIO_CTRL_DGRAM_CONNECT 31/* BIO dgram special */
+# define BIO_CTRL_DGRAM_SET_CONNECTED 32/* allow for an externally connected
+ * socket to be passed in */
+# define BIO_CTRL_DGRAM_SET_RECV_TIMEOUT 33/* setsockopt, essentially */
+# define BIO_CTRL_DGRAM_GET_RECV_TIMEOUT 34/* getsockopt, essentially */
+# define BIO_CTRL_DGRAM_SET_SEND_TIMEOUT 35/* setsockopt, essentially */
+# define BIO_CTRL_DGRAM_GET_SEND_TIMEOUT 36/* getsockopt, essentially */
+
+# define BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP 37/* flag whether the last */
+# define BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP 38/* I/O operation timed out */
+
+/* #ifdef IP_MTU_DISCOVER */
+# define BIO_CTRL_DGRAM_MTU_DISCOVER 39/* set DF bit on egress packets */
+/* #endif */
+
+# define BIO_CTRL_DGRAM_QUERY_MTU 40/* as kernel for current MTU */
+# define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47
+# define BIO_CTRL_DGRAM_GET_MTU 41/* get cached value for MTU */
+# define BIO_CTRL_DGRAM_SET_MTU 42/* set cached value for MTU.
+ * want to use this if asking
+ * the kernel fails */
+
+# define BIO_CTRL_DGRAM_MTU_EXCEEDED 43/* check whether the MTU was
+ * exceed in the previous write
+ * operation */
+
+# define BIO_CTRL_DGRAM_GET_PEER 46
+# define BIO_CTRL_DGRAM_SET_PEER 44/* Destination for the data */
+
+# define BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT 45/* Next DTLS handshake timeout
+ * to adjust socket timeouts */
+# define BIO_CTRL_DGRAM_SET_DONT_FRAG 48
+
+# define BIO_CTRL_DGRAM_GET_MTU_OVERHEAD 49
+
+/* Deliberately outside of OPENSSL_NO_SCTP - used in bss_dgram.c */
+# define BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE 50
+# ifndef OPENSSL_NO_SCTP
+/* SCTP stuff */
+# define BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY 51
+# define BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY 52
+# define BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD 53
+# define BIO_CTRL_DGRAM_SCTP_GET_SNDINFO 60
+# define BIO_CTRL_DGRAM_SCTP_SET_SNDINFO 61
+# define BIO_CTRL_DGRAM_SCTP_GET_RCVINFO 62
+# define BIO_CTRL_DGRAM_SCTP_SET_RCVINFO 63
+# define BIO_CTRL_DGRAM_SCTP_GET_PRINFO 64
+# define BIO_CTRL_DGRAM_SCTP_SET_PRINFO 65
+# define BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN 70
+# endif
+
+# define BIO_CTRL_DGRAM_SET_PEEK_MODE 71
+
+/*
+ * internal BIO:
+ * # define BIO_CTRL_SET_KTLS_SEND 72
+ * # define BIO_CTRL_SET_KTLS_SEND_CTRL_MSG 74
+ * # define BIO_CTRL_CLEAR_KTLS_CTRL_MSG 75
+ */
+
+# define BIO_CTRL_GET_KTLS_SEND 73
+# define BIO_CTRL_GET_KTLS_RECV 76
+
+# define BIO_CTRL_DGRAM_SCTP_WAIT_FOR_DRY 77
+# define BIO_CTRL_DGRAM_SCTP_MSG_WAITING 78
+
+/* BIO_f_prefix controls */
+# define BIO_CTRL_SET_PREFIX 79
+# define BIO_CTRL_SET_INDENT 80
+# define BIO_CTRL_GET_INDENT 81
+
+# ifndef OPENSSL_NO_KTLS
+# define BIO_get_ktls_send(b) \
+ BIO_ctrl(b, BIO_CTRL_GET_KTLS_SEND, 0, NULL)
+# define BIO_get_ktls_recv(b) \
+ BIO_ctrl(b, BIO_CTRL_GET_KTLS_RECV, 0, NULL)
+# else
+# define BIO_get_ktls_send(b) (0)
+# define BIO_get_ktls_recv(b) (0)
+# endif
+
+/* modifiers */
+# define BIO_FP_READ 0x02
+# define BIO_FP_WRITE 0x04
+# define BIO_FP_APPEND 0x08
+# define BIO_FP_TEXT 0x10
+
+# define BIO_FLAGS_READ 0x01
+# define BIO_FLAGS_WRITE 0x02
+# define BIO_FLAGS_IO_SPECIAL 0x04
+# define BIO_FLAGS_RWS (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL)
+# define BIO_FLAGS_SHOULD_RETRY 0x08
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* This #define was replaced by an internal constant and should not be used. */
+# define BIO_FLAGS_UPLINK 0
+# endif
+
+# define BIO_FLAGS_BASE64_NO_NL 0x100
+
+/*
+ * This is used with memory BIOs:
+ * BIO_FLAGS_MEM_RDONLY means we shouldn't free up or change the data in any way;
+ * BIO_FLAGS_NONCLEAR_RST means we shouldn't clear data on reset.
+ */
+# define BIO_FLAGS_MEM_RDONLY 0x200
+# define BIO_FLAGS_NONCLEAR_RST 0x400
+# define BIO_FLAGS_IN_EOF 0x800
+
+typedef union bio_addr_st BIO_ADDR;
+typedef struct bio_addrinfo_st BIO_ADDRINFO;
+
+int BIO_get_new_index(void);
+void BIO_set_flags(BIO *b, int flags);
+int BIO_test_flags(const BIO *b, int flags);
+void BIO_clear_flags(BIO *b, int flags);
+
+# define BIO_get_flags(b) BIO_test_flags(b, ~(0x0))
+# define BIO_set_retry_special(b) \
+ BIO_set_flags(b, (BIO_FLAGS_IO_SPECIAL|BIO_FLAGS_SHOULD_RETRY))
+# define BIO_set_retry_read(b) \
+ BIO_set_flags(b, (BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY))
+# define BIO_set_retry_write(b) \
+ BIO_set_flags(b, (BIO_FLAGS_WRITE|BIO_FLAGS_SHOULD_RETRY))
+
+/* These are normally used internally in BIOs */
+# define BIO_clear_retry_flags(b) \
+ BIO_clear_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
+# define BIO_get_retry_flags(b) \
+ BIO_test_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
+
+/* These should be used by the application to tell why we should retry */
+# define BIO_should_read(a) BIO_test_flags(a, BIO_FLAGS_READ)
+# define BIO_should_write(a) BIO_test_flags(a, BIO_FLAGS_WRITE)
+# define BIO_should_io_special(a) BIO_test_flags(a, BIO_FLAGS_IO_SPECIAL)
+# define BIO_retry_type(a) BIO_test_flags(a, BIO_FLAGS_RWS)
+# define BIO_should_retry(a) BIO_test_flags(a, BIO_FLAGS_SHOULD_RETRY)
+
+/*
+ * The next three are used in conjunction with the BIO_should_io_special()
+ * condition. After this returns true, BIO *BIO_get_retry_BIO(BIO *bio, int
+ * *reason); will walk the BIO stack and return the 'reason' for the special
+ * and the offending BIO. Given a BIO, BIO_get_retry_reason(bio) will return
+ * the code.
+ */
+/*
+ * Returned from the SSL bio when the certificate retrieval code had an error
+ */
+# define BIO_RR_SSL_X509_LOOKUP 0x01
+/* Returned from the connect BIO when a connect would have blocked */
+# define BIO_RR_CONNECT 0x02
+/* Returned from the accept BIO when an accept would have blocked */
+# define BIO_RR_ACCEPT 0x03
+
+/* These are passed by the BIO callback */
+# define BIO_CB_FREE 0x01
+# define BIO_CB_READ 0x02
+# define BIO_CB_WRITE 0x03
+# define BIO_CB_PUTS 0x04
+# define BIO_CB_GETS 0x05
+# define BIO_CB_CTRL 0x06
+
+/*
+ * The callback is called before and after the underling operation, The
+ * BIO_CB_RETURN flag indicates if it is after the call
+ */
+# define BIO_CB_RETURN 0x80
+# define BIO_CB_return(a) ((a)|BIO_CB_RETURN)
+# define BIO_cb_pre(a) (!((a)&BIO_CB_RETURN))
+# define BIO_cb_post(a) ((a)&BIO_CB_RETURN)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef long (*BIO_callback_fn)(BIO *b, int oper, const char *argp, int argi,
+ long argl, long ret);
+OSSL_DEPRECATEDIN_3_0 BIO_callback_fn BIO_get_callback(const BIO *b);
+OSSL_DEPRECATEDIN_3_0 void BIO_set_callback(BIO *b, BIO_callback_fn callback);
+OSSL_DEPRECATEDIN_3_0 long BIO_debug_callback(BIO *bio, int cmd,
+ const char *argp, int argi,
+ long argl, long ret);
+# endif
+
+typedef long (*BIO_callback_fn_ex)(BIO *b, int oper, const char *argp,
+ size_t len, int argi,
+ long argl, int ret, size_t *processed);
+BIO_callback_fn_ex BIO_get_callback_ex(const BIO *b);
+void BIO_set_callback_ex(BIO *b, BIO_callback_fn_ex callback);
+long BIO_debug_callback_ex(BIO *bio, int oper, const char *argp, size_t len,
+ int argi, long argl, int ret, size_t *processed);
+
+char *BIO_get_callback_arg(const BIO *b);
+void BIO_set_callback_arg(BIO *b, char *arg);
+
+typedef struct bio_method_st BIO_METHOD;
+
+const char *BIO_method_name(const BIO *b);
+int BIO_method_type(const BIO *b);
+
+typedef int BIO_info_cb(BIO *, int, int);
+typedef BIO_info_cb bio_info_cb; /* backward compatibility */
+
+SKM_DEFINE_STACK_OF_INTERNAL(BIO, BIO, BIO)
+#define sk_BIO_num(sk) OPENSSL_sk_num(ossl_check_const_BIO_sk_type(sk))
+#define sk_BIO_value(sk, idx) ((BIO *)OPENSSL_sk_value(ossl_check_const_BIO_sk_type(sk), (idx)))
+#define sk_BIO_new(cmp) ((STACK_OF(BIO) *)OPENSSL_sk_new(ossl_check_BIO_compfunc_type(cmp)))
+#define sk_BIO_new_null() ((STACK_OF(BIO) *)OPENSSL_sk_new_null())
+#define sk_BIO_new_reserve(cmp, n) ((STACK_OF(BIO) *)OPENSSL_sk_new_reserve(ossl_check_BIO_compfunc_type(cmp), (n)))
+#define sk_BIO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_BIO_sk_type(sk), (n))
+#define sk_BIO_free(sk) OPENSSL_sk_free(ossl_check_BIO_sk_type(sk))
+#define sk_BIO_zero(sk) OPENSSL_sk_zero(ossl_check_BIO_sk_type(sk))
+#define sk_BIO_delete(sk, i) ((BIO *)OPENSSL_sk_delete(ossl_check_BIO_sk_type(sk), (i)))
+#define sk_BIO_delete_ptr(sk, ptr) ((BIO *)OPENSSL_sk_delete_ptr(ossl_check_BIO_sk_type(sk), ossl_check_BIO_type(ptr)))
+#define sk_BIO_push(sk, ptr) OPENSSL_sk_push(ossl_check_BIO_sk_type(sk), ossl_check_BIO_type(ptr))
+#define sk_BIO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_BIO_sk_type(sk), ossl_check_BIO_type(ptr))
+#define sk_BIO_pop(sk) ((BIO *)OPENSSL_sk_pop(ossl_check_BIO_sk_type(sk)))
+#define sk_BIO_shift(sk) ((BIO *)OPENSSL_sk_shift(ossl_check_BIO_sk_type(sk)))
+#define sk_BIO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_BIO_sk_type(sk),ossl_check_BIO_freefunc_type(freefunc))
+#define sk_BIO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_BIO_sk_type(sk), ossl_check_BIO_type(ptr), (idx))
+#define sk_BIO_set(sk, idx, ptr) ((BIO *)OPENSSL_sk_set(ossl_check_BIO_sk_type(sk), (idx), ossl_check_BIO_type(ptr)))
+#define sk_BIO_find(sk, ptr) OPENSSL_sk_find(ossl_check_BIO_sk_type(sk), ossl_check_BIO_type(ptr))
+#define sk_BIO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_BIO_sk_type(sk), ossl_check_BIO_type(ptr))
+#define sk_BIO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_BIO_sk_type(sk), ossl_check_BIO_type(ptr), pnum)
+#define sk_BIO_sort(sk) OPENSSL_sk_sort(ossl_check_BIO_sk_type(sk))
+#define sk_BIO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_BIO_sk_type(sk))
+#define sk_BIO_dup(sk) ((STACK_OF(BIO) *)OPENSSL_sk_dup(ossl_check_const_BIO_sk_type(sk)))
+#define sk_BIO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(BIO) *)OPENSSL_sk_deep_copy(ossl_check_const_BIO_sk_type(sk), ossl_check_BIO_copyfunc_type(copyfunc), ossl_check_BIO_freefunc_type(freefunc)))
+#define sk_BIO_set_cmp_func(sk, cmp) ((sk_BIO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_BIO_sk_type(sk), ossl_check_BIO_compfunc_type(cmp)))
+
+
+
+/* Prefix and suffix callback in ASN1 BIO */
+typedef int asn1_ps_func (BIO *b, unsigned char **pbuf, int *plen,
+ void *parg);
+
+typedef void (*BIO_dgram_sctp_notification_handler_fn) (BIO *b,
+ void *context,
+ void *buf);
+# ifndef OPENSSL_NO_SCTP
+/* SCTP parameter structs */
+struct bio_dgram_sctp_sndinfo {
+ uint16_t snd_sid;
+ uint16_t snd_flags;
+ uint32_t snd_ppid;
+ uint32_t snd_context;
+};
+
+struct bio_dgram_sctp_rcvinfo {
+ uint16_t rcv_sid;
+ uint16_t rcv_ssn;
+ uint16_t rcv_flags;
+ uint32_t rcv_ppid;
+ uint32_t rcv_tsn;
+ uint32_t rcv_cumtsn;
+ uint32_t rcv_context;
+};
+
+struct bio_dgram_sctp_prinfo {
+ uint16_t pr_policy;
+ uint32_t pr_value;
+};
+# endif
+
+/*
+ * #define BIO_CONN_get_param_hostname BIO_ctrl
+ */
+
+# define BIO_C_SET_CONNECT 100
+# define BIO_C_DO_STATE_MACHINE 101
+# define BIO_C_SET_NBIO 102
+/* # define BIO_C_SET_PROXY_PARAM 103 */
+# define BIO_C_SET_FD 104
+# define BIO_C_GET_FD 105
+# define BIO_C_SET_FILE_PTR 106
+# define BIO_C_GET_FILE_PTR 107
+# define BIO_C_SET_FILENAME 108
+# define BIO_C_SET_SSL 109
+# define BIO_C_GET_SSL 110
+# define BIO_C_SET_MD 111
+# define BIO_C_GET_MD 112
+# define BIO_C_GET_CIPHER_STATUS 113
+# define BIO_C_SET_BUF_MEM 114
+# define BIO_C_GET_BUF_MEM_PTR 115
+# define BIO_C_GET_BUFF_NUM_LINES 116
+# define BIO_C_SET_BUFF_SIZE 117
+# define BIO_C_SET_ACCEPT 118
+# define BIO_C_SSL_MODE 119
+# define BIO_C_GET_MD_CTX 120
+/* # define BIO_C_GET_PROXY_PARAM 121 */
+# define BIO_C_SET_BUFF_READ_DATA 122/* data to read first */
+# define BIO_C_GET_CONNECT 123
+# define BIO_C_GET_ACCEPT 124
+# define BIO_C_SET_SSL_RENEGOTIATE_BYTES 125
+# define BIO_C_GET_SSL_NUM_RENEGOTIATES 126
+# define BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT 127
+# define BIO_C_FILE_SEEK 128
+# define BIO_C_GET_CIPHER_CTX 129
+# define BIO_C_SET_BUF_MEM_EOF_RETURN 130/* return end of input
+ * value */
+# define BIO_C_SET_BIND_MODE 131
+# define BIO_C_GET_BIND_MODE 132
+# define BIO_C_FILE_TELL 133
+# define BIO_C_GET_SOCKS 134
+# define BIO_C_SET_SOCKS 135
+
+# define BIO_C_SET_WRITE_BUF_SIZE 136/* for BIO_s_bio */
+# define BIO_C_GET_WRITE_BUF_SIZE 137
+# define BIO_C_MAKE_BIO_PAIR 138
+# define BIO_C_DESTROY_BIO_PAIR 139
+# define BIO_C_GET_WRITE_GUARANTEE 140
+# define BIO_C_GET_READ_REQUEST 141
+# define BIO_C_SHUTDOWN_WR 142
+# define BIO_C_NREAD0 143
+# define BIO_C_NREAD 144
+# define BIO_C_NWRITE0 145
+# define BIO_C_NWRITE 146
+# define BIO_C_RESET_READ_REQUEST 147
+# define BIO_C_SET_MD_CTX 148
+
+# define BIO_C_SET_PREFIX 149
+# define BIO_C_GET_PREFIX 150
+# define BIO_C_SET_SUFFIX 151
+# define BIO_C_GET_SUFFIX 152
+
+# define BIO_C_SET_EX_ARG 153
+# define BIO_C_GET_EX_ARG 154
+
+# define BIO_C_SET_CONNECT_MODE 155
+
+# define BIO_set_app_data(s,arg) BIO_set_ex_data(s,0,arg)
+# define BIO_get_app_data(s) BIO_get_ex_data(s,0)
+
+# define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL)
+
+# ifndef OPENSSL_NO_SOCK
+/* IP families we support, for BIO_s_connect() and BIO_s_accept() */
+/* Note: the underlying operating system may not support some of them */
+# define BIO_FAMILY_IPV4 4
+# define BIO_FAMILY_IPV6 6
+# define BIO_FAMILY_IPANY 256
+
+/* BIO_s_connect() */
+# define BIO_set_conn_hostname(b,name) BIO_ctrl(b,BIO_C_SET_CONNECT,0, \
+ (char *)(name))
+# define BIO_set_conn_port(b,port) BIO_ctrl(b,BIO_C_SET_CONNECT,1, \
+ (char *)(port))
+# define BIO_set_conn_address(b,addr) BIO_ctrl(b,BIO_C_SET_CONNECT,2, \
+ (char *)(addr))
+# define BIO_set_conn_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_CONNECT,3,f)
+# define BIO_get_conn_hostname(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,0))
+# define BIO_get_conn_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,1))
+# define BIO_get_conn_address(b) ((const BIO_ADDR *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,2))
+# define BIO_get_conn_ip_family(b) BIO_ctrl(b,BIO_C_GET_CONNECT,3,NULL)
+# define BIO_set_conn_mode(b,n) BIO_ctrl(b,BIO_C_SET_CONNECT_MODE,(n),NULL)
+
+/* BIO_s_accept() */
+# define BIO_set_accept_name(b,name) BIO_ctrl(b,BIO_C_SET_ACCEPT,0, \
+ (char *)(name))
+# define BIO_set_accept_port(b,port) BIO_ctrl(b,BIO_C_SET_ACCEPT,1, \
+ (char *)(port))
+# define BIO_get_accept_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,0))
+# define BIO_get_accept_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,1))
+# define BIO_get_peer_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,2))
+# define BIO_get_peer_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,3))
+/* #define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL) */
+# define BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,2,(n)?(void *)"a":NULL)
+# define BIO_set_accept_bios(b,bio) BIO_ctrl(b,BIO_C_SET_ACCEPT,3, \
+ (char *)(bio))
+# define BIO_set_accept_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_ACCEPT,4,f)
+# define BIO_get_accept_ip_family(b) BIO_ctrl(b,BIO_C_GET_ACCEPT,4,NULL)
+
+/* Aliases kept for backward compatibility */
+# define BIO_BIND_NORMAL 0
+# define BIO_BIND_REUSEADDR BIO_SOCK_REUSEADDR
+# define BIO_BIND_REUSEADDR_IF_UNUSED BIO_SOCK_REUSEADDR
+# define BIO_set_bind_mode(b,mode) BIO_ctrl(b,BIO_C_SET_BIND_MODE,mode,NULL)
+# define BIO_get_bind_mode(b) BIO_ctrl(b,BIO_C_GET_BIND_MODE,0,NULL)
+# endif /* OPENSSL_NO_SOCK */
+
+# define BIO_do_connect(b) BIO_do_handshake(b)
+# define BIO_do_accept(b) BIO_do_handshake(b)
+
+# define BIO_do_handshake(b) BIO_ctrl(b,BIO_C_DO_STATE_MACHINE,0,NULL)
+
+/* BIO_s_datagram(), BIO_s_fd(), BIO_s_socket(), BIO_s_accept() and BIO_s_connect() */
+# define BIO_set_fd(b,fd,c) BIO_int_ctrl(b,BIO_C_SET_FD,c,fd)
+# define BIO_get_fd(b,c) BIO_ctrl(b,BIO_C_GET_FD,0,(char *)(c))
+
+/* BIO_s_file() */
+# define BIO_set_fp(b,fp,c) BIO_ctrl(b,BIO_C_SET_FILE_PTR,c,(char *)(fp))
+# define BIO_get_fp(b,fpp) BIO_ctrl(b,BIO_C_GET_FILE_PTR,0,(char *)(fpp))
+
+/* BIO_s_fd() and BIO_s_file() */
+# define BIO_seek(b,ofs) (int)BIO_ctrl(b,BIO_C_FILE_SEEK,ofs,NULL)
+# define BIO_tell(b) (int)BIO_ctrl(b,BIO_C_FILE_TELL,0,NULL)
+
+/*
+ * name is cast to lose const, but might be better to route through a
+ * function so we can do it safely
+ */
+# ifdef CONST_STRICT
+/*
+ * If you are wondering why this isn't defined, its because CONST_STRICT is
+ * purely a compile-time kludge to allow const to be checked.
+ */
+int BIO_read_filename(BIO *b, const char *name);
+# else
+# define BIO_read_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_READ,(char *)(name))
+# endif
+# define BIO_write_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_WRITE,name)
+# define BIO_append_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_APPEND,name)
+# define BIO_rw_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_READ|BIO_FP_WRITE,name)
+
+/*
+ * WARNING WARNING, this ups the reference count on the read bio of the SSL
+ * structure. This is because the ssl read BIO is now pointed to by the
+ * next_bio field in the bio. So when you free the BIO, make sure you are
+ * doing a BIO_free_all() to catch the underlying BIO.
+ */
+# define BIO_set_ssl(b,ssl,c) BIO_ctrl(b,BIO_C_SET_SSL,c,(char *)(ssl))
+# define BIO_get_ssl(b,sslp) BIO_ctrl(b,BIO_C_GET_SSL,0,(char *)(sslp))
+# define BIO_set_ssl_mode(b,client) BIO_ctrl(b,BIO_C_SSL_MODE,client,NULL)
+# define BIO_set_ssl_renegotiate_bytes(b,num) \
+ BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_BYTES,num,NULL)
+# define BIO_get_num_renegotiates(b) \
+ BIO_ctrl(b,BIO_C_GET_SSL_NUM_RENEGOTIATES,0,NULL)
+# define BIO_set_ssl_renegotiate_timeout(b,seconds) \
+ BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT,seconds,NULL)
+
+/* defined in evp.h */
+/* #define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,1,(char *)(md)) */
+
+# define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)(pp))
+# define BIO_set_mem_buf(b,bm,c) BIO_ctrl(b,BIO_C_SET_BUF_MEM,c,(char *)(bm))
+# define BIO_get_mem_ptr(b,pp) BIO_ctrl(b,BIO_C_GET_BUF_MEM_PTR,0, \
+ (char *)(pp))
+# define BIO_set_mem_eof_return(b,v) \
+ BIO_ctrl(b,BIO_C_SET_BUF_MEM_EOF_RETURN,v,NULL)
+
+/* For the BIO_f_buffer() type */
+# define BIO_get_buffer_num_lines(b) BIO_ctrl(b,BIO_C_GET_BUFF_NUM_LINES,0,NULL)
+# define BIO_set_buffer_size(b,size) BIO_ctrl(b,BIO_C_SET_BUFF_SIZE,size,NULL)
+# define BIO_set_read_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,0)
+# define BIO_set_write_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,1)
+# define BIO_set_buffer_read_data(b,buf,num) BIO_ctrl(b,BIO_C_SET_BUFF_READ_DATA,num,buf)
+
+/* Don't use the next one unless you know what you are doing :-) */
+# define BIO_dup_state(b,ret) BIO_ctrl(b,BIO_CTRL_DUP,0,(char *)(ret))
+
+# define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL)
+# define BIO_eof(b) (int)BIO_ctrl(b,BIO_CTRL_EOF,0,NULL)
+# define BIO_set_close(b,c) (int)BIO_ctrl(b,BIO_CTRL_SET_CLOSE,(c),NULL)
+# define BIO_get_close(b) (int)BIO_ctrl(b,BIO_CTRL_GET_CLOSE,0,NULL)
+# define BIO_pending(b) (int)BIO_ctrl(b,BIO_CTRL_PENDING,0,NULL)
+# define BIO_wpending(b) (int)BIO_ctrl(b,BIO_CTRL_WPENDING,0,NULL)
+/* ...pending macros have inappropriate return type */
+size_t BIO_ctrl_pending(BIO *b);
+size_t BIO_ctrl_wpending(BIO *b);
+# define BIO_flush(b) (int)BIO_ctrl(b,BIO_CTRL_FLUSH,0,NULL)
+# define BIO_get_info_callback(b,cbp) (int)BIO_ctrl(b,BIO_CTRL_GET_CALLBACK,0, \
+ cbp)
+# define BIO_set_info_callback(b,cb) (int)BIO_callback_ctrl(b,BIO_CTRL_SET_CALLBACK,cb)
+
+/* For the BIO_f_buffer() type */
+# define BIO_buffer_get_num_lines(b) BIO_ctrl(b,BIO_CTRL_GET,0,NULL)
+# define BIO_buffer_peek(b,s,l) BIO_ctrl(b,BIO_CTRL_PEEK,(l),(s))
+
+/* For BIO_s_bio() */
+# define BIO_set_write_buf_size(b,size) (int)BIO_ctrl(b,BIO_C_SET_WRITE_BUF_SIZE,size,NULL)
+# define BIO_get_write_buf_size(b,size) (size_t)BIO_ctrl(b,BIO_C_GET_WRITE_BUF_SIZE,size,NULL)
+# define BIO_make_bio_pair(b1,b2) (int)BIO_ctrl(b1,BIO_C_MAKE_BIO_PAIR,0,b2)
+# define BIO_destroy_bio_pair(b) (int)BIO_ctrl(b,BIO_C_DESTROY_BIO_PAIR,0,NULL)
+# define BIO_shutdown_wr(b) (int)BIO_ctrl(b, BIO_C_SHUTDOWN_WR, 0, NULL)
+/* macros with inappropriate type -- but ...pending macros use int too: */
+# define BIO_get_write_guarantee(b) (int)BIO_ctrl(b,BIO_C_GET_WRITE_GUARANTEE,0,NULL)
+# define BIO_get_read_request(b) (int)BIO_ctrl(b,BIO_C_GET_READ_REQUEST,0,NULL)
+size_t BIO_ctrl_get_write_guarantee(BIO *b);
+size_t BIO_ctrl_get_read_request(BIO *b);
+int BIO_ctrl_reset_read_request(BIO *b);
+
+/* ctrl macros for dgram */
+# define BIO_ctrl_dgram_connect(b,peer) \
+ (int)BIO_ctrl(b,BIO_CTRL_DGRAM_CONNECT,0, (char *)(peer))
+# define BIO_ctrl_set_connected(b,peer) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_CONNECTED, 0, (char *)(peer))
+# define BIO_dgram_recv_timedout(b) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)
+# define BIO_dgram_send_timedout(b) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP, 0, NULL)
+# define BIO_dgram_get_peer(b,peer) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_PEER, 0, (char *)(peer))
+# define BIO_dgram_set_peer(b,peer) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, (char *)(peer))
+# define BIO_dgram_get_mtu_overhead(b) \
+ (unsigned int)BIO_ctrl((b), BIO_CTRL_DGRAM_GET_MTU_OVERHEAD, 0, NULL)
+
+/* ctrl macros for BIO_f_prefix */
+# define BIO_set_prefix(b,p) BIO_ctrl((b), BIO_CTRL_SET_PREFIX, 0, (void *)(p))
+# define BIO_set_indent(b,i) BIO_ctrl((b), BIO_CTRL_SET_INDENT, (i), NULL)
+# define BIO_get_indent(b) BIO_ctrl((b), BIO_CTRL_GET_INDENT, 0, NULL)
+
+#define BIO_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_BIO, l, p, newf, dupf, freef)
+int BIO_set_ex_data(BIO *bio, int idx, void *data);
+void *BIO_get_ex_data(const BIO *bio, int idx);
+uint64_t BIO_number_read(BIO *bio);
+uint64_t BIO_number_written(BIO *bio);
+
+/* For BIO_f_asn1() */
+int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix,
+ asn1_ps_func *prefix_free);
+int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix,
+ asn1_ps_func **pprefix_free);
+int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix,
+ asn1_ps_func *suffix_free);
+int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix,
+ asn1_ps_func **psuffix_free);
+
+const BIO_METHOD *BIO_s_file(void);
+BIO *BIO_new_file(const char *filename, const char *mode);
+BIO *BIO_new_from_core_bio(OSSL_LIB_CTX *libctx, OSSL_CORE_BIO *corebio);
+# ifndef OPENSSL_NO_STDIO
+BIO *BIO_new_fp(FILE *stream, int close_flag);
+# endif
+BIO *BIO_new_ex(OSSL_LIB_CTX *libctx, const BIO_METHOD *method);
+BIO *BIO_new(const BIO_METHOD *type);
+int BIO_free(BIO *a);
+void BIO_set_data(BIO *a, void *ptr);
+void *BIO_get_data(BIO *a);
+void BIO_set_init(BIO *a, int init);
+int BIO_get_init(BIO *a);
+void BIO_set_shutdown(BIO *a, int shut);
+int BIO_get_shutdown(BIO *a);
+void BIO_vfree(BIO *a);
+int BIO_up_ref(BIO *a);
+int BIO_read(BIO *b, void *data, int dlen);
+int BIO_read_ex(BIO *b, void *data, size_t dlen, size_t *readbytes);
+int BIO_gets(BIO *bp, char *buf, int size);
+int BIO_get_line(BIO *bio, char *buf, int size);
+int BIO_write(BIO *b, const void *data, int dlen);
+int BIO_write_ex(BIO *b, const void *data, size_t dlen, size_t *written);
+int BIO_puts(BIO *bp, const char *buf);
+int BIO_indent(BIO *b, int indent, int max);
+long BIO_ctrl(BIO *bp, int cmd, long larg, void *parg);
+long BIO_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp);
+void *BIO_ptr_ctrl(BIO *bp, int cmd, long larg);
+long BIO_int_ctrl(BIO *bp, int cmd, long larg, int iarg);
+BIO *BIO_push(BIO *b, BIO *append);
+BIO *BIO_pop(BIO *b);
+void BIO_free_all(BIO *a);
+BIO *BIO_find_type(BIO *b, int bio_type);
+BIO *BIO_next(BIO *b);
+void BIO_set_next(BIO *b, BIO *next);
+BIO *BIO_get_retry_BIO(BIO *bio, int *reason);
+int BIO_get_retry_reason(BIO *bio);
+void BIO_set_retry_reason(BIO *bio, int reason);
+BIO *BIO_dup_chain(BIO *in);
+
+int BIO_nread0(BIO *bio, char **buf);
+int BIO_nread(BIO *bio, char **buf, int num);
+int BIO_nwrite0(BIO *bio, char **buf);
+int BIO_nwrite(BIO *bio, char **buf, int num);
+
+const BIO_METHOD *BIO_s_mem(void);
+const BIO_METHOD *BIO_s_secmem(void);
+BIO *BIO_new_mem_buf(const void *buf, int len);
+# ifndef OPENSSL_NO_SOCK
+const BIO_METHOD *BIO_s_socket(void);
+const BIO_METHOD *BIO_s_connect(void);
+const BIO_METHOD *BIO_s_accept(void);
+# endif
+const BIO_METHOD *BIO_s_fd(void);
+const BIO_METHOD *BIO_s_log(void);
+const BIO_METHOD *BIO_s_bio(void);
+const BIO_METHOD *BIO_s_null(void);
+const BIO_METHOD *BIO_f_null(void);
+const BIO_METHOD *BIO_f_buffer(void);
+const BIO_METHOD *BIO_f_readbuffer(void);
+const BIO_METHOD *BIO_f_linebuffer(void);
+const BIO_METHOD *BIO_f_nbio_test(void);
+const BIO_METHOD *BIO_f_prefix(void);
+const BIO_METHOD *BIO_s_core(void);
+# ifndef OPENSSL_NO_DGRAM
+const BIO_METHOD *BIO_s_datagram(void);
+int BIO_dgram_non_fatal_error(int error);
+BIO *BIO_new_dgram(int fd, int close_flag);
+# ifndef OPENSSL_NO_SCTP
+const BIO_METHOD *BIO_s_datagram_sctp(void);
+BIO *BIO_new_dgram_sctp(int fd, int close_flag);
+int BIO_dgram_is_sctp(BIO *bio);
+int BIO_dgram_sctp_notification_cb(BIO *b,
+ BIO_dgram_sctp_notification_handler_fn handle_notifications,
+ void *context);
+int BIO_dgram_sctp_wait_for_dry(BIO *b);
+int BIO_dgram_sctp_msg_waiting(BIO *b);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_SOCK
+int BIO_sock_should_retry(int i);
+int BIO_sock_non_fatal_error(int error);
+int BIO_socket_wait(int fd, int for_read, time_t max_time);
+# endif
+int BIO_wait(BIO *bio, time_t max_time, unsigned int nap_milliseconds);
+int BIO_do_connect_retry(BIO *bio, int timeout, int nap_milliseconds);
+
+int BIO_fd_should_retry(int i);
+int BIO_fd_non_fatal_error(int error);
+int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u),
+ void *u, const void *s, int len);
+int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u),
+ void *u, const void *s, int len, int indent);
+int BIO_dump(BIO *b, const void *bytes, int len);
+int BIO_dump_indent(BIO *b, const void *bytes, int len, int indent);
+# ifndef OPENSSL_NO_STDIO
+int BIO_dump_fp(FILE *fp, const void *s, int len);
+int BIO_dump_indent_fp(FILE *fp, const void *s, int len, int indent);
+# endif
+int BIO_hex_string(BIO *out, int indent, int width, const void *data,
+ int datalen);
+
+# ifndef OPENSSL_NO_SOCK
+BIO_ADDR *BIO_ADDR_new(void);
+int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
+ const void *where, size_t wherelen, unsigned short port);
+void BIO_ADDR_free(BIO_ADDR *);
+void BIO_ADDR_clear(BIO_ADDR *ap);
+int BIO_ADDR_family(const BIO_ADDR *ap);
+int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l);
+unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap);
+char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric);
+char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric);
+char *BIO_ADDR_path_string(const BIO_ADDR *ap);
+
+const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai);
+int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai);
+int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai);
+int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai);
+const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai);
+void BIO_ADDRINFO_free(BIO_ADDRINFO *bai);
+
+enum BIO_hostserv_priorities {
+ BIO_PARSE_PRIO_HOST, BIO_PARSE_PRIO_SERV
+};
+int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
+ enum BIO_hostserv_priorities hostserv_prio);
+enum BIO_lookup_type {
+ BIO_LOOKUP_CLIENT, BIO_LOOKUP_SERVER
+};
+int BIO_lookup(const char *host, const char *service,
+ enum BIO_lookup_type lookup_type,
+ int family, int socktype, BIO_ADDRINFO **res);
+int BIO_lookup_ex(const char *host, const char *service,
+ int lookup_type, int family, int socktype, int protocol,
+ BIO_ADDRINFO **res);
+int BIO_sock_error(int sock);
+int BIO_socket_ioctl(int fd, long type, void *arg);
+int BIO_socket_nbio(int fd, int mode);
+int BIO_sock_init(void);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define BIO_sock_cleanup() while(0) continue
+# endif
+int BIO_set_tcp_ndelay(int sock, int turn_on);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 struct hostent *BIO_gethostbyname(const char *name);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_get_port(const char *str, unsigned short *port_ptr);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_get_host_ip(const char *str, unsigned char *ip);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_get_accept_socket(char *host_port, int mode);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_accept(int sock, char **ip_port);
+# endif
+
+union BIO_sock_info_u {
+ BIO_ADDR *addr;
+};
+enum BIO_sock_info_type {
+ BIO_SOCK_INFO_ADDRESS
+};
+int BIO_sock_info(int sock,
+ enum BIO_sock_info_type type, union BIO_sock_info_u *info);
+
+# define BIO_SOCK_REUSEADDR 0x01
+# define BIO_SOCK_V6_ONLY 0x02
+# define BIO_SOCK_KEEPALIVE 0x04
+# define BIO_SOCK_NONBLOCK 0x08
+# define BIO_SOCK_NODELAY 0x10
+
+int BIO_socket(int domain, int socktype, int protocol, int options);
+int BIO_connect(int sock, const BIO_ADDR *addr, int options);
+int BIO_bind(int sock, const BIO_ADDR *addr, int options);
+int BIO_listen(int sock, const BIO_ADDR *addr, int options);
+int BIO_accept_ex(int accept_sock, BIO_ADDR *addr, int options);
+int BIO_closesocket(int sock);
+
+BIO *BIO_new_socket(int sock, int close_flag);
+BIO *BIO_new_connect(const char *host_port);
+BIO *BIO_new_accept(const char *host_port);
+# endif /* OPENSSL_NO_SOCK*/
+
+BIO *BIO_new_fd(int fd, int close_flag);
+
+int BIO_new_bio_pair(BIO **bio1, size_t writebuf1,
+ BIO **bio2, size_t writebuf2);
+/*
+ * If successful, returns 1 and in *bio1, *bio2 two BIO pair endpoints.
+ * Otherwise returns 0 and sets *bio1 and *bio2 to NULL. Size 0 uses default
+ * value.
+ */
+
+void BIO_copy_next_retry(BIO *b);
+
+/*
+ * long BIO_ghbn_ctrl(int cmd,int iarg,char *parg);
+ */
+
+# define ossl_bio__attr__(x)
+# if defined(__GNUC__) && defined(__STDC_VERSION__) \
+ && !defined(__APPLE__)
+ /*
+ * Because we support the 'z' modifier, which made its appearance in C99,
+ * we can't use __attribute__ with pre C99 dialects.
+ */
+# if __STDC_VERSION__ >= 199901L
+# undef ossl_bio__attr__
+# define ossl_bio__attr__ __attribute__
+# if __GNUC__*10 + __GNUC_MINOR__ >= 44
+# define ossl_bio__printf__ __gnu_printf__
+# else
+# define ossl_bio__printf__ __printf__
+# endif
+# endif
+# endif
+int BIO_printf(BIO *bio, const char *format, ...)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 3)));
+int BIO_vprintf(BIO *bio, const char *format, va_list args)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 0)));
+int BIO_snprintf(char *buf, size_t n, const char *format, ...)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 4)));
+int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 0)));
+# undef ossl_bio__attr__
+# undef ossl_bio__printf__
+
+
+BIO_METHOD *BIO_meth_new(int type, const char *name);
+void BIO_meth_free(BIO_METHOD *biom);
+int (*BIO_meth_get_write(const BIO_METHOD *biom)) (BIO *, const char *, int);
+int (*BIO_meth_get_write_ex(const BIO_METHOD *biom)) (BIO *, const char *, size_t,
+ size_t *);
+int BIO_meth_set_write(BIO_METHOD *biom,
+ int (*write) (BIO *, const char *, int));
+int BIO_meth_set_write_ex(BIO_METHOD *biom,
+ int (*bwrite) (BIO *, const char *, size_t, size_t *));
+int (*BIO_meth_get_read(const BIO_METHOD *biom)) (BIO *, char *, int);
+int (*BIO_meth_get_read_ex(const BIO_METHOD *biom)) (BIO *, char *, size_t, size_t *);
+int BIO_meth_set_read(BIO_METHOD *biom,
+ int (*read) (BIO *, char *, int));
+int BIO_meth_set_read_ex(BIO_METHOD *biom,
+ int (*bread) (BIO *, char *, size_t, size_t *));
+int (*BIO_meth_get_puts(const BIO_METHOD *biom)) (BIO *, const char *);
+int BIO_meth_set_puts(BIO_METHOD *biom,
+ int (*puts) (BIO *, const char *));
+int (*BIO_meth_get_gets(const BIO_METHOD *biom)) (BIO *, char *, int);
+int BIO_meth_set_gets(BIO_METHOD *biom,
+ int (*gets) (BIO *, char *, int));
+long (*BIO_meth_get_ctrl(const BIO_METHOD *biom)) (BIO *, int, long, void *);
+int BIO_meth_set_ctrl(BIO_METHOD *biom,
+ long (*ctrl) (BIO *, int, long, void *));
+int (*BIO_meth_get_create(const BIO_METHOD *bion)) (BIO *);
+int BIO_meth_set_create(BIO_METHOD *biom, int (*create) (BIO *));
+int (*BIO_meth_get_destroy(const BIO_METHOD *biom)) (BIO *);
+int BIO_meth_set_destroy(BIO_METHOD *biom, int (*destroy) (BIO *));
+long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *biom))
+ (BIO *, int, BIO_info_cb *);
+int BIO_meth_set_callback_ctrl(BIO_METHOD *biom,
+ long (*callback_ctrl) (BIO *, int,
+ BIO_info_cb *));
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/bio.h.in b/include/openssl/bio.h.in
new file mode 100644
index 00000000..2c65b7e1
--- /dev/null
+++ b/include/openssl/bio.h.in
@@ -0,0 +1,861 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_BIO_H
+# define OPENSSL_BIO_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_BIO_H
+# endif
+
+# include <openssl/e_os2.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+# include <stdarg.h>
+
+# include <openssl/crypto.h>
+# include <openssl/bioerr.h>
+# include <openssl/core.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* There are the classes of BIOs */
+# define BIO_TYPE_DESCRIPTOR 0x0100 /* socket, fd, connect or accept */
+# define BIO_TYPE_FILTER 0x0200
+# define BIO_TYPE_SOURCE_SINK 0x0400
+
+/* These are the 'types' of BIOs */
+# define BIO_TYPE_NONE 0
+# define BIO_TYPE_MEM ( 1|BIO_TYPE_SOURCE_SINK)
+# define BIO_TYPE_FILE ( 2|BIO_TYPE_SOURCE_SINK)
+
+# define BIO_TYPE_FD ( 4|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_SOCKET ( 5|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_NULL ( 6|BIO_TYPE_SOURCE_SINK)
+# define BIO_TYPE_SSL ( 7|BIO_TYPE_FILTER)
+# define BIO_TYPE_MD ( 8|BIO_TYPE_FILTER)
+# define BIO_TYPE_BUFFER ( 9|BIO_TYPE_FILTER)
+# define BIO_TYPE_CIPHER (10|BIO_TYPE_FILTER)
+# define BIO_TYPE_BASE64 (11|BIO_TYPE_FILTER)
+# define BIO_TYPE_CONNECT (12|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_ACCEPT (13|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+
+# define BIO_TYPE_NBIO_TEST (16|BIO_TYPE_FILTER)/* server proxy BIO */
+# define BIO_TYPE_NULL_FILTER (17|BIO_TYPE_FILTER)
+# define BIO_TYPE_BIO (19|BIO_TYPE_SOURCE_SINK)/* half a BIO pair */
+# define BIO_TYPE_LINEBUFFER (20|BIO_TYPE_FILTER)
+# define BIO_TYPE_DGRAM (21|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# define BIO_TYPE_ASN1 (22|BIO_TYPE_FILTER)
+# define BIO_TYPE_COMP (23|BIO_TYPE_FILTER)
+# ifndef OPENSSL_NO_SCTP
+# define BIO_TYPE_DGRAM_SCTP (24|BIO_TYPE_SOURCE_SINK|BIO_TYPE_DESCRIPTOR)
+# endif
+# define BIO_TYPE_CORE_TO_PROV (25|BIO_TYPE_SOURCE_SINK)
+
+#define BIO_TYPE_START 128
+
+/*
+ * BIO_FILENAME_READ|BIO_CLOSE to open or close on free.
+ * BIO_set_fp(in,stdin,BIO_NOCLOSE);
+ */
+# define BIO_NOCLOSE 0x00
+# define BIO_CLOSE 0x01
+
+/*
+ * These are used in the following macros and are passed to BIO_ctrl()
+ */
+# define BIO_CTRL_RESET 1/* opt - rewind/zero etc */
+# define BIO_CTRL_EOF 2/* opt - are we at the eof */
+# define BIO_CTRL_INFO 3/* opt - extra tit-bits */
+# define BIO_CTRL_SET 4/* man - set the 'IO' type */
+# define BIO_CTRL_GET 5/* man - get the 'IO' type */
+# define BIO_CTRL_PUSH 6/* opt - internal, used to signify change */
+# define BIO_CTRL_POP 7/* opt - internal, used to signify change */
+# define BIO_CTRL_GET_CLOSE 8/* man - set the 'close' on free */
+# define BIO_CTRL_SET_CLOSE 9/* man - set the 'close' on free */
+# define BIO_CTRL_PENDING 10/* opt - is their more data buffered */
+# define BIO_CTRL_FLUSH 11/* opt - 'flush' buffered output */
+# define BIO_CTRL_DUP 12/* man - extra stuff for 'duped' BIO */
+# define BIO_CTRL_WPENDING 13/* opt - number of bytes still to write */
+# define BIO_CTRL_SET_CALLBACK 14/* opt - set callback function */
+# define BIO_CTRL_GET_CALLBACK 15/* opt - set callback function */
+
+# define BIO_CTRL_PEEK 29/* BIO_f_buffer special */
+# define BIO_CTRL_SET_FILENAME 30/* BIO_s_file special */
+
+/* dgram BIO stuff */
+# define BIO_CTRL_DGRAM_CONNECT 31/* BIO dgram special */
+# define BIO_CTRL_DGRAM_SET_CONNECTED 32/* allow for an externally connected
+ * socket to be passed in */
+# define BIO_CTRL_DGRAM_SET_RECV_TIMEOUT 33/* setsockopt, essentially */
+# define BIO_CTRL_DGRAM_GET_RECV_TIMEOUT 34/* getsockopt, essentially */
+# define BIO_CTRL_DGRAM_SET_SEND_TIMEOUT 35/* setsockopt, essentially */
+# define BIO_CTRL_DGRAM_GET_SEND_TIMEOUT 36/* getsockopt, essentially */
+
+# define BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP 37/* flag whether the last */
+# define BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP 38/* I/O operation timed out */
+
+/* #ifdef IP_MTU_DISCOVER */
+# define BIO_CTRL_DGRAM_MTU_DISCOVER 39/* set DF bit on egress packets */
+/* #endif */
+
+# define BIO_CTRL_DGRAM_QUERY_MTU 40/* as kernel for current MTU */
+# define BIO_CTRL_DGRAM_GET_FALLBACK_MTU 47
+# define BIO_CTRL_DGRAM_GET_MTU 41/* get cached value for MTU */
+# define BIO_CTRL_DGRAM_SET_MTU 42/* set cached value for MTU.
+ * want to use this if asking
+ * the kernel fails */
+
+# define BIO_CTRL_DGRAM_MTU_EXCEEDED 43/* check whether the MTU was
+ * exceed in the previous write
+ * operation */
+
+# define BIO_CTRL_DGRAM_GET_PEER 46
+# define BIO_CTRL_DGRAM_SET_PEER 44/* Destination for the data */
+
+# define BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT 45/* Next DTLS handshake timeout
+ * to adjust socket timeouts */
+# define BIO_CTRL_DGRAM_SET_DONT_FRAG 48
+
+# define BIO_CTRL_DGRAM_GET_MTU_OVERHEAD 49
+
+/* Deliberately outside of OPENSSL_NO_SCTP - used in bss_dgram.c */
+# define BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE 50
+# ifndef OPENSSL_NO_SCTP
+/* SCTP stuff */
+# define BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY 51
+# define BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY 52
+# define BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD 53
+# define BIO_CTRL_DGRAM_SCTP_GET_SNDINFO 60
+# define BIO_CTRL_DGRAM_SCTP_SET_SNDINFO 61
+# define BIO_CTRL_DGRAM_SCTP_GET_RCVINFO 62
+# define BIO_CTRL_DGRAM_SCTP_SET_RCVINFO 63
+# define BIO_CTRL_DGRAM_SCTP_GET_PRINFO 64
+# define BIO_CTRL_DGRAM_SCTP_SET_PRINFO 65
+# define BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN 70
+# endif
+
+# define BIO_CTRL_DGRAM_SET_PEEK_MODE 71
+
+/*
+ * internal BIO:
+ * # define BIO_CTRL_SET_KTLS_SEND 72
+ * # define BIO_CTRL_SET_KTLS_SEND_CTRL_MSG 74
+ * # define BIO_CTRL_CLEAR_KTLS_CTRL_MSG 75
+ */
+
+# define BIO_CTRL_GET_KTLS_SEND 73
+# define BIO_CTRL_GET_KTLS_RECV 76
+
+# define BIO_CTRL_DGRAM_SCTP_WAIT_FOR_DRY 77
+# define BIO_CTRL_DGRAM_SCTP_MSG_WAITING 78
+
+/* BIO_f_prefix controls */
+# define BIO_CTRL_SET_PREFIX 79
+# define BIO_CTRL_SET_INDENT 80
+# define BIO_CTRL_GET_INDENT 81
+
+# ifndef OPENSSL_NO_KTLS
+# define BIO_get_ktls_send(b) \
+ BIO_ctrl(b, BIO_CTRL_GET_KTLS_SEND, 0, NULL)
+# define BIO_get_ktls_recv(b) \
+ BIO_ctrl(b, BIO_CTRL_GET_KTLS_RECV, 0, NULL)
+# else
+# define BIO_get_ktls_send(b) (0)
+# define BIO_get_ktls_recv(b) (0)
+# endif
+
+/* modifiers */
+# define BIO_FP_READ 0x02
+# define BIO_FP_WRITE 0x04
+# define BIO_FP_APPEND 0x08
+# define BIO_FP_TEXT 0x10
+
+# define BIO_FLAGS_READ 0x01
+# define BIO_FLAGS_WRITE 0x02
+# define BIO_FLAGS_IO_SPECIAL 0x04
+# define BIO_FLAGS_RWS (BIO_FLAGS_READ|BIO_FLAGS_WRITE|BIO_FLAGS_IO_SPECIAL)
+# define BIO_FLAGS_SHOULD_RETRY 0x08
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* This #define was replaced by an internal constant and should not be used. */
+# define BIO_FLAGS_UPLINK 0
+# endif
+
+# define BIO_FLAGS_BASE64_NO_NL 0x100
+
+/*
+ * This is used with memory BIOs:
+ * BIO_FLAGS_MEM_RDONLY means we shouldn't free up or change the data in any way;
+ * BIO_FLAGS_NONCLEAR_RST means we shouldn't clear data on reset.
+ */
+# define BIO_FLAGS_MEM_RDONLY 0x200
+# define BIO_FLAGS_NONCLEAR_RST 0x400
+# define BIO_FLAGS_IN_EOF 0x800
+
+typedef union bio_addr_st BIO_ADDR;
+typedef struct bio_addrinfo_st BIO_ADDRINFO;
+
+int BIO_get_new_index(void);
+void BIO_set_flags(BIO *b, int flags);
+int BIO_test_flags(const BIO *b, int flags);
+void BIO_clear_flags(BIO *b, int flags);
+
+# define BIO_get_flags(b) BIO_test_flags(b, ~(0x0))
+# define BIO_set_retry_special(b) \
+ BIO_set_flags(b, (BIO_FLAGS_IO_SPECIAL|BIO_FLAGS_SHOULD_RETRY))
+# define BIO_set_retry_read(b) \
+ BIO_set_flags(b, (BIO_FLAGS_READ|BIO_FLAGS_SHOULD_RETRY))
+# define BIO_set_retry_write(b) \
+ BIO_set_flags(b, (BIO_FLAGS_WRITE|BIO_FLAGS_SHOULD_RETRY))
+
+/* These are normally used internally in BIOs */
+# define BIO_clear_retry_flags(b) \
+ BIO_clear_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
+# define BIO_get_retry_flags(b) \
+ BIO_test_flags(b, (BIO_FLAGS_RWS|BIO_FLAGS_SHOULD_RETRY))
+
+/* These should be used by the application to tell why we should retry */
+# define BIO_should_read(a) BIO_test_flags(a, BIO_FLAGS_READ)
+# define BIO_should_write(a) BIO_test_flags(a, BIO_FLAGS_WRITE)
+# define BIO_should_io_special(a) BIO_test_flags(a, BIO_FLAGS_IO_SPECIAL)
+# define BIO_retry_type(a) BIO_test_flags(a, BIO_FLAGS_RWS)
+# define BIO_should_retry(a) BIO_test_flags(a, BIO_FLAGS_SHOULD_RETRY)
+
+/*
+ * The next three are used in conjunction with the BIO_should_io_special()
+ * condition. After this returns true, BIO *BIO_get_retry_BIO(BIO *bio, int
+ * *reason); will walk the BIO stack and return the 'reason' for the special
+ * and the offending BIO. Given a BIO, BIO_get_retry_reason(bio) will return
+ * the code.
+ */
+/*
+ * Returned from the SSL bio when the certificate retrieval code had an error
+ */
+# define BIO_RR_SSL_X509_LOOKUP 0x01
+/* Returned from the connect BIO when a connect would have blocked */
+# define BIO_RR_CONNECT 0x02
+/* Returned from the accept BIO when an accept would have blocked */
+# define BIO_RR_ACCEPT 0x03
+
+/* These are passed by the BIO callback */
+# define BIO_CB_FREE 0x01
+# define BIO_CB_READ 0x02
+# define BIO_CB_WRITE 0x03
+# define BIO_CB_PUTS 0x04
+# define BIO_CB_GETS 0x05
+# define BIO_CB_CTRL 0x06
+
+/*
+ * The callback is called before and after the underling operation, The
+ * BIO_CB_RETURN flag indicates if it is after the call
+ */
+# define BIO_CB_RETURN 0x80
+# define BIO_CB_return(a) ((a)|BIO_CB_RETURN)
+# define BIO_cb_pre(a) (!((a)&BIO_CB_RETURN))
+# define BIO_cb_post(a) ((a)&BIO_CB_RETURN)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef long (*BIO_callback_fn)(BIO *b, int oper, const char *argp, int argi,
+ long argl, long ret);
+OSSL_DEPRECATEDIN_3_0 BIO_callback_fn BIO_get_callback(const BIO *b);
+OSSL_DEPRECATEDIN_3_0 void BIO_set_callback(BIO *b, BIO_callback_fn callback);
+OSSL_DEPRECATEDIN_3_0 long BIO_debug_callback(BIO *bio, int cmd,
+ const char *argp, int argi,
+ long argl, long ret);
+# endif
+
+typedef long (*BIO_callback_fn_ex)(BIO *b, int oper, const char *argp,
+ size_t len, int argi,
+ long argl, int ret, size_t *processed);
+BIO_callback_fn_ex BIO_get_callback_ex(const BIO *b);
+void BIO_set_callback_ex(BIO *b, BIO_callback_fn_ex callback);
+long BIO_debug_callback_ex(BIO *bio, int oper, const char *argp, size_t len,
+ int argi, long argl, int ret, size_t *processed);
+
+char *BIO_get_callback_arg(const BIO *b);
+void BIO_set_callback_arg(BIO *b, char *arg);
+
+typedef struct bio_method_st BIO_METHOD;
+
+const char *BIO_method_name(const BIO *b);
+int BIO_method_type(const BIO *b);
+
+typedef int BIO_info_cb(BIO *, int, int);
+typedef BIO_info_cb bio_info_cb; /* backward compatibility */
+
+{-
+ generate_stack_macros("BIO");
+-}
+
+
+/* Prefix and suffix callback in ASN1 BIO */
+typedef int asn1_ps_func (BIO *b, unsigned char **pbuf, int *plen,
+ void *parg);
+
+typedef void (*BIO_dgram_sctp_notification_handler_fn) (BIO *b,
+ void *context,
+ void *buf);
+# ifndef OPENSSL_NO_SCTP
+/* SCTP parameter structs */
+struct bio_dgram_sctp_sndinfo {
+ uint16_t snd_sid;
+ uint16_t snd_flags;
+ uint32_t snd_ppid;
+ uint32_t snd_context;
+};
+
+struct bio_dgram_sctp_rcvinfo {
+ uint16_t rcv_sid;
+ uint16_t rcv_ssn;
+ uint16_t rcv_flags;
+ uint32_t rcv_ppid;
+ uint32_t rcv_tsn;
+ uint32_t rcv_cumtsn;
+ uint32_t rcv_context;
+};
+
+struct bio_dgram_sctp_prinfo {
+ uint16_t pr_policy;
+ uint32_t pr_value;
+};
+# endif
+
+/*
+ * #define BIO_CONN_get_param_hostname BIO_ctrl
+ */
+
+# define BIO_C_SET_CONNECT 100
+# define BIO_C_DO_STATE_MACHINE 101
+# define BIO_C_SET_NBIO 102
+/* # define BIO_C_SET_PROXY_PARAM 103 */
+# define BIO_C_SET_FD 104
+# define BIO_C_GET_FD 105
+# define BIO_C_SET_FILE_PTR 106
+# define BIO_C_GET_FILE_PTR 107
+# define BIO_C_SET_FILENAME 108
+# define BIO_C_SET_SSL 109
+# define BIO_C_GET_SSL 110
+# define BIO_C_SET_MD 111
+# define BIO_C_GET_MD 112
+# define BIO_C_GET_CIPHER_STATUS 113
+# define BIO_C_SET_BUF_MEM 114
+# define BIO_C_GET_BUF_MEM_PTR 115
+# define BIO_C_GET_BUFF_NUM_LINES 116
+# define BIO_C_SET_BUFF_SIZE 117
+# define BIO_C_SET_ACCEPT 118
+# define BIO_C_SSL_MODE 119
+# define BIO_C_GET_MD_CTX 120
+/* # define BIO_C_GET_PROXY_PARAM 121 */
+# define BIO_C_SET_BUFF_READ_DATA 122/* data to read first */
+# define BIO_C_GET_CONNECT 123
+# define BIO_C_GET_ACCEPT 124
+# define BIO_C_SET_SSL_RENEGOTIATE_BYTES 125
+# define BIO_C_GET_SSL_NUM_RENEGOTIATES 126
+# define BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT 127
+# define BIO_C_FILE_SEEK 128
+# define BIO_C_GET_CIPHER_CTX 129
+# define BIO_C_SET_BUF_MEM_EOF_RETURN 130/* return end of input
+ * value */
+# define BIO_C_SET_BIND_MODE 131
+# define BIO_C_GET_BIND_MODE 132
+# define BIO_C_FILE_TELL 133
+# define BIO_C_GET_SOCKS 134
+# define BIO_C_SET_SOCKS 135
+
+# define BIO_C_SET_WRITE_BUF_SIZE 136/* for BIO_s_bio */
+# define BIO_C_GET_WRITE_BUF_SIZE 137
+# define BIO_C_MAKE_BIO_PAIR 138
+# define BIO_C_DESTROY_BIO_PAIR 139
+# define BIO_C_GET_WRITE_GUARANTEE 140
+# define BIO_C_GET_READ_REQUEST 141
+# define BIO_C_SHUTDOWN_WR 142
+# define BIO_C_NREAD0 143
+# define BIO_C_NREAD 144
+# define BIO_C_NWRITE0 145
+# define BIO_C_NWRITE 146
+# define BIO_C_RESET_READ_REQUEST 147
+# define BIO_C_SET_MD_CTX 148
+
+# define BIO_C_SET_PREFIX 149
+# define BIO_C_GET_PREFIX 150
+# define BIO_C_SET_SUFFIX 151
+# define BIO_C_GET_SUFFIX 152
+
+# define BIO_C_SET_EX_ARG 153
+# define BIO_C_GET_EX_ARG 154
+
+# define BIO_C_SET_CONNECT_MODE 155
+
+# define BIO_set_app_data(s,arg) BIO_set_ex_data(s,0,arg)
+# define BIO_get_app_data(s) BIO_get_ex_data(s,0)
+
+# define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL)
+
+# ifndef OPENSSL_NO_SOCK
+/* IP families we support, for BIO_s_connect() and BIO_s_accept() */
+/* Note: the underlying operating system may not support some of them */
+# define BIO_FAMILY_IPV4 4
+# define BIO_FAMILY_IPV6 6
+# define BIO_FAMILY_IPANY 256
+
+/* BIO_s_connect() */
+# define BIO_set_conn_hostname(b,name) BIO_ctrl(b,BIO_C_SET_CONNECT,0, \
+ (char *)(name))
+# define BIO_set_conn_port(b,port) BIO_ctrl(b,BIO_C_SET_CONNECT,1, \
+ (char *)(port))
+# define BIO_set_conn_address(b,addr) BIO_ctrl(b,BIO_C_SET_CONNECT,2, \
+ (char *)(addr))
+# define BIO_set_conn_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_CONNECT,3,f)
+# define BIO_get_conn_hostname(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,0))
+# define BIO_get_conn_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,1))
+# define BIO_get_conn_address(b) ((const BIO_ADDR *)BIO_ptr_ctrl(b,BIO_C_GET_CONNECT,2))
+# define BIO_get_conn_ip_family(b) BIO_ctrl(b,BIO_C_GET_CONNECT,3,NULL)
+# define BIO_set_conn_mode(b,n) BIO_ctrl(b,BIO_C_SET_CONNECT_MODE,(n),NULL)
+
+/* BIO_s_accept() */
+# define BIO_set_accept_name(b,name) BIO_ctrl(b,BIO_C_SET_ACCEPT,0, \
+ (char *)(name))
+# define BIO_set_accept_port(b,port) BIO_ctrl(b,BIO_C_SET_ACCEPT,1, \
+ (char *)(port))
+# define BIO_get_accept_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,0))
+# define BIO_get_accept_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,1))
+# define BIO_get_peer_name(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,2))
+# define BIO_get_peer_port(b) ((const char *)BIO_ptr_ctrl(b,BIO_C_GET_ACCEPT,3))
+/* #define BIO_set_nbio(b,n) BIO_ctrl(b,BIO_C_SET_NBIO,(n),NULL) */
+# define BIO_set_nbio_accept(b,n) BIO_ctrl(b,BIO_C_SET_ACCEPT,2,(n)?(void *)"a":NULL)
+# define BIO_set_accept_bios(b,bio) BIO_ctrl(b,BIO_C_SET_ACCEPT,3, \
+ (char *)(bio))
+# define BIO_set_accept_ip_family(b,f) BIO_int_ctrl(b,BIO_C_SET_ACCEPT,4,f)
+# define BIO_get_accept_ip_family(b) BIO_ctrl(b,BIO_C_GET_ACCEPT,4,NULL)
+
+/* Aliases kept for backward compatibility */
+# define BIO_BIND_NORMAL 0
+# define BIO_BIND_REUSEADDR BIO_SOCK_REUSEADDR
+# define BIO_BIND_REUSEADDR_IF_UNUSED BIO_SOCK_REUSEADDR
+# define BIO_set_bind_mode(b,mode) BIO_ctrl(b,BIO_C_SET_BIND_MODE,mode,NULL)
+# define BIO_get_bind_mode(b) BIO_ctrl(b,BIO_C_GET_BIND_MODE,0,NULL)
+# endif /* OPENSSL_NO_SOCK */
+
+# define BIO_do_connect(b) BIO_do_handshake(b)
+# define BIO_do_accept(b) BIO_do_handshake(b)
+
+# define BIO_do_handshake(b) BIO_ctrl(b,BIO_C_DO_STATE_MACHINE,0,NULL)
+
+/* BIO_s_datagram(), BIO_s_fd(), BIO_s_socket(), BIO_s_accept() and BIO_s_connect() */
+# define BIO_set_fd(b,fd,c) BIO_int_ctrl(b,BIO_C_SET_FD,c,fd)
+# define BIO_get_fd(b,c) BIO_ctrl(b,BIO_C_GET_FD,0,(char *)(c))
+
+/* BIO_s_file() */
+# define BIO_set_fp(b,fp,c) BIO_ctrl(b,BIO_C_SET_FILE_PTR,c,(char *)(fp))
+# define BIO_get_fp(b,fpp) BIO_ctrl(b,BIO_C_GET_FILE_PTR,0,(char *)(fpp))
+
+/* BIO_s_fd() and BIO_s_file() */
+# define BIO_seek(b,ofs) (int)BIO_ctrl(b,BIO_C_FILE_SEEK,ofs,NULL)
+# define BIO_tell(b) (int)BIO_ctrl(b,BIO_C_FILE_TELL,0,NULL)
+
+/*
+ * name is cast to lose const, but might be better to route through a
+ * function so we can do it safely
+ */
+# ifdef CONST_STRICT
+/*
+ * If you are wondering why this isn't defined, its because CONST_STRICT is
+ * purely a compile-time kludge to allow const to be checked.
+ */
+int BIO_read_filename(BIO *b, const char *name);
+# else
+# define BIO_read_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_READ,(char *)(name))
+# endif
+# define BIO_write_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_WRITE,name)
+# define BIO_append_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_APPEND,name)
+# define BIO_rw_filename(b,name) (int)BIO_ctrl(b,BIO_C_SET_FILENAME, \
+ BIO_CLOSE|BIO_FP_READ|BIO_FP_WRITE,name)
+
+/*
+ * WARNING WARNING, this ups the reference count on the read bio of the SSL
+ * structure. This is because the ssl read BIO is now pointed to by the
+ * next_bio field in the bio. So when you free the BIO, make sure you are
+ * doing a BIO_free_all() to catch the underlying BIO.
+ */
+# define BIO_set_ssl(b,ssl,c) BIO_ctrl(b,BIO_C_SET_SSL,c,(char *)(ssl))
+# define BIO_get_ssl(b,sslp) BIO_ctrl(b,BIO_C_GET_SSL,0,(char *)(sslp))
+# define BIO_set_ssl_mode(b,client) BIO_ctrl(b,BIO_C_SSL_MODE,client,NULL)
+# define BIO_set_ssl_renegotiate_bytes(b,num) \
+ BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_BYTES,num,NULL)
+# define BIO_get_num_renegotiates(b) \
+ BIO_ctrl(b,BIO_C_GET_SSL_NUM_RENEGOTIATES,0,NULL)
+# define BIO_set_ssl_renegotiate_timeout(b,seconds) \
+ BIO_ctrl(b,BIO_C_SET_SSL_RENEGOTIATE_TIMEOUT,seconds,NULL)
+
+/* defined in evp.h */
+/* #define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,1,(char *)(md)) */
+
+# define BIO_get_mem_data(b,pp) BIO_ctrl(b,BIO_CTRL_INFO,0,(char *)(pp))
+# define BIO_set_mem_buf(b,bm,c) BIO_ctrl(b,BIO_C_SET_BUF_MEM,c,(char *)(bm))
+# define BIO_get_mem_ptr(b,pp) BIO_ctrl(b,BIO_C_GET_BUF_MEM_PTR,0, \
+ (char *)(pp))
+# define BIO_set_mem_eof_return(b,v) \
+ BIO_ctrl(b,BIO_C_SET_BUF_MEM_EOF_RETURN,v,NULL)
+
+/* For the BIO_f_buffer() type */
+# define BIO_get_buffer_num_lines(b) BIO_ctrl(b,BIO_C_GET_BUFF_NUM_LINES,0,NULL)
+# define BIO_set_buffer_size(b,size) BIO_ctrl(b,BIO_C_SET_BUFF_SIZE,size,NULL)
+# define BIO_set_read_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,0)
+# define BIO_set_write_buffer_size(b,size) BIO_int_ctrl(b,BIO_C_SET_BUFF_SIZE,size,1)
+# define BIO_set_buffer_read_data(b,buf,num) BIO_ctrl(b,BIO_C_SET_BUFF_READ_DATA,num,buf)
+
+/* Don't use the next one unless you know what you are doing :-) */
+# define BIO_dup_state(b,ret) BIO_ctrl(b,BIO_CTRL_DUP,0,(char *)(ret))
+
+# define BIO_reset(b) (int)BIO_ctrl(b,BIO_CTRL_RESET,0,NULL)
+# define BIO_eof(b) (int)BIO_ctrl(b,BIO_CTRL_EOF,0,NULL)
+# define BIO_set_close(b,c) (int)BIO_ctrl(b,BIO_CTRL_SET_CLOSE,(c),NULL)
+# define BIO_get_close(b) (int)BIO_ctrl(b,BIO_CTRL_GET_CLOSE,0,NULL)
+# define BIO_pending(b) (int)BIO_ctrl(b,BIO_CTRL_PENDING,0,NULL)
+# define BIO_wpending(b) (int)BIO_ctrl(b,BIO_CTRL_WPENDING,0,NULL)
+/* ...pending macros have inappropriate return type */
+size_t BIO_ctrl_pending(BIO *b);
+size_t BIO_ctrl_wpending(BIO *b);
+# define BIO_flush(b) (int)BIO_ctrl(b,BIO_CTRL_FLUSH,0,NULL)
+# define BIO_get_info_callback(b,cbp) (int)BIO_ctrl(b,BIO_CTRL_GET_CALLBACK,0, \
+ cbp)
+# define BIO_set_info_callback(b,cb) (int)BIO_callback_ctrl(b,BIO_CTRL_SET_CALLBACK,cb)
+
+/* For the BIO_f_buffer() type */
+# define BIO_buffer_get_num_lines(b) BIO_ctrl(b,BIO_CTRL_GET,0,NULL)
+# define BIO_buffer_peek(b,s,l) BIO_ctrl(b,BIO_CTRL_PEEK,(l),(s))
+
+/* For BIO_s_bio() */
+# define BIO_set_write_buf_size(b,size) (int)BIO_ctrl(b,BIO_C_SET_WRITE_BUF_SIZE,size,NULL)
+# define BIO_get_write_buf_size(b,size) (size_t)BIO_ctrl(b,BIO_C_GET_WRITE_BUF_SIZE,size,NULL)
+# define BIO_make_bio_pair(b1,b2) (int)BIO_ctrl(b1,BIO_C_MAKE_BIO_PAIR,0,b2)
+# define BIO_destroy_bio_pair(b) (int)BIO_ctrl(b,BIO_C_DESTROY_BIO_PAIR,0,NULL)
+# define BIO_shutdown_wr(b) (int)BIO_ctrl(b, BIO_C_SHUTDOWN_WR, 0, NULL)
+/* macros with inappropriate type -- but ...pending macros use int too: */
+# define BIO_get_write_guarantee(b) (int)BIO_ctrl(b,BIO_C_GET_WRITE_GUARANTEE,0,NULL)
+# define BIO_get_read_request(b) (int)BIO_ctrl(b,BIO_C_GET_READ_REQUEST,0,NULL)
+size_t BIO_ctrl_get_write_guarantee(BIO *b);
+size_t BIO_ctrl_get_read_request(BIO *b);
+int BIO_ctrl_reset_read_request(BIO *b);
+
+/* ctrl macros for dgram */
+# define BIO_ctrl_dgram_connect(b,peer) \
+ (int)BIO_ctrl(b,BIO_CTRL_DGRAM_CONNECT,0, (char *)(peer))
+# define BIO_ctrl_set_connected(b,peer) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_CONNECTED, 0, (char *)(peer))
+# define BIO_dgram_recv_timedout(b) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP, 0, NULL)
+# define BIO_dgram_send_timedout(b) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP, 0, NULL)
+# define BIO_dgram_get_peer(b,peer) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_GET_PEER, 0, (char *)(peer))
+# define BIO_dgram_set_peer(b,peer) \
+ (int)BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, (char *)(peer))
+# define BIO_dgram_get_mtu_overhead(b) \
+ (unsigned int)BIO_ctrl((b), BIO_CTRL_DGRAM_GET_MTU_OVERHEAD, 0, NULL)
+
+/* ctrl macros for BIO_f_prefix */
+# define BIO_set_prefix(b,p) BIO_ctrl((b), BIO_CTRL_SET_PREFIX, 0, (void *)(p))
+# define BIO_set_indent(b,i) BIO_ctrl((b), BIO_CTRL_SET_INDENT, (i), NULL)
+# define BIO_get_indent(b) BIO_ctrl((b), BIO_CTRL_GET_INDENT, 0, NULL)
+
+#define BIO_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_BIO, l, p, newf, dupf, freef)
+int BIO_set_ex_data(BIO *bio, int idx, void *data);
+void *BIO_get_ex_data(const BIO *bio, int idx);
+uint64_t BIO_number_read(BIO *bio);
+uint64_t BIO_number_written(BIO *bio);
+
+/* For BIO_f_asn1() */
+int BIO_asn1_set_prefix(BIO *b, asn1_ps_func *prefix,
+ asn1_ps_func *prefix_free);
+int BIO_asn1_get_prefix(BIO *b, asn1_ps_func **pprefix,
+ asn1_ps_func **pprefix_free);
+int BIO_asn1_set_suffix(BIO *b, asn1_ps_func *suffix,
+ asn1_ps_func *suffix_free);
+int BIO_asn1_get_suffix(BIO *b, asn1_ps_func **psuffix,
+ asn1_ps_func **psuffix_free);
+
+const BIO_METHOD *BIO_s_file(void);
+BIO *BIO_new_file(const char *filename, const char *mode);
+BIO *BIO_new_from_core_bio(OSSL_LIB_CTX *libctx, OSSL_CORE_BIO *corebio);
+# ifndef OPENSSL_NO_STDIO
+BIO *BIO_new_fp(FILE *stream, int close_flag);
+# endif
+BIO *BIO_new_ex(OSSL_LIB_CTX *libctx, const BIO_METHOD *method);
+BIO *BIO_new(const BIO_METHOD *type);
+int BIO_free(BIO *a);
+void BIO_set_data(BIO *a, void *ptr);
+void *BIO_get_data(BIO *a);
+void BIO_set_init(BIO *a, int init);
+int BIO_get_init(BIO *a);
+void BIO_set_shutdown(BIO *a, int shut);
+int BIO_get_shutdown(BIO *a);
+void BIO_vfree(BIO *a);
+int BIO_up_ref(BIO *a);
+int BIO_read(BIO *b, void *data, int dlen);
+int BIO_read_ex(BIO *b, void *data, size_t dlen, size_t *readbytes);
+int BIO_gets(BIO *bp, char *buf, int size);
+int BIO_get_line(BIO *bio, char *buf, int size);
+int BIO_write(BIO *b, const void *data, int dlen);
+int BIO_write_ex(BIO *b, const void *data, size_t dlen, size_t *written);
+int BIO_puts(BIO *bp, const char *buf);
+int BIO_indent(BIO *b, int indent, int max);
+long BIO_ctrl(BIO *bp, int cmd, long larg, void *parg);
+long BIO_callback_ctrl(BIO *b, int cmd, BIO_info_cb *fp);
+void *BIO_ptr_ctrl(BIO *bp, int cmd, long larg);
+long BIO_int_ctrl(BIO *bp, int cmd, long larg, int iarg);
+BIO *BIO_push(BIO *b, BIO *append);
+BIO *BIO_pop(BIO *b);
+void BIO_free_all(BIO *a);
+BIO *BIO_find_type(BIO *b, int bio_type);
+BIO *BIO_next(BIO *b);
+void BIO_set_next(BIO *b, BIO *next);
+BIO *BIO_get_retry_BIO(BIO *bio, int *reason);
+int BIO_get_retry_reason(BIO *bio);
+void BIO_set_retry_reason(BIO *bio, int reason);
+BIO *BIO_dup_chain(BIO *in);
+
+int BIO_nread0(BIO *bio, char **buf);
+int BIO_nread(BIO *bio, char **buf, int num);
+int BIO_nwrite0(BIO *bio, char **buf);
+int BIO_nwrite(BIO *bio, char **buf, int num);
+
+const BIO_METHOD *BIO_s_mem(void);
+const BIO_METHOD *BIO_s_secmem(void);
+BIO *BIO_new_mem_buf(const void *buf, int len);
+# ifndef OPENSSL_NO_SOCK
+const BIO_METHOD *BIO_s_socket(void);
+const BIO_METHOD *BIO_s_connect(void);
+const BIO_METHOD *BIO_s_accept(void);
+# endif
+const BIO_METHOD *BIO_s_fd(void);
+const BIO_METHOD *BIO_s_log(void);
+const BIO_METHOD *BIO_s_bio(void);
+const BIO_METHOD *BIO_s_null(void);
+const BIO_METHOD *BIO_f_null(void);
+const BIO_METHOD *BIO_f_buffer(void);
+const BIO_METHOD *BIO_f_readbuffer(void);
+const BIO_METHOD *BIO_f_linebuffer(void);
+const BIO_METHOD *BIO_f_nbio_test(void);
+const BIO_METHOD *BIO_f_prefix(void);
+const BIO_METHOD *BIO_s_core(void);
+# ifndef OPENSSL_NO_DGRAM
+const BIO_METHOD *BIO_s_datagram(void);
+int BIO_dgram_non_fatal_error(int error);
+BIO *BIO_new_dgram(int fd, int close_flag);
+# ifndef OPENSSL_NO_SCTP
+const BIO_METHOD *BIO_s_datagram_sctp(void);
+BIO *BIO_new_dgram_sctp(int fd, int close_flag);
+int BIO_dgram_is_sctp(BIO *bio);
+int BIO_dgram_sctp_notification_cb(BIO *b,
+ BIO_dgram_sctp_notification_handler_fn handle_notifications,
+ void *context);
+int BIO_dgram_sctp_wait_for_dry(BIO *b);
+int BIO_dgram_sctp_msg_waiting(BIO *b);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_SOCK
+int BIO_sock_should_retry(int i);
+int BIO_sock_non_fatal_error(int error);
+int BIO_socket_wait(int fd, int for_read, time_t max_time);
+# endif
+int BIO_wait(BIO *bio, time_t max_time, unsigned int nap_milliseconds);
+int BIO_do_connect_retry(BIO *bio, int timeout, int nap_milliseconds);
+
+int BIO_fd_should_retry(int i);
+int BIO_fd_non_fatal_error(int error);
+int BIO_dump_cb(int (*cb) (const void *data, size_t len, void *u),
+ void *u, const void *s, int len);
+int BIO_dump_indent_cb(int (*cb) (const void *data, size_t len, void *u),
+ void *u, const void *s, int len, int indent);
+int BIO_dump(BIO *b, const void *bytes, int len);
+int BIO_dump_indent(BIO *b, const void *bytes, int len, int indent);
+# ifndef OPENSSL_NO_STDIO
+int BIO_dump_fp(FILE *fp, const void *s, int len);
+int BIO_dump_indent_fp(FILE *fp, const void *s, int len, int indent);
+# endif
+int BIO_hex_string(BIO *out, int indent, int width, const void *data,
+ int datalen);
+
+# ifndef OPENSSL_NO_SOCK
+BIO_ADDR *BIO_ADDR_new(void);
+int BIO_ADDR_rawmake(BIO_ADDR *ap, int family,
+ const void *where, size_t wherelen, unsigned short port);
+void BIO_ADDR_free(BIO_ADDR *);
+void BIO_ADDR_clear(BIO_ADDR *ap);
+int BIO_ADDR_family(const BIO_ADDR *ap);
+int BIO_ADDR_rawaddress(const BIO_ADDR *ap, void *p, size_t *l);
+unsigned short BIO_ADDR_rawport(const BIO_ADDR *ap);
+char *BIO_ADDR_hostname_string(const BIO_ADDR *ap, int numeric);
+char *BIO_ADDR_service_string(const BIO_ADDR *ap, int numeric);
+char *BIO_ADDR_path_string(const BIO_ADDR *ap);
+
+const BIO_ADDRINFO *BIO_ADDRINFO_next(const BIO_ADDRINFO *bai);
+int BIO_ADDRINFO_family(const BIO_ADDRINFO *bai);
+int BIO_ADDRINFO_socktype(const BIO_ADDRINFO *bai);
+int BIO_ADDRINFO_protocol(const BIO_ADDRINFO *bai);
+const BIO_ADDR *BIO_ADDRINFO_address(const BIO_ADDRINFO *bai);
+void BIO_ADDRINFO_free(BIO_ADDRINFO *bai);
+
+enum BIO_hostserv_priorities {
+ BIO_PARSE_PRIO_HOST, BIO_PARSE_PRIO_SERV
+};
+int BIO_parse_hostserv(const char *hostserv, char **host, char **service,
+ enum BIO_hostserv_priorities hostserv_prio);
+enum BIO_lookup_type {
+ BIO_LOOKUP_CLIENT, BIO_LOOKUP_SERVER
+};
+int BIO_lookup(const char *host, const char *service,
+ enum BIO_lookup_type lookup_type,
+ int family, int socktype, BIO_ADDRINFO **res);
+int BIO_lookup_ex(const char *host, const char *service,
+ int lookup_type, int family, int socktype, int protocol,
+ BIO_ADDRINFO **res);
+int BIO_sock_error(int sock);
+int BIO_socket_ioctl(int fd, long type, void *arg);
+int BIO_socket_nbio(int fd, int mode);
+int BIO_sock_init(void);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define BIO_sock_cleanup() while(0) continue
+# endif
+int BIO_set_tcp_ndelay(int sock, int turn_on);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 struct hostent *BIO_gethostbyname(const char *name);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_get_port(const char *str, unsigned short *port_ptr);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_get_host_ip(const char *str, unsigned char *ip);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_get_accept_socket(char *host_port, int mode);
+OSSL_DEPRECATEDIN_1_1_0 int BIO_accept(int sock, char **ip_port);
+# endif
+
+union BIO_sock_info_u {
+ BIO_ADDR *addr;
+};
+enum BIO_sock_info_type {
+ BIO_SOCK_INFO_ADDRESS
+};
+int BIO_sock_info(int sock,
+ enum BIO_sock_info_type type, union BIO_sock_info_u *info);
+
+# define BIO_SOCK_REUSEADDR 0x01
+# define BIO_SOCK_V6_ONLY 0x02
+# define BIO_SOCK_KEEPALIVE 0x04
+# define BIO_SOCK_NONBLOCK 0x08
+# define BIO_SOCK_NODELAY 0x10
+
+int BIO_socket(int domain, int socktype, int protocol, int options);
+int BIO_connect(int sock, const BIO_ADDR *addr, int options);
+int BIO_bind(int sock, const BIO_ADDR *addr, int options);
+int BIO_listen(int sock, const BIO_ADDR *addr, int options);
+int BIO_accept_ex(int accept_sock, BIO_ADDR *addr, int options);
+int BIO_closesocket(int sock);
+
+BIO *BIO_new_socket(int sock, int close_flag);
+BIO *BIO_new_connect(const char *host_port);
+BIO *BIO_new_accept(const char *host_port);
+# endif /* OPENSSL_NO_SOCK*/
+
+BIO *BIO_new_fd(int fd, int close_flag);
+
+int BIO_new_bio_pair(BIO **bio1, size_t writebuf1,
+ BIO **bio2, size_t writebuf2);
+/*
+ * If successful, returns 1 and in *bio1, *bio2 two BIO pair endpoints.
+ * Otherwise returns 0 and sets *bio1 and *bio2 to NULL. Size 0 uses default
+ * value.
+ */
+
+void BIO_copy_next_retry(BIO *b);
+
+/*
+ * long BIO_ghbn_ctrl(int cmd,int iarg,char *parg);
+ */
+
+# define ossl_bio__attr__(x)
+# if defined(__GNUC__) && defined(__STDC_VERSION__) \
+ && !defined(__APPLE__)
+ /*
+ * Because we support the 'z' modifier, which made its appearance in C99,
+ * we can't use __attribute__ with pre C99 dialects.
+ */
+# if __STDC_VERSION__ >= 199901L
+# undef ossl_bio__attr__
+# define ossl_bio__attr__ __attribute__
+# if __GNUC__*10 + __GNUC_MINOR__ >= 44
+# define ossl_bio__printf__ __gnu_printf__
+# else
+# define ossl_bio__printf__ __printf__
+# endif
+# endif
+# endif
+int BIO_printf(BIO *bio, const char *format, ...)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 3)));
+int BIO_vprintf(BIO *bio, const char *format, va_list args)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 2, 0)));
+int BIO_snprintf(char *buf, size_t n, const char *format, ...)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 4)));
+int BIO_vsnprintf(char *buf, size_t n, const char *format, va_list args)
+ossl_bio__attr__((__format__(ossl_bio__printf__, 3, 0)));
+# undef ossl_bio__attr__
+# undef ossl_bio__printf__
+
+
+BIO_METHOD *BIO_meth_new(int type, const char *name);
+void BIO_meth_free(BIO_METHOD *biom);
+int (*BIO_meth_get_write(const BIO_METHOD *biom)) (BIO *, const char *, int);
+int (*BIO_meth_get_write_ex(const BIO_METHOD *biom)) (BIO *, const char *, size_t,
+ size_t *);
+int BIO_meth_set_write(BIO_METHOD *biom,
+ int (*write) (BIO *, const char *, int));
+int BIO_meth_set_write_ex(BIO_METHOD *biom,
+ int (*bwrite) (BIO *, const char *, size_t, size_t *));
+int (*BIO_meth_get_read(const BIO_METHOD *biom)) (BIO *, char *, int);
+int (*BIO_meth_get_read_ex(const BIO_METHOD *biom)) (BIO *, char *, size_t, size_t *);
+int BIO_meth_set_read(BIO_METHOD *biom,
+ int (*read) (BIO *, char *, int));
+int BIO_meth_set_read_ex(BIO_METHOD *biom,
+ int (*bread) (BIO *, char *, size_t, size_t *));
+int (*BIO_meth_get_puts(const BIO_METHOD *biom)) (BIO *, const char *);
+int BIO_meth_set_puts(BIO_METHOD *biom,
+ int (*puts) (BIO *, const char *));
+int (*BIO_meth_get_gets(const BIO_METHOD *biom)) (BIO *, char *, int);
+int BIO_meth_set_gets(BIO_METHOD *biom,
+ int (*gets) (BIO *, char *, int));
+long (*BIO_meth_get_ctrl(const BIO_METHOD *biom)) (BIO *, int, long, void *);
+int BIO_meth_set_ctrl(BIO_METHOD *biom,
+ long (*ctrl) (BIO *, int, long, void *));
+int (*BIO_meth_get_create(const BIO_METHOD *bion)) (BIO *);
+int BIO_meth_set_create(BIO_METHOD *biom, int (*create) (BIO *));
+int (*BIO_meth_get_destroy(const BIO_METHOD *biom)) (BIO *);
+int BIO_meth_set_destroy(BIO_METHOD *biom, int (*destroy) (BIO *));
+long (*BIO_meth_get_callback_ctrl(const BIO_METHOD *biom))
+ (BIO *, int, BIO_info_cb *);
+int BIO_meth_set_callback_ctrl(BIO_METHOD *biom,
+ long (*callback_ctrl) (BIO *, int,
+ BIO_info_cb *));
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/bioerr.h b/include/openssl/bioerr.h
new file mode 100644
index 00000000..787b30af
--- /dev/null
+++ b/include/openssl/bioerr.h
@@ -0,0 +1,65 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_BIOERR_H
+# define OPENSSL_BIOERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * BIO reason codes.
+ */
+# define BIO_R_ACCEPT_ERROR 100
+# define BIO_R_ADDRINFO_ADDR_IS_NOT_AF_INET 141
+# define BIO_R_AMBIGUOUS_HOST_OR_SERVICE 129
+# define BIO_R_BAD_FOPEN_MODE 101
+# define BIO_R_BROKEN_PIPE 124
+# define BIO_R_CONNECT_ERROR 103
+# define BIO_R_CONNECT_TIMEOUT 147
+# define BIO_R_GETHOSTBYNAME_ADDR_IS_NOT_AF_INET 107
+# define BIO_R_GETSOCKNAME_ERROR 132
+# define BIO_R_GETSOCKNAME_TRUNCATED_ADDRESS 133
+# define BIO_R_GETTING_SOCKTYPE 134
+# define BIO_R_INVALID_ARGUMENT 125
+# define BIO_R_INVALID_SOCKET 135
+# define BIO_R_IN_USE 123
+# define BIO_R_LENGTH_TOO_LONG 102
+# define BIO_R_LISTEN_V6_ONLY 136
+# define BIO_R_LOOKUP_RETURNED_NOTHING 142
+# define BIO_R_MALFORMED_HOST_OR_SERVICE 130
+# define BIO_R_NBIO_CONNECT_ERROR 110
+# define BIO_R_NO_ACCEPT_ADDR_OR_SERVICE_SPECIFIED 143
+# define BIO_R_NO_HOSTNAME_OR_SERVICE_SPECIFIED 144
+# define BIO_R_NO_PORT_DEFINED 113
+# define BIO_R_NO_SUCH_FILE 128
+# define BIO_R_NULL_PARAMETER 115 /* unused */
+# define BIO_R_TRANSFER_ERROR 104
+# define BIO_R_TRANSFER_TIMEOUT 105
+# define BIO_R_UNABLE_TO_BIND_SOCKET 117
+# define BIO_R_UNABLE_TO_CREATE_SOCKET 118
+# define BIO_R_UNABLE_TO_KEEPALIVE 137
+# define BIO_R_UNABLE_TO_LISTEN_SOCKET 119
+# define BIO_R_UNABLE_TO_NODELAY 138
+# define BIO_R_UNABLE_TO_REUSEADDR 139
+# define BIO_R_UNAVAILABLE_IP_FAMILY 145
+# define BIO_R_UNINITIALIZED 120
+# define BIO_R_UNKNOWN_INFO_TYPE 140
+# define BIO_R_UNSUPPORTED_IP_FAMILY 146
+# define BIO_R_UNSUPPORTED_METHOD 121
+# define BIO_R_UNSUPPORTED_PROTOCOL_FAMILY 131
+# define BIO_R_WRITE_TO_READ_ONLY_BIO 126
+# define BIO_R_WSASTARTUP 122
+
+#endif
diff --git a/include/openssl/blowfish.h b/include/openssl/blowfish.h
new file mode 100644
index 00000000..667d6423
--- /dev/null
+++ b/include/openssl/blowfish.h
@@ -0,0 +1,78 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_BLOWFISH_H
+# define OPENSSL_BLOWFISH_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_BLOWFISH_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_BF
+# include <openssl/e_os2.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define BF_BLOCK 8
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+# define BF_ENCRYPT 1
+# define BF_DECRYPT 0
+
+/*-
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ * ! BF_LONG has to be at least 32 bits wide. !
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ */
+# define BF_LONG unsigned int
+
+# define BF_ROUNDS 16
+
+typedef struct bf_key_st {
+ BF_LONG P[BF_ROUNDS + 2];
+ BF_LONG S[4 * 256];
+} BF_KEY;
+
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void BF_set_key(BF_KEY *key, int len,
+ const unsigned char *data);
+OSSL_DEPRECATEDIN_3_0 void BF_encrypt(BF_LONG *data, const BF_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void BF_decrypt(BF_LONG *data, const BF_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void BF_ecb_encrypt(const unsigned char *in,
+ unsigned char *out, const BF_KEY *key,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void BF_cbc_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ const BF_KEY *schedule,
+ unsigned char *ivec, int enc);
+OSSL_DEPRECATEDIN_3_0 void BF_cfb64_encrypt(const unsigned char *in,
+ unsigned char *out,
+ long length, const BF_KEY *schedule,
+ unsigned char *ivec, int *num,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void BF_ofb64_encrypt(const unsigned char *in,
+ unsigned char *out,
+ long length, const BF_KEY *schedule,
+ unsigned char *ivec, int *num);
+OSSL_DEPRECATEDIN_3_0 const char *BF_options(void);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/bn.h b/include/openssl/bn.h
new file mode 100644
index 00000000..ecd7f01b
--- /dev/null
+++ b/include/openssl/bn.h
@@ -0,0 +1,583 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_BN_H
+# define OPENSSL_BN_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_BN_H
+# endif
+
+# include <openssl/e_os2.h>
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+# include <openssl/opensslconf.h>
+# include <openssl/types.h>
+# include <openssl/crypto.h>
+# include <openssl/bnerr.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * 64-bit processor with LP64 ABI
+ */
+# ifdef SIXTY_FOUR_BIT_LONG
+# define BN_ULONG unsigned long
+# define BN_BYTES 8
+# endif
+
+/*
+ * 64-bit processor other than LP64 ABI
+ */
+# ifdef SIXTY_FOUR_BIT
+# define BN_ULONG unsigned long long
+# define BN_BYTES 8
+# endif
+
+# ifdef THIRTY_TWO_BIT
+# define BN_ULONG unsigned int
+# define BN_BYTES 4
+# endif
+
+# define BN_BITS2 (BN_BYTES * 8)
+# define BN_BITS (BN_BITS2 * 2)
+# define BN_TBIT ((BN_ULONG)1 << (BN_BITS2 - 1))
+
+# define BN_FLG_MALLOCED 0x01
+# define BN_FLG_STATIC_DATA 0x02
+
+/*
+ * avoid leaking exponent information through timing,
+ * BN_mod_exp_mont() will call BN_mod_exp_mont_consttime,
+ * BN_div() will call BN_div_no_branch,
+ * BN_mod_inverse() will call bn_mod_inverse_no_branch.
+ */
+# define BN_FLG_CONSTTIME 0x04
+# define BN_FLG_SECURE 0x08
+
+# ifndef OPENSSL_NO_DEPRECATED_0_9_8
+/* deprecated name for the flag */
+# define BN_FLG_EXP_CONSTTIME BN_FLG_CONSTTIME
+# define BN_FLG_FREE 0x8000 /* used for debugging */
+# endif
+
+void BN_set_flags(BIGNUM *b, int n);
+int BN_get_flags(const BIGNUM *b, int n);
+
+/* Values for |top| in BN_rand() */
+#define BN_RAND_TOP_ANY -1
+#define BN_RAND_TOP_ONE 0
+#define BN_RAND_TOP_TWO 1
+
+/* Values for |bottom| in BN_rand() */
+#define BN_RAND_BOTTOM_ANY 0
+#define BN_RAND_BOTTOM_ODD 1
+
+/*
+ * get a clone of a BIGNUM with changed flags, for *temporary* use only (the
+ * two BIGNUMs cannot be used in parallel!). Also only for *read only* use. The
+ * value |dest| should be a newly allocated BIGNUM obtained via BN_new() that
+ * has not been otherwise initialised or used.
+ */
+void BN_with_flags(BIGNUM *dest, const BIGNUM *b, int flags);
+
+/* Wrapper function to make using BN_GENCB easier */
+int BN_GENCB_call(BN_GENCB *cb, int a, int b);
+
+BN_GENCB *BN_GENCB_new(void);
+void BN_GENCB_free(BN_GENCB *cb);
+
+/* Populate a BN_GENCB structure with an "old"-style callback */
+void BN_GENCB_set_old(BN_GENCB *gencb, void (*callback) (int, int, void *),
+ void *cb_arg);
+
+/* Populate a BN_GENCB structure with a "new"-style callback */
+void BN_GENCB_set(BN_GENCB *gencb, int (*callback) (int, int, BN_GENCB *),
+ void *cb_arg);
+
+void *BN_GENCB_get_arg(BN_GENCB *cb);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define BN_prime_checks 0 /* default: select number of iterations based
+ * on the size of the number */
+
+/*
+ * BN_prime_checks_for_size() returns the number of Miller-Rabin iterations
+ * that will be done for checking that a random number is probably prime. The
+ * error rate for accepting a composite number as prime depends on the size of
+ * the prime |b|. The error rates used are for calculating an RSA key with 2 primes,
+ * and so the level is what you would expect for a key of double the size of the
+ * prime.
+ *
+ * This table is generated using the algorithm of FIPS PUB 186-4
+ * Digital Signature Standard (DSS), section F.1, page 117.
+ * (https://dx.doi.org/10.6028/NIST.FIPS.186-4)
+ *
+ * The following magma script was used to generate the output:
+ * securitybits:=125;
+ * k:=1024;
+ * for t:=1 to 65 do
+ * for M:=3 to Floor(2*Sqrt(k-1)-1) do
+ * S:=0;
+ * // Sum over m
+ * for m:=3 to M do
+ * s:=0;
+ * // Sum over j
+ * for j:=2 to m do
+ * s+:=(RealField(32)!2)^-(j+(k-1)/j);
+ * end for;
+ * S+:=2^(m-(m-1)*t)*s;
+ * end for;
+ * A:=2^(k-2-M*t);
+ * B:=8*(Pi(RealField(32))^2-6)/3*2^(k-2)*S;
+ * pkt:=2.00743*Log(2)*k*2^-k*(A+B);
+ * seclevel:=Floor(-Log(2,pkt));
+ * if seclevel ge securitybits then
+ * printf "k: %5o, security: %o bits (t: %o, M: %o)\n",k,seclevel,t,M;
+ * break;
+ * end if;
+ * end for;
+ * if seclevel ge securitybits then break; end if;
+ * end for;
+ *
+ * It can be run online at:
+ * http://magma.maths.usyd.edu.au/calc
+ *
+ * And will output:
+ * k: 1024, security: 129 bits (t: 6, M: 23)
+ *
+ * k is the number of bits of the prime, securitybits is the level we want to
+ * reach.
+ *
+ * prime length | RSA key size | # MR tests | security level
+ * -------------+--------------|------------+---------------
+ * (b) >= 6394 | >= 12788 | 3 | 256 bit
+ * (b) >= 3747 | >= 7494 | 3 | 192 bit
+ * (b) >= 1345 | >= 2690 | 4 | 128 bit
+ * (b) >= 1080 | >= 2160 | 5 | 128 bit
+ * (b) >= 852 | >= 1704 | 5 | 112 bit
+ * (b) >= 476 | >= 952 | 5 | 80 bit
+ * (b) >= 400 | >= 800 | 6 | 80 bit
+ * (b) >= 347 | >= 694 | 7 | 80 bit
+ * (b) >= 308 | >= 616 | 8 | 80 bit
+ * (b) >= 55 | >= 110 | 27 | 64 bit
+ * (b) >= 6 | >= 12 | 34 | 64 bit
+ */
+
+# define BN_prime_checks_for_size(b) ((b) >= 3747 ? 3 : \
+ (b) >= 1345 ? 4 : \
+ (b) >= 476 ? 5 : \
+ (b) >= 400 ? 6 : \
+ (b) >= 347 ? 7 : \
+ (b) >= 308 ? 8 : \
+ (b) >= 55 ? 27 : \
+ /* b >= 6 */ 34)
+# endif
+
+# define BN_num_bytes(a) ((BN_num_bits(a)+7)/8)
+
+int BN_abs_is_word(const BIGNUM *a, const BN_ULONG w);
+int BN_is_zero(const BIGNUM *a);
+int BN_is_one(const BIGNUM *a);
+int BN_is_word(const BIGNUM *a, const BN_ULONG w);
+int BN_is_odd(const BIGNUM *a);
+
+# define BN_one(a) (BN_set_word((a),1))
+
+void BN_zero_ex(BIGNUM *a);
+
+# if OPENSSL_API_LEVEL > 908
+# define BN_zero(a) BN_zero_ex(a)
+# else
+# define BN_zero(a) (BN_set_word((a),0))
+# endif
+
+const BIGNUM *BN_value_one(void);
+char *BN_options(void);
+BN_CTX *BN_CTX_new_ex(OSSL_LIB_CTX *ctx);
+BN_CTX *BN_CTX_new(void);
+BN_CTX *BN_CTX_secure_new_ex(OSSL_LIB_CTX *ctx);
+BN_CTX *BN_CTX_secure_new(void);
+void BN_CTX_free(BN_CTX *c);
+void BN_CTX_start(BN_CTX *ctx);
+BIGNUM *BN_CTX_get(BN_CTX *ctx);
+void BN_CTX_end(BN_CTX *ctx);
+int BN_rand_ex(BIGNUM *rnd, int bits, int top, int bottom,
+ unsigned int strength, BN_CTX *ctx);
+int BN_rand(BIGNUM *rnd, int bits, int top, int bottom);
+int BN_priv_rand_ex(BIGNUM *rnd, int bits, int top, int bottom,
+ unsigned int strength, BN_CTX *ctx);
+int BN_priv_rand(BIGNUM *rnd, int bits, int top, int bottom);
+int BN_rand_range_ex(BIGNUM *r, const BIGNUM *range, unsigned int strength,
+ BN_CTX *ctx);
+int BN_rand_range(BIGNUM *rnd, const BIGNUM *range);
+int BN_priv_rand_range_ex(BIGNUM *r, const BIGNUM *range,
+ unsigned int strength, BN_CTX *ctx);
+int BN_priv_rand_range(BIGNUM *rnd, const BIGNUM *range);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int BN_pseudo_rand(BIGNUM *rnd, int bits, int top, int bottom);
+OSSL_DEPRECATEDIN_3_0
+int BN_pseudo_rand_range(BIGNUM *rnd, const BIGNUM *range);
+# endif
+int BN_num_bits(const BIGNUM *a);
+int BN_num_bits_word(BN_ULONG l);
+int BN_security_bits(int L, int N);
+BIGNUM *BN_new(void);
+BIGNUM *BN_secure_new(void);
+void BN_clear_free(BIGNUM *a);
+BIGNUM *BN_copy(BIGNUM *a, const BIGNUM *b);
+void BN_swap(BIGNUM *a, BIGNUM *b);
+BIGNUM *BN_bin2bn(const unsigned char *s, int len, BIGNUM *ret);
+int BN_bn2bin(const BIGNUM *a, unsigned char *to);
+int BN_bn2binpad(const BIGNUM *a, unsigned char *to, int tolen);
+BIGNUM *BN_lebin2bn(const unsigned char *s, int len, BIGNUM *ret);
+int BN_bn2lebinpad(const BIGNUM *a, unsigned char *to, int tolen);
+BIGNUM *BN_native2bn(const unsigned char *s, int len, BIGNUM *ret);
+int BN_bn2nativepad(const BIGNUM *a, unsigned char *to, int tolen);
+BIGNUM *BN_mpi2bn(const unsigned char *s, int len, BIGNUM *ret);
+int BN_bn2mpi(const BIGNUM *a, unsigned char *to);
+int BN_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
+int BN_usub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
+int BN_uadd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
+int BN_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
+int BN_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
+int BN_sqr(BIGNUM *r, const BIGNUM *a, BN_CTX *ctx);
+/** BN_set_negative sets sign of a BIGNUM
+ * \param b pointer to the BIGNUM object
+ * \param n 0 if the BIGNUM b should be positive and a value != 0 otherwise
+ */
+void BN_set_negative(BIGNUM *b, int n);
+/** BN_is_negative returns 1 if the BIGNUM is negative
+ * \param b pointer to the BIGNUM object
+ * \return 1 if a < 0 and 0 otherwise
+ */
+int BN_is_negative(const BIGNUM *b);
+
+int BN_div(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m, const BIGNUM *d,
+ BN_CTX *ctx);
+# define BN_mod(rem,m,d,ctx) BN_div(NULL,(rem),(m),(d),(ctx))
+int BN_nnmod(BIGNUM *r, const BIGNUM *m, const BIGNUM *d, BN_CTX *ctx);
+int BN_mod_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
+ BN_CTX *ctx);
+int BN_mod_add_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const BIGNUM *m);
+int BN_mod_sub(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
+ BN_CTX *ctx);
+int BN_mod_sub_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const BIGNUM *m);
+int BN_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, const BIGNUM *m,
+ BN_CTX *ctx);
+int BN_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
+int BN_mod_lshift1(BIGNUM *r, const BIGNUM *a, const BIGNUM *m, BN_CTX *ctx);
+int BN_mod_lshift1_quick(BIGNUM *r, const BIGNUM *a, const BIGNUM *m);
+int BN_mod_lshift(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m,
+ BN_CTX *ctx);
+int BN_mod_lshift_quick(BIGNUM *r, const BIGNUM *a, int n, const BIGNUM *m);
+
+BN_ULONG BN_mod_word(const BIGNUM *a, BN_ULONG w);
+BN_ULONG BN_div_word(BIGNUM *a, BN_ULONG w);
+int BN_mul_word(BIGNUM *a, BN_ULONG w);
+int BN_add_word(BIGNUM *a, BN_ULONG w);
+int BN_sub_word(BIGNUM *a, BN_ULONG w);
+int BN_set_word(BIGNUM *a, BN_ULONG w);
+BN_ULONG BN_get_word(const BIGNUM *a);
+
+int BN_cmp(const BIGNUM *a, const BIGNUM *b);
+void BN_free(BIGNUM *a);
+int BN_is_bit_set(const BIGNUM *a, int n);
+int BN_lshift(BIGNUM *r, const BIGNUM *a, int n);
+int BN_lshift1(BIGNUM *r, const BIGNUM *a);
+int BN_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+
+int BN_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
+ const BIGNUM *m, BN_CTX *ctx);
+int BN_mod_exp_mont(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
+ const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
+int BN_mod_exp_mont_consttime(BIGNUM *rr, const BIGNUM *a, const BIGNUM *p,
+ const BIGNUM *m, BN_CTX *ctx,
+ BN_MONT_CTX *in_mont);
+int BN_mod_exp_mont_word(BIGNUM *r, BN_ULONG a, const BIGNUM *p,
+ const BIGNUM *m, BN_CTX *ctx, BN_MONT_CTX *m_ctx);
+int BN_mod_exp2_mont(BIGNUM *r, const BIGNUM *a1, const BIGNUM *p1,
+ const BIGNUM *a2, const BIGNUM *p2, const BIGNUM *m,
+ BN_CTX *ctx, BN_MONT_CTX *m_ctx);
+int BN_mod_exp_simple(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
+ const BIGNUM *m, BN_CTX *ctx);
+int BN_mod_exp_mont_consttime_x2(BIGNUM *rr1, const BIGNUM *a1, const BIGNUM *p1,
+ const BIGNUM *m1, BN_MONT_CTX *in_mont1,
+ BIGNUM *rr2, const BIGNUM *a2, const BIGNUM *p2,
+ const BIGNUM *m2, BN_MONT_CTX *in_mont2,
+ BN_CTX *ctx);
+
+int BN_mask_bits(BIGNUM *a, int n);
+# ifndef OPENSSL_NO_STDIO
+int BN_print_fp(FILE *fp, const BIGNUM *a);
+# endif
+int BN_print(BIO *bio, const BIGNUM *a);
+int BN_reciprocal(BIGNUM *r, const BIGNUM *m, int len, BN_CTX *ctx);
+int BN_rshift(BIGNUM *r, const BIGNUM *a, int n);
+int BN_rshift1(BIGNUM *r, const BIGNUM *a);
+void BN_clear(BIGNUM *a);
+BIGNUM *BN_dup(const BIGNUM *a);
+int BN_ucmp(const BIGNUM *a, const BIGNUM *b);
+int BN_set_bit(BIGNUM *a, int n);
+int BN_clear_bit(BIGNUM *a, int n);
+char *BN_bn2hex(const BIGNUM *a);
+char *BN_bn2dec(const BIGNUM *a);
+int BN_hex2bn(BIGNUM **a, const char *str);
+int BN_dec2bn(BIGNUM **a, const char *str);
+int BN_asc2bn(BIGNUM **a, const char *str);
+int BN_gcd(BIGNUM *r, const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx);
+int BN_kronecker(const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx); /* returns
+ * -2 for
+ * error */
+BIGNUM *BN_mod_inverse(BIGNUM *ret,
+ const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
+BIGNUM *BN_mod_sqrt(BIGNUM *ret,
+ const BIGNUM *a, const BIGNUM *n, BN_CTX *ctx);
+
+void BN_consttime_swap(BN_ULONG swap, BIGNUM *a, BIGNUM *b, int nwords);
+
+/* Deprecated versions */
+# ifndef OPENSSL_NO_DEPRECATED_0_9_8
+OSSL_DEPRECATEDIN_0_9_8
+BIGNUM *BN_generate_prime(BIGNUM *ret, int bits, int safe,
+ const BIGNUM *add, const BIGNUM *rem,
+ void (*callback) (int, int, void *),
+ void *cb_arg);
+OSSL_DEPRECATEDIN_0_9_8
+int BN_is_prime(const BIGNUM *p, int nchecks,
+ void (*callback) (int, int, void *),
+ BN_CTX *ctx, void *cb_arg);
+OSSL_DEPRECATEDIN_0_9_8
+int BN_is_prime_fasttest(const BIGNUM *p, int nchecks,
+ void (*callback) (int, int, void *),
+ BN_CTX *ctx, void *cb_arg,
+ int do_trial_division);
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int BN_is_prime_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx, BN_GENCB *cb);
+OSSL_DEPRECATEDIN_3_0
+int BN_is_prime_fasttest_ex(const BIGNUM *p, int nchecks, BN_CTX *ctx,
+ int do_trial_division, BN_GENCB *cb);
+# endif
+/* Newer versions */
+int BN_generate_prime_ex2(BIGNUM *ret, int bits, int safe,
+ const BIGNUM *add, const BIGNUM *rem, BN_GENCB *cb,
+ BN_CTX *ctx);
+int BN_generate_prime_ex(BIGNUM *ret, int bits, int safe, const BIGNUM *add,
+ const BIGNUM *rem, BN_GENCB *cb);
+int BN_check_prime(const BIGNUM *p, BN_CTX *ctx, BN_GENCB *cb);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int BN_X931_generate_Xpq(BIGNUM *Xp, BIGNUM *Xq, int nbits, BN_CTX *ctx);
+
+OSSL_DEPRECATEDIN_3_0
+int BN_X931_derive_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2,
+ const BIGNUM *Xp, const BIGNUM *Xp1,
+ const BIGNUM *Xp2, const BIGNUM *e, BN_CTX *ctx,
+ BN_GENCB *cb);
+OSSL_DEPRECATEDIN_3_0
+int BN_X931_generate_prime_ex(BIGNUM *p, BIGNUM *p1, BIGNUM *p2, BIGNUM *Xp1,
+ BIGNUM *Xp2, const BIGNUM *Xp, const BIGNUM *e,
+ BN_CTX *ctx, BN_GENCB *cb);
+# endif
+
+BN_MONT_CTX *BN_MONT_CTX_new(void);
+int BN_mod_mul_montgomery(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ BN_MONT_CTX *mont, BN_CTX *ctx);
+int BN_to_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
+ BN_CTX *ctx);
+int BN_from_montgomery(BIGNUM *r, const BIGNUM *a, BN_MONT_CTX *mont,
+ BN_CTX *ctx);
+void BN_MONT_CTX_free(BN_MONT_CTX *mont);
+int BN_MONT_CTX_set(BN_MONT_CTX *mont, const BIGNUM *mod, BN_CTX *ctx);
+BN_MONT_CTX *BN_MONT_CTX_copy(BN_MONT_CTX *to, BN_MONT_CTX *from);
+BN_MONT_CTX *BN_MONT_CTX_set_locked(BN_MONT_CTX **pmont, CRYPTO_RWLOCK *lock,
+ const BIGNUM *mod, BN_CTX *ctx);
+
+/* BN_BLINDING flags */
+# define BN_BLINDING_NO_UPDATE 0x00000001
+# define BN_BLINDING_NO_RECREATE 0x00000002
+
+BN_BLINDING *BN_BLINDING_new(const BIGNUM *A, const BIGNUM *Ai, BIGNUM *mod);
+void BN_BLINDING_free(BN_BLINDING *b);
+int BN_BLINDING_update(BN_BLINDING *b, BN_CTX *ctx);
+int BN_BLINDING_convert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
+int BN_BLINDING_invert(BIGNUM *n, BN_BLINDING *b, BN_CTX *ctx);
+int BN_BLINDING_convert_ex(BIGNUM *n, BIGNUM *r, BN_BLINDING *b, BN_CTX *);
+int BN_BLINDING_invert_ex(BIGNUM *n, const BIGNUM *r, BN_BLINDING *b,
+ BN_CTX *);
+
+int BN_BLINDING_is_current_thread(BN_BLINDING *b);
+void BN_BLINDING_set_current_thread(BN_BLINDING *b);
+int BN_BLINDING_lock(BN_BLINDING *b);
+int BN_BLINDING_unlock(BN_BLINDING *b);
+
+unsigned long BN_BLINDING_get_flags(const BN_BLINDING *);
+void BN_BLINDING_set_flags(BN_BLINDING *, unsigned long);
+BN_BLINDING *BN_BLINDING_create_param(BN_BLINDING *b,
+ const BIGNUM *e, BIGNUM *m, BN_CTX *ctx,
+ int (*bn_mod_exp) (BIGNUM *r,
+ const BIGNUM *a,
+ const BIGNUM *p,
+ const BIGNUM *m,
+ BN_CTX *ctx,
+ BN_MONT_CTX *m_ctx),
+ BN_MONT_CTX *m_ctx);
+# ifndef OPENSSL_NO_DEPRECATED_0_9_8
+OSSL_DEPRECATEDIN_0_9_8
+void BN_set_params(int mul, int high, int low, int mont);
+OSSL_DEPRECATEDIN_0_9_8
+int BN_get_params(int which); /* 0, mul, 1 high, 2 low, 3 mont */
+# endif
+
+BN_RECP_CTX *BN_RECP_CTX_new(void);
+void BN_RECP_CTX_free(BN_RECP_CTX *recp);
+int BN_RECP_CTX_set(BN_RECP_CTX *recp, const BIGNUM *rdiv, BN_CTX *ctx);
+int BN_mod_mul_reciprocal(BIGNUM *r, const BIGNUM *x, const BIGNUM *y,
+ BN_RECP_CTX *recp, BN_CTX *ctx);
+int BN_mod_exp_recp(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
+ const BIGNUM *m, BN_CTX *ctx);
+int BN_div_recp(BIGNUM *dv, BIGNUM *rem, const BIGNUM *m,
+ BN_RECP_CTX *recp, BN_CTX *ctx);
+
+# ifndef OPENSSL_NO_EC2M
+
+/*
+ * Functions for arithmetic over binary polynomials represented by BIGNUMs.
+ * The BIGNUM::neg property of BIGNUMs representing binary polynomials is
+ * ignored. Note that input arguments are not const so that their bit arrays
+ * can be expanded to the appropriate size if needed.
+ */
+
+/*
+ * r = a + b
+ */
+int BN_GF2m_add(BIGNUM *r, const BIGNUM *a, const BIGNUM *b);
+# define BN_GF2m_sub(r, a, b) BN_GF2m_add(r, a, b)
+/*
+ * r=a mod p
+ */
+int BN_GF2m_mod(BIGNUM *r, const BIGNUM *a, const BIGNUM *p);
+/* r = (a * b) mod p */
+int BN_GF2m_mod_mul(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const BIGNUM *p, BN_CTX *ctx);
+/* r = (a * a) mod p */
+int BN_GF2m_mod_sqr(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+/* r = (1 / b) mod p */
+int BN_GF2m_mod_inv(BIGNUM *r, const BIGNUM *b, const BIGNUM *p, BN_CTX *ctx);
+/* r = (a / b) mod p */
+int BN_GF2m_mod_div(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const BIGNUM *p, BN_CTX *ctx);
+/* r = (a ^ b) mod p */
+int BN_GF2m_mod_exp(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const BIGNUM *p, BN_CTX *ctx);
+/* r = sqrt(a) mod p */
+int BN_GF2m_mod_sqrt(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
+ BN_CTX *ctx);
+/* r^2 + r = a mod p */
+int BN_GF2m_mod_solve_quad(BIGNUM *r, const BIGNUM *a, const BIGNUM *p,
+ BN_CTX *ctx);
+# define BN_GF2m_cmp(a, b) BN_ucmp((a), (b))
+/*-
+ * Some functions allow for representation of the irreducible polynomials
+ * as an unsigned int[], say p. The irreducible f(t) is then of the form:
+ * t^p[0] + t^p[1] + ... + t^p[k]
+ * where m = p[0] > p[1] > ... > p[k] = 0.
+ */
+/* r = a mod p */
+int BN_GF2m_mod_arr(BIGNUM *r, const BIGNUM *a, const int p[]);
+/* r = (a * b) mod p */
+int BN_GF2m_mod_mul_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const int p[], BN_CTX *ctx);
+/* r = (a * a) mod p */
+int BN_GF2m_mod_sqr_arr(BIGNUM *r, const BIGNUM *a, const int p[],
+ BN_CTX *ctx);
+/* r = (1 / b) mod p */
+int BN_GF2m_mod_inv_arr(BIGNUM *r, const BIGNUM *b, const int p[],
+ BN_CTX *ctx);
+/* r = (a / b) mod p */
+int BN_GF2m_mod_div_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const int p[], BN_CTX *ctx);
+/* r = (a ^ b) mod p */
+int BN_GF2m_mod_exp_arr(BIGNUM *r, const BIGNUM *a, const BIGNUM *b,
+ const int p[], BN_CTX *ctx);
+/* r = sqrt(a) mod p */
+int BN_GF2m_mod_sqrt_arr(BIGNUM *r, const BIGNUM *a,
+ const int p[], BN_CTX *ctx);
+/* r^2 + r = a mod p */
+int BN_GF2m_mod_solve_quad_arr(BIGNUM *r, const BIGNUM *a,
+ const int p[], BN_CTX *ctx);
+int BN_GF2m_poly2arr(const BIGNUM *a, int p[], int max);
+int BN_GF2m_arr2poly(const int p[], BIGNUM *a);
+
+# endif
+
+/*
+ * faster mod functions for the 'NIST primes' 0 <= a < p^2
+ */
+int BN_nist_mod_192(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+int BN_nist_mod_224(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+int BN_nist_mod_256(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+int BN_nist_mod_384(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+int BN_nist_mod_521(BIGNUM *r, const BIGNUM *a, const BIGNUM *p, BN_CTX *ctx);
+
+const BIGNUM *BN_get0_nist_prime_192(void);
+const BIGNUM *BN_get0_nist_prime_224(void);
+const BIGNUM *BN_get0_nist_prime_256(void);
+const BIGNUM *BN_get0_nist_prime_384(void);
+const BIGNUM *BN_get0_nist_prime_521(void);
+
+int (*BN_nist_mod_func(const BIGNUM *p)) (BIGNUM *r, const BIGNUM *a,
+ const BIGNUM *field, BN_CTX *ctx);
+
+int BN_generate_dsa_nonce(BIGNUM *out, const BIGNUM *range,
+ const BIGNUM *priv, const unsigned char *message,
+ size_t message_len, BN_CTX *ctx);
+
+/* Primes from RFC 2409 */
+BIGNUM *BN_get_rfc2409_prime_768(BIGNUM *bn);
+BIGNUM *BN_get_rfc2409_prime_1024(BIGNUM *bn);
+
+/* Primes from RFC 3526 */
+BIGNUM *BN_get_rfc3526_prime_1536(BIGNUM *bn);
+BIGNUM *BN_get_rfc3526_prime_2048(BIGNUM *bn);
+BIGNUM *BN_get_rfc3526_prime_3072(BIGNUM *bn);
+BIGNUM *BN_get_rfc3526_prime_4096(BIGNUM *bn);
+BIGNUM *BN_get_rfc3526_prime_6144(BIGNUM *bn);
+BIGNUM *BN_get_rfc3526_prime_8192(BIGNUM *bn);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define get_rfc2409_prime_768 BN_get_rfc2409_prime_768
+# define get_rfc2409_prime_1024 BN_get_rfc2409_prime_1024
+# define get_rfc3526_prime_1536 BN_get_rfc3526_prime_1536
+# define get_rfc3526_prime_2048 BN_get_rfc3526_prime_2048
+# define get_rfc3526_prime_3072 BN_get_rfc3526_prime_3072
+# define get_rfc3526_prime_4096 BN_get_rfc3526_prime_4096
+# define get_rfc3526_prime_6144 BN_get_rfc3526_prime_6144
+# define get_rfc3526_prime_8192 BN_get_rfc3526_prime_8192
+# endif
+
+int BN_bntest_rand(BIGNUM *rnd, int bits, int top, int bottom);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/bnerr.h b/include/openssl/bnerr.h
new file mode 100644
index 00000000..847d326b
--- /dev/null
+++ b/include/openssl/bnerr.h
@@ -0,0 +1,46 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_BNERR_H
+# define OPENSSL_BNERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * BN reason codes.
+ */
+# define BN_R_ARG2_LT_ARG3 100
+# define BN_R_BAD_RECIPROCAL 101
+# define BN_R_BIGNUM_TOO_LONG 114
+# define BN_R_BITS_TOO_SMALL 118
+# define BN_R_CALLED_WITH_EVEN_MODULUS 102
+# define BN_R_DIV_BY_ZERO 103
+# define BN_R_ENCODING_ERROR 104
+# define BN_R_EXPAND_ON_STATIC_BIGNUM_DATA 105
+# define BN_R_INPUT_NOT_REDUCED 110
+# define BN_R_INVALID_LENGTH 106
+# define BN_R_INVALID_RANGE 115
+# define BN_R_INVALID_SHIFT 119
+# define BN_R_NOT_A_SQUARE 111
+# define BN_R_NOT_INITIALIZED 107
+# define BN_R_NO_INVERSE 108
+# define BN_R_NO_SOLUTION 116
+# define BN_R_NO_SUITABLE_DIGEST 120
+# define BN_R_PRIVATE_KEY_TOO_LARGE 117
+# define BN_R_P_IS_NOT_PRIME 112
+# define BN_R_TOO_MANY_ITERATIONS 113
+# define BN_R_TOO_MANY_TEMPORARY_VARIABLES 109
+
+#endif
diff --git a/include/openssl/buffer.h b/include/openssl/buffer.h
new file mode 100644
index 00000000..5773b986
--- /dev/null
+++ b/include/openssl/buffer.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright 1995-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_BUFFER_H
+# define OPENSSL_BUFFER_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_BUFFER_H
+# endif
+
+# include <openssl/types.h>
+# ifndef OPENSSL_CRYPTO_H
+# include <openssl/crypto.h>
+# endif
+# include <openssl/buffererr.h>
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# include <stddef.h>
+# include <sys/types.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define BUF_strdup(s) OPENSSL_strdup(s)
+# define BUF_strndup(s, size) OPENSSL_strndup(s, size)
+# define BUF_memdup(data, size) OPENSSL_memdup(data, size)
+# define BUF_strlcpy(dst, src, size) OPENSSL_strlcpy(dst, src, size)
+# define BUF_strlcat(dst, src, size) OPENSSL_strlcat(dst, src, size)
+# define BUF_strnlen(str, maxlen) OPENSSL_strnlen(str, maxlen)
+# endif
+
+struct buf_mem_st {
+ size_t length; /* current number of bytes */
+ char *data;
+ size_t max; /* size of buffer */
+ unsigned long flags;
+};
+
+# define BUF_MEM_FLAG_SECURE 0x01
+
+BUF_MEM *BUF_MEM_new(void);
+BUF_MEM *BUF_MEM_new_ex(unsigned long flags);
+void BUF_MEM_free(BUF_MEM *a);
+size_t BUF_MEM_grow(BUF_MEM *str, size_t len);
+size_t BUF_MEM_grow_clean(BUF_MEM *str, size_t len);
+void BUF_reverse(unsigned char *out, const unsigned char *in, size_t siz);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/buffererr.h b/include/openssl/buffererr.h
new file mode 100644
index 00000000..d18b1f8f
--- /dev/null
+++ b/include/openssl/buffererr.h
@@ -0,0 +1,25 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_BUFFERERR_H
+# define OPENSSL_BUFFERERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * BUF reason codes.
+ */
+
+#endif
diff --git a/include/openssl/camellia.h b/include/openssl/camellia.h
new file mode 100644
index 00000000..88c2279e
--- /dev/null
+++ b/include/openssl/camellia.h
@@ -0,0 +1,117 @@
+/*
+ * Copyright 2006-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CAMELLIA_H
+# define OPENSSL_CAMELLIA_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CAMELLIA_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CAMELLIA
+# include <stddef.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define CAMELLIA_BLOCK_SIZE 16
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+# define CAMELLIA_ENCRYPT 1
+# define CAMELLIA_DECRYPT 0
+
+/*
+ * Because array size can't be a const in C, the following two are macros.
+ * Both sizes are in bytes.
+ */
+
+/* This should be a hidden type, but EVP requires that the size be known */
+
+# define CAMELLIA_TABLE_BYTE_LEN 272
+# define CAMELLIA_TABLE_WORD_LEN (CAMELLIA_TABLE_BYTE_LEN / 4)
+
+typedef unsigned int KEY_TABLE_TYPE[CAMELLIA_TABLE_WORD_LEN]; /* to match
+ * with WORD */
+
+struct camellia_key_st {
+ union {
+ double d; /* ensures 64-bit align */
+ KEY_TABLE_TYPE rd_key;
+ } u;
+ int grand_rounds;
+};
+typedef struct camellia_key_st CAMELLIA_KEY;
+
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int Camellia_set_key(const unsigned char *userKey,
+ const int bits,
+ CAMELLIA_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void Camellia_encrypt(const unsigned char *in,
+ unsigned char *out,
+ const CAMELLIA_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void Camellia_decrypt(const unsigned char *in,
+ unsigned char *out,
+ const CAMELLIA_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void Camellia_ecb_encrypt(const unsigned char *in,
+ unsigned char *out,
+ const CAMELLIA_KEY *key,
+ const int enc);
+OSSL_DEPRECATEDIN_3_0 void Camellia_cbc_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const CAMELLIA_KEY *key,
+ unsigned char *ivec,
+ const int enc);
+OSSL_DEPRECATEDIN_3_0 void Camellia_cfb128_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const CAMELLIA_KEY *key,
+ unsigned char *ivec,
+ int *num,
+ const int enc);
+OSSL_DEPRECATEDIN_3_0 void Camellia_cfb1_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const CAMELLIA_KEY *key,
+ unsigned char *ivec,
+ int *num,
+ const int enc);
+OSSL_DEPRECATEDIN_3_0 void Camellia_cfb8_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const CAMELLIA_KEY *key,
+ unsigned char *ivec,
+ int *num,
+ const int enc);
+OSSL_DEPRECATEDIN_3_0 void Camellia_ofb128_encrypt(const unsigned char *in,
+ unsigned char *out,
+ size_t length,
+ const CAMELLIA_KEY *key,
+ unsigned char *ivec,
+ int *num);
+OSSL_DEPRECATEDIN_3_0
+void Camellia_ctr128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const CAMELLIA_KEY *key,
+ unsigned char ivec[CAMELLIA_BLOCK_SIZE],
+ unsigned char ecount_buf[CAMELLIA_BLOCK_SIZE],
+ unsigned int *num);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/cast.h b/include/openssl/cast.h
new file mode 100644
index 00000000..0bf217be
--- /dev/null
+++ b/include/openssl/cast.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CAST_H
+# define OPENSSL_CAST_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CAST_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CAST
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define CAST_BLOCK 8
+# define CAST_KEY_LENGTH 16
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+# define CAST_ENCRYPT 1
+# define CAST_DECRYPT 0
+
+# define CAST_LONG unsigned int
+
+typedef struct cast_key_st {
+ CAST_LONG data[32];
+ int short_key; /* Use reduced rounds for short key */
+} CAST_KEY;
+
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data);
+OSSL_DEPRECATEDIN_3_0
+void CAST_ecb_encrypt(const unsigned char *in, unsigned char *out,
+ const CAST_KEY *key, int enc);
+OSSL_DEPRECATEDIN_3_0
+void CAST_encrypt(CAST_LONG *data, const CAST_KEY *key);
+OSSL_DEPRECATEDIN_3_0
+void CAST_decrypt(CAST_LONG *data, const CAST_KEY *key);
+OSSL_DEPRECATEDIN_3_0
+void CAST_cbc_encrypt(const unsigned char *in, unsigned char *out,
+ long length, const CAST_KEY *ks, unsigned char *iv,
+ int enc);
+OSSL_DEPRECATEDIN_3_0
+void CAST_cfb64_encrypt(const unsigned char *in, unsigned char *out,
+ long length, const CAST_KEY *schedule,
+ unsigned char *ivec, int *num, int enc);
+OSSL_DEPRECATEDIN_3_0
+void CAST_ofb64_encrypt(const unsigned char *in, unsigned char *out,
+ long length, const CAST_KEY *schedule,
+ unsigned char *ivec, int *num);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/cmac.h b/include/openssl/cmac.h
new file mode 100644
index 00000000..f5086183
--- /dev/null
+++ b/include/openssl/cmac.h
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2010-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CMAC_H
+# define OPENSSL_CMAC_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CMAC_H
+# endif
+
+# ifndef OPENSSL_NO_CMAC
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# include <openssl/evp.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* Opaque */
+typedef struct CMAC_CTX_st CMAC_CTX;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 CMAC_CTX *CMAC_CTX_new(void);
+OSSL_DEPRECATEDIN_3_0 void CMAC_CTX_cleanup(CMAC_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 void CMAC_CTX_free(CMAC_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 EVP_CIPHER_CTX *CMAC_CTX_get0_cipher_ctx(CMAC_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 int CMAC_CTX_copy(CMAC_CTX *out, const CMAC_CTX *in);
+OSSL_DEPRECATEDIN_3_0 int CMAC_Init(CMAC_CTX *ctx,
+ const void *key, size_t keylen,
+ const EVP_CIPHER *cipher, ENGINE *impl);
+OSSL_DEPRECATEDIN_3_0 int CMAC_Update(CMAC_CTX *ctx,
+ const void *data, size_t dlen);
+OSSL_DEPRECATEDIN_3_0 int CMAC_Final(CMAC_CTX *ctx,
+ unsigned char *out, size_t *poutlen);
+OSSL_DEPRECATEDIN_3_0 int CMAC_resume(CMAC_CTX *ctx);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+
+# endif
+#endif
diff --git a/include/openssl/cmp.h b/include/openssl/cmp.h
new file mode 100644
index 00000000..7f258dc9
--- /dev/null
+++ b/include/openssl/cmp.h
@@ -0,0 +1,592 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\cmp.h.in
+ *
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright Nokia 2007-2019
+ * Copyright Siemens AG 2015-2019
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_CMP_H
+# define OPENSSL_CMP_H
+
+# include <openssl/opensslconf.h>
+# ifndef OPENSSL_NO_CMP
+
+# include <openssl/crmf.h>
+# include <openssl/cmperr.h>
+# include <openssl/cmp_util.h>
+# include <openssl/http.h>
+
+/* explicit #includes not strictly needed since implied by the above: */
+# include <openssl/types.h>
+# include <openssl/safestack.h>
+# include <openssl/x509.h>
+# include <openssl/x509v3.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define OSSL_CMP_PVNO 2
+
+/*-
+ * PKIFailureInfo ::= BIT STRING {
+ * -- since we can fail in more than one way!
+ * -- More codes may be added in the future if/when required.
+ * badAlg (0),
+ * -- unrecognized or unsupported Algorithm Identifier
+ * badMessageCheck (1),
+ * -- integrity check failed (e.g., signature did not verify)
+ * badRequest (2),
+ * -- transaction not permitted or supported
+ * badTime (3),
+ * -- messageTime was not sufficiently close to the system time,
+ * -- as defined by local policy
+ * badCertId (4),
+ * -- no certificate could be found matching the provided criteria
+ * badDataFormat (5),
+ * -- the data submitted has the wrong format
+ * wrongAuthority (6),
+ * -- the authority indicated in the request is different from the
+ * -- one creating the response token
+ * incorrectData (7),
+ * -- the requester's data is incorrect (for notary services)
+ * missingTimeStamp (8),
+ * -- when the timestamp is missing but should be there
+ * -- (by policy)
+ * badPOP (9),
+ * -- the proof-of-possession failed
+ * certRevoked (10),
+ * -- the certificate has already been revoked
+ * certConfirmed (11),
+ * -- the certificate has already been confirmed
+ * wrongIntegrity (12),
+ * -- invalid integrity, password based instead of signature or
+ * -- vice versa
+ * badRecipientNonce (13),
+ * -- invalid recipient nonce, either missing or wrong value
+ * timeNotAvailable (14),
+ * -- the TSA's time source is not available
+ * unacceptedPolicy (15),
+ * -- the requested TSA policy is not supported by the TSA.
+ * unacceptedExtension (16),
+ * -- the requested extension is not supported by the TSA.
+ * addInfoNotAvailable (17),
+ * -- the additional information requested could not be
+ * -- understood or is not available
+ * badSenderNonce (18),
+ * -- invalid sender nonce, either missing or wrong size
+ * badCertTemplate (19),
+ * -- invalid cert. template or missing mandatory information
+ * signerNotTrusted (20),
+ * -- signer of the message unknown or not trusted
+ * transactionIdInUse (21),
+ * -- the transaction identifier is already in use
+ * unsupportedVersion (22),
+ * -- the version of the message is not supported
+ * notAuthorized (23),
+ * -- the sender was not authorized to make the preceding
+ * -- request or perform the preceding action
+ * systemUnavail (24),
+ * -- the request cannot be handled due to system unavailability
+ * systemFailure (25),
+ * -- the request cannot be handled due to system failure
+ * duplicateCertReq (26)
+ * -- certificate cannot be issued because a duplicate
+ * -- certificate already exists
+ * }
+ */
+# define OSSL_CMP_PKIFAILUREINFO_badAlg 0
+# define OSSL_CMP_PKIFAILUREINFO_badMessageCheck 1
+# define OSSL_CMP_PKIFAILUREINFO_badRequest 2
+# define OSSL_CMP_PKIFAILUREINFO_badTime 3
+# define OSSL_CMP_PKIFAILUREINFO_badCertId 4
+# define OSSL_CMP_PKIFAILUREINFO_badDataFormat 5
+# define OSSL_CMP_PKIFAILUREINFO_wrongAuthority 6
+# define OSSL_CMP_PKIFAILUREINFO_incorrectData 7
+# define OSSL_CMP_PKIFAILUREINFO_missingTimeStamp 8
+# define OSSL_CMP_PKIFAILUREINFO_badPOP 9
+# define OSSL_CMP_PKIFAILUREINFO_certRevoked 10
+# define OSSL_CMP_PKIFAILUREINFO_certConfirmed 11
+# define OSSL_CMP_PKIFAILUREINFO_wrongIntegrity 12
+# define OSSL_CMP_PKIFAILUREINFO_badRecipientNonce 13
+# define OSSL_CMP_PKIFAILUREINFO_timeNotAvailable 14
+# define OSSL_CMP_PKIFAILUREINFO_unacceptedPolicy 15
+# define OSSL_CMP_PKIFAILUREINFO_unacceptedExtension 16
+# define OSSL_CMP_PKIFAILUREINFO_addInfoNotAvailable 17
+# define OSSL_CMP_PKIFAILUREINFO_badSenderNonce 18
+# define OSSL_CMP_PKIFAILUREINFO_badCertTemplate 19
+# define OSSL_CMP_PKIFAILUREINFO_signerNotTrusted 20
+# define OSSL_CMP_PKIFAILUREINFO_transactionIdInUse 21
+# define OSSL_CMP_PKIFAILUREINFO_unsupportedVersion 22
+# define OSSL_CMP_PKIFAILUREINFO_notAuthorized 23
+# define OSSL_CMP_PKIFAILUREINFO_systemUnavail 24
+# define OSSL_CMP_PKIFAILUREINFO_systemFailure 25
+# define OSSL_CMP_PKIFAILUREINFO_duplicateCertReq 26
+# define OSSL_CMP_PKIFAILUREINFO_MAX 26
+# define OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN \
+ ((1 << (OSSL_CMP_PKIFAILUREINFO_MAX + 1)) - 1)
+# if OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN > INT_MAX
+# error CMP_PKIFAILUREINFO_MAX bit pattern does not fit in type int
+# endif
+
+typedef ASN1_BIT_STRING OSSL_CMP_PKIFAILUREINFO;
+
+# define OSSL_CMP_CTX_FAILINFO_badAlg (1 << 0)
+# define OSSL_CMP_CTX_FAILINFO_badMessageCheck (1 << 1)
+# define OSSL_CMP_CTX_FAILINFO_badRequest (1 << 2)
+# define OSSL_CMP_CTX_FAILINFO_badTime (1 << 3)
+# define OSSL_CMP_CTX_FAILINFO_badCertId (1 << 4)
+# define OSSL_CMP_CTX_FAILINFO_badDataFormat (1 << 5)
+# define OSSL_CMP_CTX_FAILINFO_wrongAuthority (1 << 6)
+# define OSSL_CMP_CTX_FAILINFO_incorrectData (1 << 7)
+# define OSSL_CMP_CTX_FAILINFO_missingTimeStamp (1 << 8)
+# define OSSL_CMP_CTX_FAILINFO_badPOP (1 << 9)
+# define OSSL_CMP_CTX_FAILINFO_certRevoked (1 << 10)
+# define OSSL_CMP_CTX_FAILINFO_certConfirmed (1 << 11)
+# define OSSL_CMP_CTX_FAILINFO_wrongIntegrity (1 << 12)
+# define OSSL_CMP_CTX_FAILINFO_badRecipientNonce (1 << 13)
+# define OSSL_CMP_CTX_FAILINFO_timeNotAvailable (1 << 14)
+# define OSSL_CMP_CTX_FAILINFO_unacceptedPolicy (1 << 15)
+# define OSSL_CMP_CTX_FAILINFO_unacceptedExtension (1 << 16)
+# define OSSL_CMP_CTX_FAILINFO_addInfoNotAvailable (1 << 17)
+# define OSSL_CMP_CTX_FAILINFO_badSenderNonce (1 << 18)
+# define OSSL_CMP_CTX_FAILINFO_badCertTemplate (1 << 19)
+# define OSSL_CMP_CTX_FAILINFO_signerNotTrusted (1 << 20)
+# define OSSL_CMP_CTX_FAILINFO_transactionIdInUse (1 << 21)
+# define OSSL_CMP_CTX_FAILINFO_unsupportedVersion (1 << 22)
+# define OSSL_CMP_CTX_FAILINFO_notAuthorized (1 << 23)
+# define OSSL_CMP_CTX_FAILINFO_systemUnavail (1 << 24)
+# define OSSL_CMP_CTX_FAILINFO_systemFailure (1 << 25)
+# define OSSL_CMP_CTX_FAILINFO_duplicateCertReq (1 << 26)
+
+/*-
+ * PKIStatus ::= INTEGER {
+ * accepted (0),
+ * -- you got exactly what you asked for
+ * grantedWithMods (1),
+ * -- you got something like what you asked for; the
+ * -- requester is responsible for ascertaining the differences
+ * rejection (2),
+ * -- you don't get it, more information elsewhere in the message
+ * waiting (3),
+ * -- the request body part has not yet been processed; expect to
+ * -- hear more later (note: proper handling of this status
+ * -- response MAY use the polling req/rep PKIMessages specified
+ * -- in Section 5.3.22; alternatively, polling in the underlying
+ * -- transport layer MAY have some utility in this regard)
+ * revocationWarning (4),
+ * -- this message contains a warning that a revocation is
+ * -- imminent
+ * revocationNotification (5),
+ * -- notification that a revocation has occurred
+ * keyUpdateWarning (6)
+ * -- update already done for the oldCertId specified in
+ * -- CertReqMsg
+ * }
+ */
+# define OSSL_CMP_PKISTATUS_accepted 0
+# define OSSL_CMP_PKISTATUS_grantedWithMods 1
+# define OSSL_CMP_PKISTATUS_rejection 2
+# define OSSL_CMP_PKISTATUS_waiting 3
+# define OSSL_CMP_PKISTATUS_revocationWarning 4
+# define OSSL_CMP_PKISTATUS_revocationNotification 5
+# define OSSL_CMP_PKISTATUS_keyUpdateWarning 6
+
+typedef ASN1_INTEGER OSSL_CMP_PKISTATUS;
+DECLARE_ASN1_ITEM(OSSL_CMP_PKISTATUS)
+
+# define OSSL_CMP_CERTORENCCERT_CERTIFICATE 0
+# define OSSL_CMP_CERTORENCCERT_ENCRYPTEDCERT 1
+
+/* data type declarations */
+typedef struct ossl_cmp_ctx_st OSSL_CMP_CTX;
+typedef struct ossl_cmp_pkiheader_st OSSL_CMP_PKIHEADER;
+DECLARE_ASN1_FUNCTIONS(OSSL_CMP_PKIHEADER)
+typedef struct ossl_cmp_msg_st OSSL_CMP_MSG;
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CMP_MSG)
+DECLARE_ASN1_ENCODE_FUNCTIONS(OSSL_CMP_MSG, OSSL_CMP_MSG, OSSL_CMP_MSG)
+typedef struct ossl_cmp_certstatus_st OSSL_CMP_CERTSTATUS;
+SKM_DEFINE_STACK_OF_INTERNAL(OSSL_CMP_CERTSTATUS, OSSL_CMP_CERTSTATUS, OSSL_CMP_CERTSTATUS)
+#define sk_OSSL_CMP_CERTSTATUS_num(sk) OPENSSL_sk_num(ossl_check_const_OSSL_CMP_CERTSTATUS_sk_type(sk))
+#define sk_OSSL_CMP_CERTSTATUS_value(sk, idx) ((OSSL_CMP_CERTSTATUS *)OPENSSL_sk_value(ossl_check_const_OSSL_CMP_CERTSTATUS_sk_type(sk), (idx)))
+#define sk_OSSL_CMP_CERTSTATUS_new(cmp) ((STACK_OF(OSSL_CMP_CERTSTATUS) *)OPENSSL_sk_new(ossl_check_OSSL_CMP_CERTSTATUS_compfunc_type(cmp)))
+#define sk_OSSL_CMP_CERTSTATUS_new_null() ((STACK_OF(OSSL_CMP_CERTSTATUS) *)OPENSSL_sk_new_null())
+#define sk_OSSL_CMP_CERTSTATUS_new_reserve(cmp, n) ((STACK_OF(OSSL_CMP_CERTSTATUS) *)OPENSSL_sk_new_reserve(ossl_check_OSSL_CMP_CERTSTATUS_compfunc_type(cmp), (n)))
+#define sk_OSSL_CMP_CERTSTATUS_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), (n))
+#define sk_OSSL_CMP_CERTSTATUS_free(sk) OPENSSL_sk_free(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk))
+#define sk_OSSL_CMP_CERTSTATUS_zero(sk) OPENSSL_sk_zero(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk))
+#define sk_OSSL_CMP_CERTSTATUS_delete(sk, i) ((OSSL_CMP_CERTSTATUS *)OPENSSL_sk_delete(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), (i)))
+#define sk_OSSL_CMP_CERTSTATUS_delete_ptr(sk, ptr) ((OSSL_CMP_CERTSTATUS *)OPENSSL_sk_delete_ptr(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr)))
+#define sk_OSSL_CMP_CERTSTATUS_push(sk, ptr) OPENSSL_sk_push(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr))
+#define sk_OSSL_CMP_CERTSTATUS_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr))
+#define sk_OSSL_CMP_CERTSTATUS_pop(sk) ((OSSL_CMP_CERTSTATUS *)OPENSSL_sk_pop(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk)))
+#define sk_OSSL_CMP_CERTSTATUS_shift(sk) ((OSSL_CMP_CERTSTATUS *)OPENSSL_sk_shift(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk)))
+#define sk_OSSL_CMP_CERTSTATUS_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk),ossl_check_OSSL_CMP_CERTSTATUS_freefunc_type(freefunc))
+#define sk_OSSL_CMP_CERTSTATUS_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr), (idx))
+#define sk_OSSL_CMP_CERTSTATUS_set(sk, idx, ptr) ((OSSL_CMP_CERTSTATUS *)OPENSSL_sk_set(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), (idx), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr)))
+#define sk_OSSL_CMP_CERTSTATUS_find(sk, ptr) OPENSSL_sk_find(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr))
+#define sk_OSSL_CMP_CERTSTATUS_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr))
+#define sk_OSSL_CMP_CERTSTATUS_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_type(ptr), pnum)
+#define sk_OSSL_CMP_CERTSTATUS_sort(sk) OPENSSL_sk_sort(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk))
+#define sk_OSSL_CMP_CERTSTATUS_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OSSL_CMP_CERTSTATUS_sk_type(sk))
+#define sk_OSSL_CMP_CERTSTATUS_dup(sk) ((STACK_OF(OSSL_CMP_CERTSTATUS) *)OPENSSL_sk_dup(ossl_check_const_OSSL_CMP_CERTSTATUS_sk_type(sk)))
+#define sk_OSSL_CMP_CERTSTATUS_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OSSL_CMP_CERTSTATUS) *)OPENSSL_sk_deep_copy(ossl_check_const_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_copyfunc_type(copyfunc), ossl_check_OSSL_CMP_CERTSTATUS_freefunc_type(freefunc)))
+#define sk_OSSL_CMP_CERTSTATUS_set_cmp_func(sk, cmp) ((sk_OSSL_CMP_CERTSTATUS_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OSSL_CMP_CERTSTATUS_sk_type(sk), ossl_check_OSSL_CMP_CERTSTATUS_compfunc_type(cmp)))
+
+typedef struct ossl_cmp_itav_st OSSL_CMP_ITAV;
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CMP_ITAV)
+SKM_DEFINE_STACK_OF_INTERNAL(OSSL_CMP_ITAV, OSSL_CMP_ITAV, OSSL_CMP_ITAV)
+#define sk_OSSL_CMP_ITAV_num(sk) OPENSSL_sk_num(ossl_check_const_OSSL_CMP_ITAV_sk_type(sk))
+#define sk_OSSL_CMP_ITAV_value(sk, idx) ((OSSL_CMP_ITAV *)OPENSSL_sk_value(ossl_check_const_OSSL_CMP_ITAV_sk_type(sk), (idx)))
+#define sk_OSSL_CMP_ITAV_new(cmp) ((STACK_OF(OSSL_CMP_ITAV) *)OPENSSL_sk_new(ossl_check_OSSL_CMP_ITAV_compfunc_type(cmp)))
+#define sk_OSSL_CMP_ITAV_new_null() ((STACK_OF(OSSL_CMP_ITAV) *)OPENSSL_sk_new_null())
+#define sk_OSSL_CMP_ITAV_new_reserve(cmp, n) ((STACK_OF(OSSL_CMP_ITAV) *)OPENSSL_sk_new_reserve(ossl_check_OSSL_CMP_ITAV_compfunc_type(cmp), (n)))
+#define sk_OSSL_CMP_ITAV_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OSSL_CMP_ITAV_sk_type(sk), (n))
+#define sk_OSSL_CMP_ITAV_free(sk) OPENSSL_sk_free(ossl_check_OSSL_CMP_ITAV_sk_type(sk))
+#define sk_OSSL_CMP_ITAV_zero(sk) OPENSSL_sk_zero(ossl_check_OSSL_CMP_ITAV_sk_type(sk))
+#define sk_OSSL_CMP_ITAV_delete(sk, i) ((OSSL_CMP_ITAV *)OPENSSL_sk_delete(ossl_check_OSSL_CMP_ITAV_sk_type(sk), (i)))
+#define sk_OSSL_CMP_ITAV_delete_ptr(sk, ptr) ((OSSL_CMP_ITAV *)OPENSSL_sk_delete_ptr(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_type(ptr)))
+#define sk_OSSL_CMP_ITAV_push(sk, ptr) OPENSSL_sk_push(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_type(ptr))
+#define sk_OSSL_CMP_ITAV_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_type(ptr))
+#define sk_OSSL_CMP_ITAV_pop(sk) ((OSSL_CMP_ITAV *)OPENSSL_sk_pop(ossl_check_OSSL_CMP_ITAV_sk_type(sk)))
+#define sk_OSSL_CMP_ITAV_shift(sk) ((OSSL_CMP_ITAV *)OPENSSL_sk_shift(ossl_check_OSSL_CMP_ITAV_sk_type(sk)))
+#define sk_OSSL_CMP_ITAV_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OSSL_CMP_ITAV_sk_type(sk),ossl_check_OSSL_CMP_ITAV_freefunc_type(freefunc))
+#define sk_OSSL_CMP_ITAV_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_type(ptr), (idx))
+#define sk_OSSL_CMP_ITAV_set(sk, idx, ptr) ((OSSL_CMP_ITAV *)OPENSSL_sk_set(ossl_check_OSSL_CMP_ITAV_sk_type(sk), (idx), ossl_check_OSSL_CMP_ITAV_type(ptr)))
+#define sk_OSSL_CMP_ITAV_find(sk, ptr) OPENSSL_sk_find(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_type(ptr))
+#define sk_OSSL_CMP_ITAV_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_type(ptr))
+#define sk_OSSL_CMP_ITAV_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_type(ptr), pnum)
+#define sk_OSSL_CMP_ITAV_sort(sk) OPENSSL_sk_sort(ossl_check_OSSL_CMP_ITAV_sk_type(sk))
+#define sk_OSSL_CMP_ITAV_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OSSL_CMP_ITAV_sk_type(sk))
+#define sk_OSSL_CMP_ITAV_dup(sk) ((STACK_OF(OSSL_CMP_ITAV) *)OPENSSL_sk_dup(ossl_check_const_OSSL_CMP_ITAV_sk_type(sk)))
+#define sk_OSSL_CMP_ITAV_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OSSL_CMP_ITAV) *)OPENSSL_sk_deep_copy(ossl_check_const_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_copyfunc_type(copyfunc), ossl_check_OSSL_CMP_ITAV_freefunc_type(freefunc)))
+#define sk_OSSL_CMP_ITAV_set_cmp_func(sk, cmp) ((sk_OSSL_CMP_ITAV_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OSSL_CMP_ITAV_sk_type(sk), ossl_check_OSSL_CMP_ITAV_compfunc_type(cmp)))
+
+typedef struct ossl_cmp_revrepcontent_st OSSL_CMP_REVREPCONTENT;
+typedef struct ossl_cmp_pkisi_st OSSL_CMP_PKISI;
+DECLARE_ASN1_FUNCTIONS(OSSL_CMP_PKISI)
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CMP_PKISI)
+SKM_DEFINE_STACK_OF_INTERNAL(OSSL_CMP_PKISI, OSSL_CMP_PKISI, OSSL_CMP_PKISI)
+#define sk_OSSL_CMP_PKISI_num(sk) OPENSSL_sk_num(ossl_check_const_OSSL_CMP_PKISI_sk_type(sk))
+#define sk_OSSL_CMP_PKISI_value(sk, idx) ((OSSL_CMP_PKISI *)OPENSSL_sk_value(ossl_check_const_OSSL_CMP_PKISI_sk_type(sk), (idx)))
+#define sk_OSSL_CMP_PKISI_new(cmp) ((STACK_OF(OSSL_CMP_PKISI) *)OPENSSL_sk_new(ossl_check_OSSL_CMP_PKISI_compfunc_type(cmp)))
+#define sk_OSSL_CMP_PKISI_new_null() ((STACK_OF(OSSL_CMP_PKISI) *)OPENSSL_sk_new_null())
+#define sk_OSSL_CMP_PKISI_new_reserve(cmp, n) ((STACK_OF(OSSL_CMP_PKISI) *)OPENSSL_sk_new_reserve(ossl_check_OSSL_CMP_PKISI_compfunc_type(cmp), (n)))
+#define sk_OSSL_CMP_PKISI_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OSSL_CMP_PKISI_sk_type(sk), (n))
+#define sk_OSSL_CMP_PKISI_free(sk) OPENSSL_sk_free(ossl_check_OSSL_CMP_PKISI_sk_type(sk))
+#define sk_OSSL_CMP_PKISI_zero(sk) OPENSSL_sk_zero(ossl_check_OSSL_CMP_PKISI_sk_type(sk))
+#define sk_OSSL_CMP_PKISI_delete(sk, i) ((OSSL_CMP_PKISI *)OPENSSL_sk_delete(ossl_check_OSSL_CMP_PKISI_sk_type(sk), (i)))
+#define sk_OSSL_CMP_PKISI_delete_ptr(sk, ptr) ((OSSL_CMP_PKISI *)OPENSSL_sk_delete_ptr(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_type(ptr)))
+#define sk_OSSL_CMP_PKISI_push(sk, ptr) OPENSSL_sk_push(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_type(ptr))
+#define sk_OSSL_CMP_PKISI_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_type(ptr))
+#define sk_OSSL_CMP_PKISI_pop(sk) ((OSSL_CMP_PKISI *)OPENSSL_sk_pop(ossl_check_OSSL_CMP_PKISI_sk_type(sk)))
+#define sk_OSSL_CMP_PKISI_shift(sk) ((OSSL_CMP_PKISI *)OPENSSL_sk_shift(ossl_check_OSSL_CMP_PKISI_sk_type(sk)))
+#define sk_OSSL_CMP_PKISI_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OSSL_CMP_PKISI_sk_type(sk),ossl_check_OSSL_CMP_PKISI_freefunc_type(freefunc))
+#define sk_OSSL_CMP_PKISI_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_type(ptr), (idx))
+#define sk_OSSL_CMP_PKISI_set(sk, idx, ptr) ((OSSL_CMP_PKISI *)OPENSSL_sk_set(ossl_check_OSSL_CMP_PKISI_sk_type(sk), (idx), ossl_check_OSSL_CMP_PKISI_type(ptr)))
+#define sk_OSSL_CMP_PKISI_find(sk, ptr) OPENSSL_sk_find(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_type(ptr))
+#define sk_OSSL_CMP_PKISI_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_type(ptr))
+#define sk_OSSL_CMP_PKISI_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_type(ptr), pnum)
+#define sk_OSSL_CMP_PKISI_sort(sk) OPENSSL_sk_sort(ossl_check_OSSL_CMP_PKISI_sk_type(sk))
+#define sk_OSSL_CMP_PKISI_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OSSL_CMP_PKISI_sk_type(sk))
+#define sk_OSSL_CMP_PKISI_dup(sk) ((STACK_OF(OSSL_CMP_PKISI) *)OPENSSL_sk_dup(ossl_check_const_OSSL_CMP_PKISI_sk_type(sk)))
+#define sk_OSSL_CMP_PKISI_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OSSL_CMP_PKISI) *)OPENSSL_sk_deep_copy(ossl_check_const_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_copyfunc_type(copyfunc), ossl_check_OSSL_CMP_PKISI_freefunc_type(freefunc)))
+#define sk_OSSL_CMP_PKISI_set_cmp_func(sk, cmp) ((sk_OSSL_CMP_PKISI_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OSSL_CMP_PKISI_sk_type(sk), ossl_check_OSSL_CMP_PKISI_compfunc_type(cmp)))
+
+typedef struct ossl_cmp_certrepmessage_st OSSL_CMP_CERTREPMESSAGE;
+SKM_DEFINE_STACK_OF_INTERNAL(OSSL_CMP_CERTREPMESSAGE, OSSL_CMP_CERTREPMESSAGE, OSSL_CMP_CERTREPMESSAGE)
+#define sk_OSSL_CMP_CERTREPMESSAGE_num(sk) OPENSSL_sk_num(ossl_check_const_OSSL_CMP_CERTREPMESSAGE_sk_type(sk))
+#define sk_OSSL_CMP_CERTREPMESSAGE_value(sk, idx) ((OSSL_CMP_CERTREPMESSAGE *)OPENSSL_sk_value(ossl_check_const_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), (idx)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_new(cmp) ((STACK_OF(OSSL_CMP_CERTREPMESSAGE) *)OPENSSL_sk_new(ossl_check_OSSL_CMP_CERTREPMESSAGE_compfunc_type(cmp)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_new_null() ((STACK_OF(OSSL_CMP_CERTREPMESSAGE) *)OPENSSL_sk_new_null())
+#define sk_OSSL_CMP_CERTREPMESSAGE_new_reserve(cmp, n) ((STACK_OF(OSSL_CMP_CERTREPMESSAGE) *)OPENSSL_sk_new_reserve(ossl_check_OSSL_CMP_CERTREPMESSAGE_compfunc_type(cmp), (n)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), (n))
+#define sk_OSSL_CMP_CERTREPMESSAGE_free(sk) OPENSSL_sk_free(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk))
+#define sk_OSSL_CMP_CERTREPMESSAGE_zero(sk) OPENSSL_sk_zero(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk))
+#define sk_OSSL_CMP_CERTREPMESSAGE_delete(sk, i) ((OSSL_CMP_CERTREPMESSAGE *)OPENSSL_sk_delete(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), (i)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_delete_ptr(sk, ptr) ((OSSL_CMP_CERTREPMESSAGE *)OPENSSL_sk_delete_ptr(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_push(sk, ptr) OPENSSL_sk_push(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr))
+#define sk_OSSL_CMP_CERTREPMESSAGE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr))
+#define sk_OSSL_CMP_CERTREPMESSAGE_pop(sk) ((OSSL_CMP_CERTREPMESSAGE *)OPENSSL_sk_pop(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_shift(sk) ((OSSL_CMP_CERTREPMESSAGE *)OPENSSL_sk_shift(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk),ossl_check_OSSL_CMP_CERTREPMESSAGE_freefunc_type(freefunc))
+#define sk_OSSL_CMP_CERTREPMESSAGE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr), (idx))
+#define sk_OSSL_CMP_CERTREPMESSAGE_set(sk, idx, ptr) ((OSSL_CMP_CERTREPMESSAGE *)OPENSSL_sk_set(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), (idx), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_find(sk, ptr) OPENSSL_sk_find(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr))
+#define sk_OSSL_CMP_CERTREPMESSAGE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr))
+#define sk_OSSL_CMP_CERTREPMESSAGE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_type(ptr), pnum)
+#define sk_OSSL_CMP_CERTREPMESSAGE_sort(sk) OPENSSL_sk_sort(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk))
+#define sk_OSSL_CMP_CERTREPMESSAGE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OSSL_CMP_CERTREPMESSAGE_sk_type(sk))
+#define sk_OSSL_CMP_CERTREPMESSAGE_dup(sk) ((STACK_OF(OSSL_CMP_CERTREPMESSAGE) *)OPENSSL_sk_dup(ossl_check_const_OSSL_CMP_CERTREPMESSAGE_sk_type(sk)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OSSL_CMP_CERTREPMESSAGE) *)OPENSSL_sk_deep_copy(ossl_check_const_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_copyfunc_type(copyfunc), ossl_check_OSSL_CMP_CERTREPMESSAGE_freefunc_type(freefunc)))
+#define sk_OSSL_CMP_CERTREPMESSAGE_set_cmp_func(sk, cmp) ((sk_OSSL_CMP_CERTREPMESSAGE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OSSL_CMP_CERTREPMESSAGE_sk_type(sk), ossl_check_OSSL_CMP_CERTREPMESSAGE_compfunc_type(cmp)))
+
+typedef struct ossl_cmp_pollrep_st OSSL_CMP_POLLREP;
+typedef STACK_OF(OSSL_CMP_POLLREP) OSSL_CMP_POLLREPCONTENT;
+typedef struct ossl_cmp_certresponse_st OSSL_CMP_CERTRESPONSE;
+SKM_DEFINE_STACK_OF_INTERNAL(OSSL_CMP_CERTRESPONSE, OSSL_CMP_CERTRESPONSE, OSSL_CMP_CERTRESPONSE)
+#define sk_OSSL_CMP_CERTRESPONSE_num(sk) OPENSSL_sk_num(ossl_check_const_OSSL_CMP_CERTRESPONSE_sk_type(sk))
+#define sk_OSSL_CMP_CERTRESPONSE_value(sk, idx) ((OSSL_CMP_CERTRESPONSE *)OPENSSL_sk_value(ossl_check_const_OSSL_CMP_CERTRESPONSE_sk_type(sk), (idx)))
+#define sk_OSSL_CMP_CERTRESPONSE_new(cmp) ((STACK_OF(OSSL_CMP_CERTRESPONSE) *)OPENSSL_sk_new(ossl_check_OSSL_CMP_CERTRESPONSE_compfunc_type(cmp)))
+#define sk_OSSL_CMP_CERTRESPONSE_new_null() ((STACK_OF(OSSL_CMP_CERTRESPONSE) *)OPENSSL_sk_new_null())
+#define sk_OSSL_CMP_CERTRESPONSE_new_reserve(cmp, n) ((STACK_OF(OSSL_CMP_CERTRESPONSE) *)OPENSSL_sk_new_reserve(ossl_check_OSSL_CMP_CERTRESPONSE_compfunc_type(cmp), (n)))
+#define sk_OSSL_CMP_CERTRESPONSE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), (n))
+#define sk_OSSL_CMP_CERTRESPONSE_free(sk) OPENSSL_sk_free(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk))
+#define sk_OSSL_CMP_CERTRESPONSE_zero(sk) OPENSSL_sk_zero(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk))
+#define sk_OSSL_CMP_CERTRESPONSE_delete(sk, i) ((OSSL_CMP_CERTRESPONSE *)OPENSSL_sk_delete(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), (i)))
+#define sk_OSSL_CMP_CERTRESPONSE_delete_ptr(sk, ptr) ((OSSL_CMP_CERTRESPONSE *)OPENSSL_sk_delete_ptr(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr)))
+#define sk_OSSL_CMP_CERTRESPONSE_push(sk, ptr) OPENSSL_sk_push(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr))
+#define sk_OSSL_CMP_CERTRESPONSE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr))
+#define sk_OSSL_CMP_CERTRESPONSE_pop(sk) ((OSSL_CMP_CERTRESPONSE *)OPENSSL_sk_pop(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk)))
+#define sk_OSSL_CMP_CERTRESPONSE_shift(sk) ((OSSL_CMP_CERTRESPONSE *)OPENSSL_sk_shift(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk)))
+#define sk_OSSL_CMP_CERTRESPONSE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk),ossl_check_OSSL_CMP_CERTRESPONSE_freefunc_type(freefunc))
+#define sk_OSSL_CMP_CERTRESPONSE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr), (idx))
+#define sk_OSSL_CMP_CERTRESPONSE_set(sk, idx, ptr) ((OSSL_CMP_CERTRESPONSE *)OPENSSL_sk_set(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), (idx), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr)))
+#define sk_OSSL_CMP_CERTRESPONSE_find(sk, ptr) OPENSSL_sk_find(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr))
+#define sk_OSSL_CMP_CERTRESPONSE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr))
+#define sk_OSSL_CMP_CERTRESPONSE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_type(ptr), pnum)
+#define sk_OSSL_CMP_CERTRESPONSE_sort(sk) OPENSSL_sk_sort(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk))
+#define sk_OSSL_CMP_CERTRESPONSE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OSSL_CMP_CERTRESPONSE_sk_type(sk))
+#define sk_OSSL_CMP_CERTRESPONSE_dup(sk) ((STACK_OF(OSSL_CMP_CERTRESPONSE) *)OPENSSL_sk_dup(ossl_check_const_OSSL_CMP_CERTRESPONSE_sk_type(sk)))
+#define sk_OSSL_CMP_CERTRESPONSE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OSSL_CMP_CERTRESPONSE) *)OPENSSL_sk_deep_copy(ossl_check_const_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_copyfunc_type(copyfunc), ossl_check_OSSL_CMP_CERTRESPONSE_freefunc_type(freefunc)))
+#define sk_OSSL_CMP_CERTRESPONSE_set_cmp_func(sk, cmp) ((sk_OSSL_CMP_CERTRESPONSE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OSSL_CMP_CERTRESPONSE_sk_type(sk), ossl_check_OSSL_CMP_CERTRESPONSE_compfunc_type(cmp)))
+
+typedef STACK_OF(ASN1_UTF8STRING) OSSL_CMP_PKIFREETEXT;
+
+/*
+ * function DECLARATIONS
+ */
+
+/* from cmp_asn.c */
+OSSL_CMP_ITAV *OSSL_CMP_ITAV_create(ASN1_OBJECT *type, ASN1_TYPE *value);
+void OSSL_CMP_ITAV_set0(OSSL_CMP_ITAV *itav, ASN1_OBJECT *type,
+ ASN1_TYPE *value);
+ASN1_OBJECT *OSSL_CMP_ITAV_get0_type(const OSSL_CMP_ITAV *itav);
+ASN1_TYPE *OSSL_CMP_ITAV_get0_value(const OSSL_CMP_ITAV *itav);
+int OSSL_CMP_ITAV_push0_stack_item(STACK_OF(OSSL_CMP_ITAV) **itav_sk_p,
+ OSSL_CMP_ITAV *itav);
+void OSSL_CMP_ITAV_free(OSSL_CMP_ITAV *itav);
+void OSSL_CMP_MSG_free(OSSL_CMP_MSG *msg);
+
+/* from cmp_ctx.c */
+OSSL_CMP_CTX *OSSL_CMP_CTX_new(OSSL_LIB_CTX *libctx, const char *propq);
+void OSSL_CMP_CTX_free(OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_reinit(OSSL_CMP_CTX *ctx);
+/* CMP general options: */
+# define OSSL_CMP_OPT_LOG_VERBOSITY 0
+/* CMP transfer options: */
+# define OSSL_CMP_OPT_KEEP_ALIVE 10
+# define OSSL_CMP_OPT_MSG_TIMEOUT 11
+# define OSSL_CMP_OPT_TOTAL_TIMEOUT 12
+/* CMP request options: */
+# define OSSL_CMP_OPT_VALIDITY_DAYS 20
+# define OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT 21
+# define OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL 22
+# define OSSL_CMP_OPT_POLICIES_CRITICAL 23
+# define OSSL_CMP_OPT_POPO_METHOD 24
+# define OSSL_CMP_OPT_IMPLICIT_CONFIRM 25
+# define OSSL_CMP_OPT_DISABLE_CONFIRM 26
+# define OSSL_CMP_OPT_REVOCATION_REASON 27
+/* CMP protection options: */
+# define OSSL_CMP_OPT_UNPROTECTED_SEND 30
+# define OSSL_CMP_OPT_UNPROTECTED_ERRORS 31
+# define OSSL_CMP_OPT_OWF_ALGNID 32
+# define OSSL_CMP_OPT_MAC_ALGNID 33
+# define OSSL_CMP_OPT_DIGEST_ALGNID 34
+# define OSSL_CMP_OPT_IGNORE_KEYUSAGE 35
+# define OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR 36
+int OSSL_CMP_CTX_set_option(OSSL_CMP_CTX *ctx, int opt, int val);
+int OSSL_CMP_CTX_get_option(const OSSL_CMP_CTX *ctx, int opt);
+/* CMP-specific callback for logging and outputting the error queue: */
+int OSSL_CMP_CTX_set_log_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_log_cb_t cb);
+# define OSSL_CMP_CTX_set_log_verbosity(ctx, level) \
+ OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_LOG_VERBOSITY, level)
+void OSSL_CMP_CTX_print_errors(const OSSL_CMP_CTX *ctx);
+/* message transfer: */
+int OSSL_CMP_CTX_set1_serverPath(OSSL_CMP_CTX *ctx, const char *path);
+int OSSL_CMP_CTX_set1_server(OSSL_CMP_CTX *ctx, const char *address);
+int OSSL_CMP_CTX_set_serverPort(OSSL_CMP_CTX *ctx, int port);
+int OSSL_CMP_CTX_set1_proxy(OSSL_CMP_CTX *ctx, const char *name);
+int OSSL_CMP_CTX_set1_no_proxy(OSSL_CMP_CTX *ctx, const char *names);
+int OSSL_CMP_CTX_set_http_cb(OSSL_CMP_CTX *ctx, OSSL_HTTP_bio_cb_t cb);
+int OSSL_CMP_CTX_set_http_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
+void *OSSL_CMP_CTX_get_http_cb_arg(const OSSL_CMP_CTX *ctx);
+typedef OSSL_CMP_MSG *(*OSSL_CMP_transfer_cb_t) (OSSL_CMP_CTX *ctx,
+ const OSSL_CMP_MSG *req);
+int OSSL_CMP_CTX_set_transfer_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_transfer_cb_t cb);
+int OSSL_CMP_CTX_set_transfer_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
+void *OSSL_CMP_CTX_get_transfer_cb_arg(const OSSL_CMP_CTX *ctx);
+/* server authentication: */
+int OSSL_CMP_CTX_set1_srvCert(OSSL_CMP_CTX *ctx, X509 *cert);
+int OSSL_CMP_CTX_set1_expected_sender(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_set0_trustedStore(OSSL_CMP_CTX *ctx, X509_STORE *store);
+X509_STORE *OSSL_CMP_CTX_get0_trustedStore(const OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_set1_untrusted(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs);
+STACK_OF(X509) *OSSL_CMP_CTX_get0_untrusted(const OSSL_CMP_CTX *ctx);
+/* client authentication: */
+int OSSL_CMP_CTX_set1_cert(OSSL_CMP_CTX *ctx, X509 *cert);
+int OSSL_CMP_CTX_build_cert_chain(OSSL_CMP_CTX *ctx, X509_STORE *own_trusted,
+ STACK_OF(X509) *candidates);
+int OSSL_CMP_CTX_set1_pkey(OSSL_CMP_CTX *ctx, EVP_PKEY *pkey);
+int OSSL_CMP_CTX_set1_referenceValue(OSSL_CMP_CTX *ctx,
+ const unsigned char *ref, int len);
+int OSSL_CMP_CTX_set1_secretValue(OSSL_CMP_CTX *ctx, const unsigned char *sec,
+ const int len);
+/* CMP message header and extra certificates: */
+int OSSL_CMP_CTX_set1_recipient(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_push0_geninfo_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav);
+int OSSL_CMP_CTX_set1_extraCertsOut(OSSL_CMP_CTX *ctx,
+ STACK_OF(X509) *extraCertsOut);
+/* certificate template: */
+int OSSL_CMP_CTX_set0_newPkey(OSSL_CMP_CTX *ctx, int priv, EVP_PKEY *pkey);
+EVP_PKEY *OSSL_CMP_CTX_get0_newPkey(const OSSL_CMP_CTX *ctx, int priv);
+int OSSL_CMP_CTX_set1_issuer(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_set1_subjectName(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_push1_subjectAltName(OSSL_CMP_CTX *ctx,
+ const GENERAL_NAME *name);
+int OSSL_CMP_CTX_set0_reqExtensions(OSSL_CMP_CTX *ctx, X509_EXTENSIONS *exts);
+int OSSL_CMP_CTX_reqExtensions_have_SAN(OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_push0_policy(OSSL_CMP_CTX *ctx, POLICYINFO *pinfo);
+int OSSL_CMP_CTX_set1_oldCert(OSSL_CMP_CTX *ctx, X509 *cert);
+int OSSL_CMP_CTX_set1_p10CSR(OSSL_CMP_CTX *ctx, const X509_REQ *csr);
+/* misc body contents: */
+int OSSL_CMP_CTX_push0_genm_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav);
+/* certificate confirmation: */
+typedef int (*OSSL_CMP_certConf_cb_t) (OSSL_CMP_CTX *ctx, X509 *cert,
+ int fail_info, const char **txt);
+int OSSL_CMP_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info,
+ const char **text);
+int OSSL_CMP_CTX_set_certConf_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_certConf_cb_t cb);
+int OSSL_CMP_CTX_set_certConf_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
+void *OSSL_CMP_CTX_get_certConf_cb_arg(const OSSL_CMP_CTX *ctx);
+/* result fetching: */
+int OSSL_CMP_CTX_get_status(const OSSL_CMP_CTX *ctx);
+OSSL_CMP_PKIFREETEXT *OSSL_CMP_CTX_get0_statusString(const OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_get_failInfoCode(const OSSL_CMP_CTX *ctx);
+# define OSSL_CMP_PKISI_BUFLEN 1024
+X509 *OSSL_CMP_CTX_get0_newCert(const OSSL_CMP_CTX *ctx);
+STACK_OF(X509) *OSSL_CMP_CTX_get1_newChain(const OSSL_CMP_CTX *ctx);
+STACK_OF(X509) *OSSL_CMP_CTX_get1_caPubs(const OSSL_CMP_CTX *ctx);
+STACK_OF(X509) *OSSL_CMP_CTX_get1_extraCertsIn(const OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_set1_transactionID(OSSL_CMP_CTX *ctx,
+ const ASN1_OCTET_STRING *id);
+int OSSL_CMP_CTX_set1_senderNonce(OSSL_CMP_CTX *ctx,
+ const ASN1_OCTET_STRING *nonce);
+
+/* from cmp_status.c */
+char *OSSL_CMP_CTX_snprint_PKIStatus(const OSSL_CMP_CTX *ctx, char *buf,
+ size_t bufsize);
+char *OSSL_CMP_snprint_PKIStatusInfo(const OSSL_CMP_PKISI *statusInfo,
+ char *buf, size_t bufsize);
+OSSL_CMP_PKISI *
+OSSL_CMP_STATUSINFO_new(int status, int fail_info, const char *text);
+
+/* from cmp_hdr.c */
+ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_transactionID(const
+ OSSL_CMP_PKIHEADER *hdr);
+ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_recipNonce(const OSSL_CMP_PKIHEADER *hdr);
+
+/* from cmp_msg.c */
+OSSL_CMP_PKIHEADER *OSSL_CMP_MSG_get0_header(const OSSL_CMP_MSG *msg);
+int OSSL_CMP_MSG_get_bodytype(const OSSL_CMP_MSG *msg);
+int OSSL_CMP_MSG_update_transactionID(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg);
+OSSL_CRMF_MSG *OSSL_CMP_CTX_setup_CRM(OSSL_CMP_CTX *ctx, int for_KUR, int rid);
+OSSL_CMP_MSG *OSSL_CMP_MSG_read(const char *file, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int OSSL_CMP_MSG_write(const char *file, const OSSL_CMP_MSG *msg);
+OSSL_CMP_MSG *d2i_OSSL_CMP_MSG_bio(BIO *bio, OSSL_CMP_MSG **msg);
+int i2d_OSSL_CMP_MSG_bio(BIO *bio, const OSSL_CMP_MSG *msg);
+
+/* from cmp_vfy.c */
+int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg);
+int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx,
+ X509_STORE *trusted_store, X509 *cert);
+
+/* from cmp_http.c */
+OSSL_CMP_MSG *OSSL_CMP_MSG_http_perform(OSSL_CMP_CTX *ctx,
+ const OSSL_CMP_MSG *req);
+
+/* from cmp_server.c */
+typedef struct ossl_cmp_srv_ctx_st OSSL_CMP_SRV_CTX;
+OSSL_CMP_MSG *OSSL_CMP_SRV_process_request(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req);
+OSSL_CMP_MSG * OSSL_CMP_CTX_server_perform(OSSL_CMP_CTX *client_ctx,
+ const OSSL_CMP_MSG *req);
+OSSL_CMP_SRV_CTX *OSSL_CMP_SRV_CTX_new(OSSL_LIB_CTX *libctx, const char *propq);
+void OSSL_CMP_SRV_CTX_free(OSSL_CMP_SRV_CTX *srv_ctx);
+typedef OSSL_CMP_PKISI *(*OSSL_CMP_SRV_cert_request_cb_t)
+ (OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req, int certReqId,
+ const OSSL_CRMF_MSG *crm, const X509_REQ *p10cr,
+ X509 **certOut, STACK_OF(X509) **chainOut, STACK_OF(X509) **caPubs);
+typedef OSSL_CMP_PKISI *(*OSSL_CMP_SRV_rr_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ const X509_NAME *issuer,
+ const ASN1_INTEGER *serial);
+typedef int (*OSSL_CMP_SRV_genm_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ const STACK_OF(OSSL_CMP_ITAV) *in,
+ STACK_OF(OSSL_CMP_ITAV) **out);
+typedef void (*OSSL_CMP_SRV_error_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ const OSSL_CMP_PKISI *statusInfo,
+ const ASN1_INTEGER *errorCode,
+ const OSSL_CMP_PKIFREETEXT *errDetails);
+typedef int (*OSSL_CMP_SRV_certConf_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ int certReqId,
+ const ASN1_OCTET_STRING *certHash,
+ const OSSL_CMP_PKISI *si);
+typedef int (*OSSL_CMP_SRV_pollReq_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req, int certReqId,
+ OSSL_CMP_MSG **certReq,
+ int64_t *check_after);
+int OSSL_CMP_SRV_CTX_init(OSSL_CMP_SRV_CTX *srv_ctx, void *custom_ctx,
+ OSSL_CMP_SRV_cert_request_cb_t process_cert_request,
+ OSSL_CMP_SRV_rr_cb_t process_rr,
+ OSSL_CMP_SRV_genm_cb_t process_genm,
+ OSSL_CMP_SRV_error_cb_t process_error,
+ OSSL_CMP_SRV_certConf_cb_t process_certConf,
+ OSSL_CMP_SRV_pollReq_cb_t process_pollReq);
+OSSL_CMP_CTX *OSSL_CMP_SRV_CTX_get0_cmp_ctx(const OSSL_CMP_SRV_CTX *srv_ctx);
+void *OSSL_CMP_SRV_CTX_get0_custom_ctx(const OSSL_CMP_SRV_CTX *srv_ctx);
+int OSSL_CMP_SRV_CTX_set_send_unprotected_errors(OSSL_CMP_SRV_CTX *srv_ctx,
+ int val);
+int OSSL_CMP_SRV_CTX_set_accept_unprotected(OSSL_CMP_SRV_CTX *srv_ctx, int val);
+int OSSL_CMP_SRV_CTX_set_accept_raverified(OSSL_CMP_SRV_CTX *srv_ctx, int val);
+int OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(OSSL_CMP_SRV_CTX *srv_ctx,
+ int val);
+
+/* from cmp_client.c */
+X509 *OSSL_CMP_exec_certreq(OSSL_CMP_CTX *ctx, int req_type,
+ const OSSL_CRMF_MSG *crm);
+# define OSSL_CMP_IR 0
+# define OSSL_CMP_CR 2
+# define OSSL_CMP_P10CR 4
+# define OSSL_CMP_KUR 7
+# define OSSL_CMP_exec_IR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_IR, NULL)
+# define OSSL_CMP_exec_CR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_CR, NULL)
+# define OSSL_CMP_exec_P10CR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_P10CR, NULL)
+# define OSSL_CMP_exec_KUR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_KUR, NULL)
+int OSSL_CMP_try_certreq(OSSL_CMP_CTX *ctx, int req_type,
+ const OSSL_CRMF_MSG *crm, int *checkAfter);
+int OSSL_CMP_exec_RR_ses(OSSL_CMP_CTX *ctx);
+STACK_OF(OSSL_CMP_ITAV) *OSSL_CMP_exec_GENM_ses(OSSL_CMP_CTX *ctx);
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* !defined(OPENSSL_NO_CMP) */
+#endif /* !defined(OPENSSL_CMP_H) */
diff --git a/include/openssl/cmp.h.in b/include/openssl/cmp.h.in
new file mode 100644
index 00000000..b4734421
--- /dev/null
+++ b/include/openssl/cmp.h.in
@@ -0,0 +1,473 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright Nokia 2007-2019
+ * Copyright Siemens AG 2015-2019
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_CMP_H
+# define OPENSSL_CMP_H
+
+# include <openssl/opensslconf.h>
+# ifndef OPENSSL_NO_CMP
+
+# include <openssl/crmf.h>
+# include <openssl/cmperr.h>
+# include <openssl/cmp_util.h>
+# include <openssl/http.h>
+
+/* explicit #includes not strictly needed since implied by the above: */
+# include <openssl/types.h>
+# include <openssl/safestack.h>
+# include <openssl/x509.h>
+# include <openssl/x509v3.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define OSSL_CMP_PVNO 2
+
+/*-
+ * PKIFailureInfo ::= BIT STRING {
+ * -- since we can fail in more than one way!
+ * -- More codes may be added in the future if/when required.
+ * badAlg (0),
+ * -- unrecognized or unsupported Algorithm Identifier
+ * badMessageCheck (1),
+ * -- integrity check failed (e.g., signature did not verify)
+ * badRequest (2),
+ * -- transaction not permitted or supported
+ * badTime (3),
+ * -- messageTime was not sufficiently close to the system time,
+ * -- as defined by local policy
+ * badCertId (4),
+ * -- no certificate could be found matching the provided criteria
+ * badDataFormat (5),
+ * -- the data submitted has the wrong format
+ * wrongAuthority (6),
+ * -- the authority indicated in the request is different from the
+ * -- one creating the response token
+ * incorrectData (7),
+ * -- the requester's data is incorrect (for notary services)
+ * missingTimeStamp (8),
+ * -- when the timestamp is missing but should be there
+ * -- (by policy)
+ * badPOP (9),
+ * -- the proof-of-possession failed
+ * certRevoked (10),
+ * -- the certificate has already been revoked
+ * certConfirmed (11),
+ * -- the certificate has already been confirmed
+ * wrongIntegrity (12),
+ * -- invalid integrity, password based instead of signature or
+ * -- vice versa
+ * badRecipientNonce (13),
+ * -- invalid recipient nonce, either missing or wrong value
+ * timeNotAvailable (14),
+ * -- the TSA's time source is not available
+ * unacceptedPolicy (15),
+ * -- the requested TSA policy is not supported by the TSA.
+ * unacceptedExtension (16),
+ * -- the requested extension is not supported by the TSA.
+ * addInfoNotAvailable (17),
+ * -- the additional information requested could not be
+ * -- understood or is not available
+ * badSenderNonce (18),
+ * -- invalid sender nonce, either missing or wrong size
+ * badCertTemplate (19),
+ * -- invalid cert. template or missing mandatory information
+ * signerNotTrusted (20),
+ * -- signer of the message unknown or not trusted
+ * transactionIdInUse (21),
+ * -- the transaction identifier is already in use
+ * unsupportedVersion (22),
+ * -- the version of the message is not supported
+ * notAuthorized (23),
+ * -- the sender was not authorized to make the preceding
+ * -- request or perform the preceding action
+ * systemUnavail (24),
+ * -- the request cannot be handled due to system unavailability
+ * systemFailure (25),
+ * -- the request cannot be handled due to system failure
+ * duplicateCertReq (26)
+ * -- certificate cannot be issued because a duplicate
+ * -- certificate already exists
+ * }
+ */
+# define OSSL_CMP_PKIFAILUREINFO_badAlg 0
+# define OSSL_CMP_PKIFAILUREINFO_badMessageCheck 1
+# define OSSL_CMP_PKIFAILUREINFO_badRequest 2
+# define OSSL_CMP_PKIFAILUREINFO_badTime 3
+# define OSSL_CMP_PKIFAILUREINFO_badCertId 4
+# define OSSL_CMP_PKIFAILUREINFO_badDataFormat 5
+# define OSSL_CMP_PKIFAILUREINFO_wrongAuthority 6
+# define OSSL_CMP_PKIFAILUREINFO_incorrectData 7
+# define OSSL_CMP_PKIFAILUREINFO_missingTimeStamp 8
+# define OSSL_CMP_PKIFAILUREINFO_badPOP 9
+# define OSSL_CMP_PKIFAILUREINFO_certRevoked 10
+# define OSSL_CMP_PKIFAILUREINFO_certConfirmed 11
+# define OSSL_CMP_PKIFAILUREINFO_wrongIntegrity 12
+# define OSSL_CMP_PKIFAILUREINFO_badRecipientNonce 13
+# define OSSL_CMP_PKIFAILUREINFO_timeNotAvailable 14
+# define OSSL_CMP_PKIFAILUREINFO_unacceptedPolicy 15
+# define OSSL_CMP_PKIFAILUREINFO_unacceptedExtension 16
+# define OSSL_CMP_PKIFAILUREINFO_addInfoNotAvailable 17
+# define OSSL_CMP_PKIFAILUREINFO_badSenderNonce 18
+# define OSSL_CMP_PKIFAILUREINFO_badCertTemplate 19
+# define OSSL_CMP_PKIFAILUREINFO_signerNotTrusted 20
+# define OSSL_CMP_PKIFAILUREINFO_transactionIdInUse 21
+# define OSSL_CMP_PKIFAILUREINFO_unsupportedVersion 22
+# define OSSL_CMP_PKIFAILUREINFO_notAuthorized 23
+# define OSSL_CMP_PKIFAILUREINFO_systemUnavail 24
+# define OSSL_CMP_PKIFAILUREINFO_systemFailure 25
+# define OSSL_CMP_PKIFAILUREINFO_duplicateCertReq 26
+# define OSSL_CMP_PKIFAILUREINFO_MAX 26
+# define OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN \
+ ((1 << (OSSL_CMP_PKIFAILUREINFO_MAX + 1)) - 1)
+# if OSSL_CMP_PKIFAILUREINFO_MAX_BIT_PATTERN > INT_MAX
+# error CMP_PKIFAILUREINFO_MAX bit pattern does not fit in type int
+# endif
+
+typedef ASN1_BIT_STRING OSSL_CMP_PKIFAILUREINFO;
+
+# define OSSL_CMP_CTX_FAILINFO_badAlg (1 << 0)
+# define OSSL_CMP_CTX_FAILINFO_badMessageCheck (1 << 1)
+# define OSSL_CMP_CTX_FAILINFO_badRequest (1 << 2)
+# define OSSL_CMP_CTX_FAILINFO_badTime (1 << 3)
+# define OSSL_CMP_CTX_FAILINFO_badCertId (1 << 4)
+# define OSSL_CMP_CTX_FAILINFO_badDataFormat (1 << 5)
+# define OSSL_CMP_CTX_FAILINFO_wrongAuthority (1 << 6)
+# define OSSL_CMP_CTX_FAILINFO_incorrectData (1 << 7)
+# define OSSL_CMP_CTX_FAILINFO_missingTimeStamp (1 << 8)
+# define OSSL_CMP_CTX_FAILINFO_badPOP (1 << 9)
+# define OSSL_CMP_CTX_FAILINFO_certRevoked (1 << 10)
+# define OSSL_CMP_CTX_FAILINFO_certConfirmed (1 << 11)
+# define OSSL_CMP_CTX_FAILINFO_wrongIntegrity (1 << 12)
+# define OSSL_CMP_CTX_FAILINFO_badRecipientNonce (1 << 13)
+# define OSSL_CMP_CTX_FAILINFO_timeNotAvailable (1 << 14)
+# define OSSL_CMP_CTX_FAILINFO_unacceptedPolicy (1 << 15)
+# define OSSL_CMP_CTX_FAILINFO_unacceptedExtension (1 << 16)
+# define OSSL_CMP_CTX_FAILINFO_addInfoNotAvailable (1 << 17)
+# define OSSL_CMP_CTX_FAILINFO_badSenderNonce (1 << 18)
+# define OSSL_CMP_CTX_FAILINFO_badCertTemplate (1 << 19)
+# define OSSL_CMP_CTX_FAILINFO_signerNotTrusted (1 << 20)
+# define OSSL_CMP_CTX_FAILINFO_transactionIdInUse (1 << 21)
+# define OSSL_CMP_CTX_FAILINFO_unsupportedVersion (1 << 22)
+# define OSSL_CMP_CTX_FAILINFO_notAuthorized (1 << 23)
+# define OSSL_CMP_CTX_FAILINFO_systemUnavail (1 << 24)
+# define OSSL_CMP_CTX_FAILINFO_systemFailure (1 << 25)
+# define OSSL_CMP_CTX_FAILINFO_duplicateCertReq (1 << 26)
+
+/*-
+ * PKIStatus ::= INTEGER {
+ * accepted (0),
+ * -- you got exactly what you asked for
+ * grantedWithMods (1),
+ * -- you got something like what you asked for; the
+ * -- requester is responsible for ascertaining the differences
+ * rejection (2),
+ * -- you don't get it, more information elsewhere in the message
+ * waiting (3),
+ * -- the request body part has not yet been processed; expect to
+ * -- hear more later (note: proper handling of this status
+ * -- response MAY use the polling req/rep PKIMessages specified
+ * -- in Section 5.3.22; alternatively, polling in the underlying
+ * -- transport layer MAY have some utility in this regard)
+ * revocationWarning (4),
+ * -- this message contains a warning that a revocation is
+ * -- imminent
+ * revocationNotification (5),
+ * -- notification that a revocation has occurred
+ * keyUpdateWarning (6)
+ * -- update already done for the oldCertId specified in
+ * -- CertReqMsg
+ * }
+ */
+# define OSSL_CMP_PKISTATUS_accepted 0
+# define OSSL_CMP_PKISTATUS_grantedWithMods 1
+# define OSSL_CMP_PKISTATUS_rejection 2
+# define OSSL_CMP_PKISTATUS_waiting 3
+# define OSSL_CMP_PKISTATUS_revocationWarning 4
+# define OSSL_CMP_PKISTATUS_revocationNotification 5
+# define OSSL_CMP_PKISTATUS_keyUpdateWarning 6
+
+typedef ASN1_INTEGER OSSL_CMP_PKISTATUS;
+DECLARE_ASN1_ITEM(OSSL_CMP_PKISTATUS)
+
+# define OSSL_CMP_CERTORENCCERT_CERTIFICATE 0
+# define OSSL_CMP_CERTORENCCERT_ENCRYPTEDCERT 1
+
+/* data type declarations */
+typedef struct ossl_cmp_ctx_st OSSL_CMP_CTX;
+typedef struct ossl_cmp_pkiheader_st OSSL_CMP_PKIHEADER;
+DECLARE_ASN1_FUNCTIONS(OSSL_CMP_PKIHEADER)
+typedef struct ossl_cmp_msg_st OSSL_CMP_MSG;
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CMP_MSG)
+DECLARE_ASN1_ENCODE_FUNCTIONS(OSSL_CMP_MSG, OSSL_CMP_MSG, OSSL_CMP_MSG)
+typedef struct ossl_cmp_certstatus_st OSSL_CMP_CERTSTATUS;
+{-
+ generate_stack_macros("OSSL_CMP_CERTSTATUS");
+-}
+typedef struct ossl_cmp_itav_st OSSL_CMP_ITAV;
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CMP_ITAV)
+{-
+ generate_stack_macros("OSSL_CMP_ITAV");
+-}
+typedef struct ossl_cmp_revrepcontent_st OSSL_CMP_REVREPCONTENT;
+typedef struct ossl_cmp_pkisi_st OSSL_CMP_PKISI;
+DECLARE_ASN1_FUNCTIONS(OSSL_CMP_PKISI)
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CMP_PKISI)
+{-
+ generate_stack_macros("OSSL_CMP_PKISI");
+-}
+typedef struct ossl_cmp_certrepmessage_st OSSL_CMP_CERTREPMESSAGE;
+{-
+ generate_stack_macros("OSSL_CMP_CERTREPMESSAGE");
+-}
+typedef struct ossl_cmp_pollrep_st OSSL_CMP_POLLREP;
+typedef STACK_OF(OSSL_CMP_POLLREP) OSSL_CMP_POLLREPCONTENT;
+typedef struct ossl_cmp_certresponse_st OSSL_CMP_CERTRESPONSE;
+{-
+ generate_stack_macros("OSSL_CMP_CERTRESPONSE");
+-}
+typedef STACK_OF(ASN1_UTF8STRING) OSSL_CMP_PKIFREETEXT;
+
+/*
+ * function DECLARATIONS
+ */
+
+/* from cmp_asn.c */
+OSSL_CMP_ITAV *OSSL_CMP_ITAV_create(ASN1_OBJECT *type, ASN1_TYPE *value);
+void OSSL_CMP_ITAV_set0(OSSL_CMP_ITAV *itav, ASN1_OBJECT *type,
+ ASN1_TYPE *value);
+ASN1_OBJECT *OSSL_CMP_ITAV_get0_type(const OSSL_CMP_ITAV *itav);
+ASN1_TYPE *OSSL_CMP_ITAV_get0_value(const OSSL_CMP_ITAV *itav);
+int OSSL_CMP_ITAV_push0_stack_item(STACK_OF(OSSL_CMP_ITAV) **itav_sk_p,
+ OSSL_CMP_ITAV *itav);
+void OSSL_CMP_ITAV_free(OSSL_CMP_ITAV *itav);
+void OSSL_CMP_MSG_free(OSSL_CMP_MSG *msg);
+
+/* from cmp_ctx.c */
+OSSL_CMP_CTX *OSSL_CMP_CTX_new(OSSL_LIB_CTX *libctx, const char *propq);
+void OSSL_CMP_CTX_free(OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_reinit(OSSL_CMP_CTX *ctx);
+/* CMP general options: */
+# define OSSL_CMP_OPT_LOG_VERBOSITY 0
+/* CMP transfer options: */
+# define OSSL_CMP_OPT_KEEP_ALIVE 10
+# define OSSL_CMP_OPT_MSG_TIMEOUT 11
+# define OSSL_CMP_OPT_TOTAL_TIMEOUT 12
+/* CMP request options: */
+# define OSSL_CMP_OPT_VALIDITY_DAYS 20
+# define OSSL_CMP_OPT_SUBJECTALTNAME_NODEFAULT 21
+# define OSSL_CMP_OPT_SUBJECTALTNAME_CRITICAL 22
+# define OSSL_CMP_OPT_POLICIES_CRITICAL 23
+# define OSSL_CMP_OPT_POPO_METHOD 24
+# define OSSL_CMP_OPT_IMPLICIT_CONFIRM 25
+# define OSSL_CMP_OPT_DISABLE_CONFIRM 26
+# define OSSL_CMP_OPT_REVOCATION_REASON 27
+/* CMP protection options: */
+# define OSSL_CMP_OPT_UNPROTECTED_SEND 30
+# define OSSL_CMP_OPT_UNPROTECTED_ERRORS 31
+# define OSSL_CMP_OPT_OWF_ALGNID 32
+# define OSSL_CMP_OPT_MAC_ALGNID 33
+# define OSSL_CMP_OPT_DIGEST_ALGNID 34
+# define OSSL_CMP_OPT_IGNORE_KEYUSAGE 35
+# define OSSL_CMP_OPT_PERMIT_TA_IN_EXTRACERTS_FOR_IR 36
+int OSSL_CMP_CTX_set_option(OSSL_CMP_CTX *ctx, int opt, int val);
+int OSSL_CMP_CTX_get_option(const OSSL_CMP_CTX *ctx, int opt);
+/* CMP-specific callback for logging and outputting the error queue: */
+int OSSL_CMP_CTX_set_log_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_log_cb_t cb);
+# define OSSL_CMP_CTX_set_log_verbosity(ctx, level) \
+ OSSL_CMP_CTX_set_option(ctx, OSSL_CMP_OPT_LOG_VERBOSITY, level)
+void OSSL_CMP_CTX_print_errors(const OSSL_CMP_CTX *ctx);
+/* message transfer: */
+int OSSL_CMP_CTX_set1_serverPath(OSSL_CMP_CTX *ctx, const char *path);
+int OSSL_CMP_CTX_set1_server(OSSL_CMP_CTX *ctx, const char *address);
+int OSSL_CMP_CTX_set_serverPort(OSSL_CMP_CTX *ctx, int port);
+int OSSL_CMP_CTX_set1_proxy(OSSL_CMP_CTX *ctx, const char *name);
+int OSSL_CMP_CTX_set1_no_proxy(OSSL_CMP_CTX *ctx, const char *names);
+int OSSL_CMP_CTX_set_http_cb(OSSL_CMP_CTX *ctx, OSSL_HTTP_bio_cb_t cb);
+int OSSL_CMP_CTX_set_http_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
+void *OSSL_CMP_CTX_get_http_cb_arg(const OSSL_CMP_CTX *ctx);
+typedef OSSL_CMP_MSG *(*OSSL_CMP_transfer_cb_t) (OSSL_CMP_CTX *ctx,
+ const OSSL_CMP_MSG *req);
+int OSSL_CMP_CTX_set_transfer_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_transfer_cb_t cb);
+int OSSL_CMP_CTX_set_transfer_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
+void *OSSL_CMP_CTX_get_transfer_cb_arg(const OSSL_CMP_CTX *ctx);
+/* server authentication: */
+int OSSL_CMP_CTX_set1_srvCert(OSSL_CMP_CTX *ctx, X509 *cert);
+int OSSL_CMP_CTX_set1_expected_sender(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_set0_trustedStore(OSSL_CMP_CTX *ctx, X509_STORE *store);
+X509_STORE *OSSL_CMP_CTX_get0_trustedStore(const OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_set1_untrusted(OSSL_CMP_CTX *ctx, STACK_OF(X509) *certs);
+STACK_OF(X509) *OSSL_CMP_CTX_get0_untrusted(const OSSL_CMP_CTX *ctx);
+/* client authentication: */
+int OSSL_CMP_CTX_set1_cert(OSSL_CMP_CTX *ctx, X509 *cert);
+int OSSL_CMP_CTX_build_cert_chain(OSSL_CMP_CTX *ctx, X509_STORE *own_trusted,
+ STACK_OF(X509) *candidates);
+int OSSL_CMP_CTX_set1_pkey(OSSL_CMP_CTX *ctx, EVP_PKEY *pkey);
+int OSSL_CMP_CTX_set1_referenceValue(OSSL_CMP_CTX *ctx,
+ const unsigned char *ref, int len);
+int OSSL_CMP_CTX_set1_secretValue(OSSL_CMP_CTX *ctx, const unsigned char *sec,
+ const int len);
+/* CMP message header and extra certificates: */
+int OSSL_CMP_CTX_set1_recipient(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_push0_geninfo_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav);
+int OSSL_CMP_CTX_set1_extraCertsOut(OSSL_CMP_CTX *ctx,
+ STACK_OF(X509) *extraCertsOut);
+/* certificate template: */
+int OSSL_CMP_CTX_set0_newPkey(OSSL_CMP_CTX *ctx, int priv, EVP_PKEY *pkey);
+EVP_PKEY *OSSL_CMP_CTX_get0_newPkey(const OSSL_CMP_CTX *ctx, int priv);
+int OSSL_CMP_CTX_set1_issuer(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_set1_subjectName(OSSL_CMP_CTX *ctx, const X509_NAME *name);
+int OSSL_CMP_CTX_push1_subjectAltName(OSSL_CMP_CTX *ctx,
+ const GENERAL_NAME *name);
+int OSSL_CMP_CTX_set0_reqExtensions(OSSL_CMP_CTX *ctx, X509_EXTENSIONS *exts);
+int OSSL_CMP_CTX_reqExtensions_have_SAN(OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_push0_policy(OSSL_CMP_CTX *ctx, POLICYINFO *pinfo);
+int OSSL_CMP_CTX_set1_oldCert(OSSL_CMP_CTX *ctx, X509 *cert);
+int OSSL_CMP_CTX_set1_p10CSR(OSSL_CMP_CTX *ctx, const X509_REQ *csr);
+/* misc body contents: */
+int OSSL_CMP_CTX_push0_genm_ITAV(OSSL_CMP_CTX *ctx, OSSL_CMP_ITAV *itav);
+/* certificate confirmation: */
+typedef int (*OSSL_CMP_certConf_cb_t) (OSSL_CMP_CTX *ctx, X509 *cert,
+ int fail_info, const char **txt);
+int OSSL_CMP_certConf_cb(OSSL_CMP_CTX *ctx, X509 *cert, int fail_info,
+ const char **text);
+int OSSL_CMP_CTX_set_certConf_cb(OSSL_CMP_CTX *ctx, OSSL_CMP_certConf_cb_t cb);
+int OSSL_CMP_CTX_set_certConf_cb_arg(OSSL_CMP_CTX *ctx, void *arg);
+void *OSSL_CMP_CTX_get_certConf_cb_arg(const OSSL_CMP_CTX *ctx);
+/* result fetching: */
+int OSSL_CMP_CTX_get_status(const OSSL_CMP_CTX *ctx);
+OSSL_CMP_PKIFREETEXT *OSSL_CMP_CTX_get0_statusString(const OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_get_failInfoCode(const OSSL_CMP_CTX *ctx);
+# define OSSL_CMP_PKISI_BUFLEN 1024
+X509 *OSSL_CMP_CTX_get0_newCert(const OSSL_CMP_CTX *ctx);
+STACK_OF(X509) *OSSL_CMP_CTX_get1_newChain(const OSSL_CMP_CTX *ctx);
+STACK_OF(X509) *OSSL_CMP_CTX_get1_caPubs(const OSSL_CMP_CTX *ctx);
+STACK_OF(X509) *OSSL_CMP_CTX_get1_extraCertsIn(const OSSL_CMP_CTX *ctx);
+int OSSL_CMP_CTX_set1_transactionID(OSSL_CMP_CTX *ctx,
+ const ASN1_OCTET_STRING *id);
+int OSSL_CMP_CTX_set1_senderNonce(OSSL_CMP_CTX *ctx,
+ const ASN1_OCTET_STRING *nonce);
+
+/* from cmp_status.c */
+char *OSSL_CMP_CTX_snprint_PKIStatus(const OSSL_CMP_CTX *ctx, char *buf,
+ size_t bufsize);
+char *OSSL_CMP_snprint_PKIStatusInfo(const OSSL_CMP_PKISI *statusInfo,
+ char *buf, size_t bufsize);
+OSSL_CMP_PKISI *
+OSSL_CMP_STATUSINFO_new(int status, int fail_info, const char *text);
+
+/* from cmp_hdr.c */
+ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_transactionID(const
+ OSSL_CMP_PKIHEADER *hdr);
+ASN1_OCTET_STRING *OSSL_CMP_HDR_get0_recipNonce(const OSSL_CMP_PKIHEADER *hdr);
+
+/* from cmp_msg.c */
+OSSL_CMP_PKIHEADER *OSSL_CMP_MSG_get0_header(const OSSL_CMP_MSG *msg);
+int OSSL_CMP_MSG_get_bodytype(const OSSL_CMP_MSG *msg);
+int OSSL_CMP_MSG_update_transactionID(OSSL_CMP_CTX *ctx, OSSL_CMP_MSG *msg);
+OSSL_CRMF_MSG *OSSL_CMP_CTX_setup_CRM(OSSL_CMP_CTX *ctx, int for_KUR, int rid);
+OSSL_CMP_MSG *OSSL_CMP_MSG_read(const char *file, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int OSSL_CMP_MSG_write(const char *file, const OSSL_CMP_MSG *msg);
+OSSL_CMP_MSG *d2i_OSSL_CMP_MSG_bio(BIO *bio, OSSL_CMP_MSG **msg);
+int i2d_OSSL_CMP_MSG_bio(BIO *bio, const OSSL_CMP_MSG *msg);
+
+/* from cmp_vfy.c */
+int OSSL_CMP_validate_msg(OSSL_CMP_CTX *ctx, const OSSL_CMP_MSG *msg);
+int OSSL_CMP_validate_cert_path(const OSSL_CMP_CTX *ctx,
+ X509_STORE *trusted_store, X509 *cert);
+
+/* from cmp_http.c */
+OSSL_CMP_MSG *OSSL_CMP_MSG_http_perform(OSSL_CMP_CTX *ctx,
+ const OSSL_CMP_MSG *req);
+
+/* from cmp_server.c */
+typedef struct ossl_cmp_srv_ctx_st OSSL_CMP_SRV_CTX;
+OSSL_CMP_MSG *OSSL_CMP_SRV_process_request(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req);
+OSSL_CMP_MSG * OSSL_CMP_CTX_server_perform(OSSL_CMP_CTX *client_ctx,
+ const OSSL_CMP_MSG *req);
+OSSL_CMP_SRV_CTX *OSSL_CMP_SRV_CTX_new(OSSL_LIB_CTX *libctx, const char *propq);
+void OSSL_CMP_SRV_CTX_free(OSSL_CMP_SRV_CTX *srv_ctx);
+typedef OSSL_CMP_PKISI *(*OSSL_CMP_SRV_cert_request_cb_t)
+ (OSSL_CMP_SRV_CTX *srv_ctx, const OSSL_CMP_MSG *req, int certReqId,
+ const OSSL_CRMF_MSG *crm, const X509_REQ *p10cr,
+ X509 **certOut, STACK_OF(X509) **chainOut, STACK_OF(X509) **caPubs);
+typedef OSSL_CMP_PKISI *(*OSSL_CMP_SRV_rr_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ const X509_NAME *issuer,
+ const ASN1_INTEGER *serial);
+typedef int (*OSSL_CMP_SRV_genm_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ const STACK_OF(OSSL_CMP_ITAV) *in,
+ STACK_OF(OSSL_CMP_ITAV) **out);
+typedef void (*OSSL_CMP_SRV_error_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ const OSSL_CMP_PKISI *statusInfo,
+ const ASN1_INTEGER *errorCode,
+ const OSSL_CMP_PKIFREETEXT *errDetails);
+typedef int (*OSSL_CMP_SRV_certConf_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req,
+ int certReqId,
+ const ASN1_OCTET_STRING *certHash,
+ const OSSL_CMP_PKISI *si);
+typedef int (*OSSL_CMP_SRV_pollReq_cb_t)(OSSL_CMP_SRV_CTX *srv_ctx,
+ const OSSL_CMP_MSG *req, int certReqId,
+ OSSL_CMP_MSG **certReq,
+ int64_t *check_after);
+int OSSL_CMP_SRV_CTX_init(OSSL_CMP_SRV_CTX *srv_ctx, void *custom_ctx,
+ OSSL_CMP_SRV_cert_request_cb_t process_cert_request,
+ OSSL_CMP_SRV_rr_cb_t process_rr,
+ OSSL_CMP_SRV_genm_cb_t process_genm,
+ OSSL_CMP_SRV_error_cb_t process_error,
+ OSSL_CMP_SRV_certConf_cb_t process_certConf,
+ OSSL_CMP_SRV_pollReq_cb_t process_pollReq);
+OSSL_CMP_CTX *OSSL_CMP_SRV_CTX_get0_cmp_ctx(const OSSL_CMP_SRV_CTX *srv_ctx);
+void *OSSL_CMP_SRV_CTX_get0_custom_ctx(const OSSL_CMP_SRV_CTX *srv_ctx);
+int OSSL_CMP_SRV_CTX_set_send_unprotected_errors(OSSL_CMP_SRV_CTX *srv_ctx,
+ int val);
+int OSSL_CMP_SRV_CTX_set_accept_unprotected(OSSL_CMP_SRV_CTX *srv_ctx, int val);
+int OSSL_CMP_SRV_CTX_set_accept_raverified(OSSL_CMP_SRV_CTX *srv_ctx, int val);
+int OSSL_CMP_SRV_CTX_set_grant_implicit_confirm(OSSL_CMP_SRV_CTX *srv_ctx,
+ int val);
+
+/* from cmp_client.c */
+X509 *OSSL_CMP_exec_certreq(OSSL_CMP_CTX *ctx, int req_type,
+ const OSSL_CRMF_MSG *crm);
+# define OSSL_CMP_IR 0
+# define OSSL_CMP_CR 2
+# define OSSL_CMP_P10CR 4
+# define OSSL_CMP_KUR 7
+# define OSSL_CMP_exec_IR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_IR, NULL)
+# define OSSL_CMP_exec_CR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_CR, NULL)
+# define OSSL_CMP_exec_P10CR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_P10CR, NULL)
+# define OSSL_CMP_exec_KUR_ses(ctx) \
+ OSSL_CMP_exec_certreq(ctx, OSSL_CMP_KUR, NULL)
+int OSSL_CMP_try_certreq(OSSL_CMP_CTX *ctx, int req_type,
+ const OSSL_CRMF_MSG *crm, int *checkAfter);
+int OSSL_CMP_exec_RR_ses(OSSL_CMP_CTX *ctx);
+STACK_OF(OSSL_CMP_ITAV) *OSSL_CMP_exec_GENM_ses(OSSL_CMP_CTX *ctx);
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* !defined(OPENSSL_NO_CMP) */
+#endif /* !defined(OPENSSL_CMP_H) */
diff --git a/include/openssl/cmp_util.h b/include/openssl/cmp_util.h
new file mode 100644
index 00000000..9a168922
--- /dev/null
+++ b/include/openssl/cmp_util.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright Nokia 2007-2019
+ * Copyright Siemens AG 2015-2019
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CMP_UTIL_H
+# define OPENSSL_CMP_UTIL_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# ifndef OPENSSL_NO_CMP
+
+# include <openssl/macros.h>
+# include <openssl/trace.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int OSSL_CMP_log_open(void);
+void OSSL_CMP_log_close(void);
+# define OSSL_CMP_LOG_PREFIX "CMP "
+
+/*
+ * generalized logging/error callback mirroring the severity levels of syslog.h
+ */
+typedef int OSSL_CMP_severity;
+# define OSSL_CMP_LOG_EMERG 0
+# define OSSL_CMP_LOG_ALERT 1
+# define OSSL_CMP_LOG_CRIT 2
+# define OSSL_CMP_LOG_ERR 3
+# define OSSL_CMP_LOG_WARNING 4
+# define OSSL_CMP_LOG_NOTICE 5
+# define OSSL_CMP_LOG_INFO 6
+# define OSSL_CMP_LOG_DEBUG 7
+# define OSSL_CMP_LOG_TRACE 8
+# define OSSL_CMP_LOG_MAX OSSL_CMP_LOG_TRACE
+typedef int (*OSSL_CMP_log_cb_t)(const char *func, const char *file, int line,
+ OSSL_CMP_severity level, const char *msg);
+
+int OSSL_CMP_print_to_bio(BIO *bio, const char *component, const char *file,
+ int line, OSSL_CMP_severity level, const char *msg);
+/* use of the logging callback for outputting error queue */
+void OSSL_CMP_print_errors_cb(OSSL_CMP_log_cb_t log_fn);
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* !defined(OPENSSL_NO_CMP) */
+#endif /* !defined(OPENSSL_CMP_UTIL_H) */
diff --git a/include/openssl/cmperr.h b/include/openssl/cmperr.h
new file mode 100644
index 00000000..3a26fd0b
--- /dev/null
+++ b/include/openssl/cmperr.h
@@ -0,0 +1,112 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CMPERR_H
+# define OPENSSL_CMPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_CMP
+
+
+/*
+ * CMP reason codes.
+ */
+# define CMP_R_ALGORITHM_NOT_SUPPORTED 139
+# define CMP_R_BAD_CHECKAFTER_IN_POLLREP 167
+# define CMP_R_BAD_REQUEST_ID 108
+# define CMP_R_CERTHASH_UNMATCHED 156
+# define CMP_R_CERTID_NOT_FOUND 109
+# define CMP_R_CERTIFICATE_NOT_ACCEPTED 169
+# define CMP_R_CERTIFICATE_NOT_FOUND 112
+# define CMP_R_CERTREQMSG_NOT_FOUND 157
+# define CMP_R_CERTRESPONSE_NOT_FOUND 113
+# define CMP_R_CERT_AND_KEY_DO_NOT_MATCH 114
+# define CMP_R_CHECKAFTER_OUT_OF_RANGE 181
+# define CMP_R_ENCOUNTERED_KEYUPDATEWARNING 176
+# define CMP_R_ENCOUNTERED_WAITING 162
+# define CMP_R_ERROR_CALCULATING_PROTECTION 115
+# define CMP_R_ERROR_CREATING_CERTCONF 116
+# define CMP_R_ERROR_CREATING_CERTREP 117
+# define CMP_R_ERROR_CREATING_CERTREQ 163
+# define CMP_R_ERROR_CREATING_ERROR 118
+# define CMP_R_ERROR_CREATING_GENM 119
+# define CMP_R_ERROR_CREATING_GENP 120
+# define CMP_R_ERROR_CREATING_PKICONF 122
+# define CMP_R_ERROR_CREATING_POLLREP 123
+# define CMP_R_ERROR_CREATING_POLLREQ 124
+# define CMP_R_ERROR_CREATING_RP 125
+# define CMP_R_ERROR_CREATING_RR 126
+# define CMP_R_ERROR_PARSING_PKISTATUS 107
+# define CMP_R_ERROR_PROCESSING_MESSAGE 158
+# define CMP_R_ERROR_PROTECTING_MESSAGE 127
+# define CMP_R_ERROR_SETTING_CERTHASH 128
+# define CMP_R_ERROR_UNEXPECTED_CERTCONF 160
+# define CMP_R_ERROR_VALIDATING_PROTECTION 140
+# define CMP_R_ERROR_VALIDATING_SIGNATURE 171
+# define CMP_R_FAILED_BUILDING_OWN_CHAIN 164
+# define CMP_R_FAILED_EXTRACTING_PUBKEY 141
+# define CMP_R_FAILURE_OBTAINING_RANDOM 110
+# define CMP_R_FAIL_INFO_OUT_OF_RANGE 129
+# define CMP_R_INVALID_ARGS 100
+# define CMP_R_INVALID_OPTION 174
+# define CMP_R_MISSING_CERTID 165
+# define CMP_R_MISSING_KEY_INPUT_FOR_CREATING_PROTECTION 130
+# define CMP_R_MISSING_KEY_USAGE_DIGITALSIGNATURE 142
+# define CMP_R_MISSING_P10CSR 121
+# define CMP_R_MISSING_PBM_SECRET 166
+# define CMP_R_MISSING_PRIVATE_KEY 131
+# define CMP_R_MISSING_PROTECTION 143
+# define CMP_R_MISSING_REFERENCE_CERT 168
+# define CMP_R_MISSING_SENDER_IDENTIFICATION 111
+# define CMP_R_MISSING_TRUST_STORE 144
+# define CMP_R_MULTIPLE_REQUESTS_NOT_SUPPORTED 161
+# define CMP_R_MULTIPLE_RESPONSES_NOT_SUPPORTED 170
+# define CMP_R_MULTIPLE_SAN_SOURCES 102
+# define CMP_R_NO_STDIO 194
+# define CMP_R_NO_SUITABLE_SENDER_CERT 145
+# define CMP_R_NULL_ARGUMENT 103
+# define CMP_R_PKIBODY_ERROR 146
+# define CMP_R_PKISTATUSINFO_NOT_FOUND 132
+# define CMP_R_POLLING_FAILED 172
+# define CMP_R_POTENTIALLY_INVALID_CERTIFICATE 147
+# define CMP_R_RECEIVED_ERROR 180
+# define CMP_R_RECIPNONCE_UNMATCHED 148
+# define CMP_R_REQUEST_NOT_ACCEPTED 149
+# define CMP_R_REQUEST_REJECTED_BY_SERVER 182
+# define CMP_R_SENDER_GENERALNAME_TYPE_NOT_SUPPORTED 150
+# define CMP_R_SRVCERT_DOES_NOT_VALIDATE_MSG 151
+# define CMP_R_TOTAL_TIMEOUT 184
+# define CMP_R_TRANSACTIONID_UNMATCHED 152
+# define CMP_R_TRANSFER_ERROR 159
+# define CMP_R_UNEXPECTED_PKIBODY 133
+# define CMP_R_UNEXPECTED_PKISTATUS 185
+# define CMP_R_UNEXPECTED_PVNO 153
+# define CMP_R_UNKNOWN_ALGORITHM_ID 134
+# define CMP_R_UNKNOWN_CERT_TYPE 135
+# define CMP_R_UNKNOWN_PKISTATUS 186
+# define CMP_R_UNSUPPORTED_ALGORITHM 136
+# define CMP_R_UNSUPPORTED_KEY_TYPE 137
+# define CMP_R_UNSUPPORTED_PROTECTION_ALG_DHBASEDMAC 154
+# define CMP_R_VALUE_TOO_LARGE 175
+# define CMP_R_VALUE_TOO_SMALL 177
+# define CMP_R_WRONG_ALGORITHM_OID 138
+# define CMP_R_WRONG_CERTID 189
+# define CMP_R_WRONG_CERTID_IN_RP 187
+# define CMP_R_WRONG_PBM_VALUE 155
+# define CMP_R_WRONG_RP_COMPONENT_COUNT 188
+# define CMP_R_WRONG_SERIAL_IN_RP 173
+
+# endif
+#endif
diff --git a/include/openssl/cms.h b/include/openssl/cms.h
new file mode 100644
index 00000000..5b907f2c
--- /dev/null
+++ b/include/openssl/cms.h
@@ -0,0 +1,493 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\cms.h.in
+ *
+ * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_CMS_H
+# define OPENSSL_CMS_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CMS_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CMS
+# include <openssl/x509.h>
+# include <openssl/x509v3.h>
+# include <openssl/cmserr.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+typedef struct CMS_ContentInfo_st CMS_ContentInfo;
+typedef struct CMS_SignerInfo_st CMS_SignerInfo;
+typedef struct CMS_CertificateChoices CMS_CertificateChoices;
+typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice;
+typedef struct CMS_RecipientInfo_st CMS_RecipientInfo;
+typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest;
+typedef struct CMS_Receipt_st CMS_Receipt;
+typedef struct CMS_RecipientEncryptedKey_st CMS_RecipientEncryptedKey;
+typedef struct CMS_OtherKeyAttribute_st CMS_OtherKeyAttribute;
+
+SKM_DEFINE_STACK_OF_INTERNAL(CMS_SignerInfo, CMS_SignerInfo, CMS_SignerInfo)
+#define sk_CMS_SignerInfo_num(sk) OPENSSL_sk_num(ossl_check_const_CMS_SignerInfo_sk_type(sk))
+#define sk_CMS_SignerInfo_value(sk, idx) ((CMS_SignerInfo *)OPENSSL_sk_value(ossl_check_const_CMS_SignerInfo_sk_type(sk), (idx)))
+#define sk_CMS_SignerInfo_new(cmp) ((STACK_OF(CMS_SignerInfo) *)OPENSSL_sk_new(ossl_check_CMS_SignerInfo_compfunc_type(cmp)))
+#define sk_CMS_SignerInfo_new_null() ((STACK_OF(CMS_SignerInfo) *)OPENSSL_sk_new_null())
+#define sk_CMS_SignerInfo_new_reserve(cmp, n) ((STACK_OF(CMS_SignerInfo) *)OPENSSL_sk_new_reserve(ossl_check_CMS_SignerInfo_compfunc_type(cmp), (n)))
+#define sk_CMS_SignerInfo_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_CMS_SignerInfo_sk_type(sk), (n))
+#define sk_CMS_SignerInfo_free(sk) OPENSSL_sk_free(ossl_check_CMS_SignerInfo_sk_type(sk))
+#define sk_CMS_SignerInfo_zero(sk) OPENSSL_sk_zero(ossl_check_CMS_SignerInfo_sk_type(sk))
+#define sk_CMS_SignerInfo_delete(sk, i) ((CMS_SignerInfo *)OPENSSL_sk_delete(ossl_check_CMS_SignerInfo_sk_type(sk), (i)))
+#define sk_CMS_SignerInfo_delete_ptr(sk, ptr) ((CMS_SignerInfo *)OPENSSL_sk_delete_ptr(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_type(ptr)))
+#define sk_CMS_SignerInfo_push(sk, ptr) OPENSSL_sk_push(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_type(ptr))
+#define sk_CMS_SignerInfo_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_type(ptr))
+#define sk_CMS_SignerInfo_pop(sk) ((CMS_SignerInfo *)OPENSSL_sk_pop(ossl_check_CMS_SignerInfo_sk_type(sk)))
+#define sk_CMS_SignerInfo_shift(sk) ((CMS_SignerInfo *)OPENSSL_sk_shift(ossl_check_CMS_SignerInfo_sk_type(sk)))
+#define sk_CMS_SignerInfo_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_CMS_SignerInfo_sk_type(sk),ossl_check_CMS_SignerInfo_freefunc_type(freefunc))
+#define sk_CMS_SignerInfo_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_type(ptr), (idx))
+#define sk_CMS_SignerInfo_set(sk, idx, ptr) ((CMS_SignerInfo *)OPENSSL_sk_set(ossl_check_CMS_SignerInfo_sk_type(sk), (idx), ossl_check_CMS_SignerInfo_type(ptr)))
+#define sk_CMS_SignerInfo_find(sk, ptr) OPENSSL_sk_find(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_type(ptr))
+#define sk_CMS_SignerInfo_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_type(ptr))
+#define sk_CMS_SignerInfo_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_type(ptr), pnum)
+#define sk_CMS_SignerInfo_sort(sk) OPENSSL_sk_sort(ossl_check_CMS_SignerInfo_sk_type(sk))
+#define sk_CMS_SignerInfo_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_CMS_SignerInfo_sk_type(sk))
+#define sk_CMS_SignerInfo_dup(sk) ((STACK_OF(CMS_SignerInfo) *)OPENSSL_sk_dup(ossl_check_const_CMS_SignerInfo_sk_type(sk)))
+#define sk_CMS_SignerInfo_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(CMS_SignerInfo) *)OPENSSL_sk_deep_copy(ossl_check_const_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_copyfunc_type(copyfunc), ossl_check_CMS_SignerInfo_freefunc_type(freefunc)))
+#define sk_CMS_SignerInfo_set_cmp_func(sk, cmp) ((sk_CMS_SignerInfo_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_CMS_SignerInfo_sk_type(sk), ossl_check_CMS_SignerInfo_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(CMS_RecipientEncryptedKey, CMS_RecipientEncryptedKey, CMS_RecipientEncryptedKey)
+#define sk_CMS_RecipientEncryptedKey_num(sk) OPENSSL_sk_num(ossl_check_const_CMS_RecipientEncryptedKey_sk_type(sk))
+#define sk_CMS_RecipientEncryptedKey_value(sk, idx) ((CMS_RecipientEncryptedKey *)OPENSSL_sk_value(ossl_check_const_CMS_RecipientEncryptedKey_sk_type(sk), (idx)))
+#define sk_CMS_RecipientEncryptedKey_new(cmp) ((STACK_OF(CMS_RecipientEncryptedKey) *)OPENSSL_sk_new(ossl_check_CMS_RecipientEncryptedKey_compfunc_type(cmp)))
+#define sk_CMS_RecipientEncryptedKey_new_null() ((STACK_OF(CMS_RecipientEncryptedKey) *)OPENSSL_sk_new_null())
+#define sk_CMS_RecipientEncryptedKey_new_reserve(cmp, n) ((STACK_OF(CMS_RecipientEncryptedKey) *)OPENSSL_sk_new_reserve(ossl_check_CMS_RecipientEncryptedKey_compfunc_type(cmp), (n)))
+#define sk_CMS_RecipientEncryptedKey_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), (n))
+#define sk_CMS_RecipientEncryptedKey_free(sk) OPENSSL_sk_free(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk))
+#define sk_CMS_RecipientEncryptedKey_zero(sk) OPENSSL_sk_zero(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk))
+#define sk_CMS_RecipientEncryptedKey_delete(sk, i) ((CMS_RecipientEncryptedKey *)OPENSSL_sk_delete(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), (i)))
+#define sk_CMS_RecipientEncryptedKey_delete_ptr(sk, ptr) ((CMS_RecipientEncryptedKey *)OPENSSL_sk_delete_ptr(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_type(ptr)))
+#define sk_CMS_RecipientEncryptedKey_push(sk, ptr) OPENSSL_sk_push(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_type(ptr))
+#define sk_CMS_RecipientEncryptedKey_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_type(ptr))
+#define sk_CMS_RecipientEncryptedKey_pop(sk) ((CMS_RecipientEncryptedKey *)OPENSSL_sk_pop(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk)))
+#define sk_CMS_RecipientEncryptedKey_shift(sk) ((CMS_RecipientEncryptedKey *)OPENSSL_sk_shift(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk)))
+#define sk_CMS_RecipientEncryptedKey_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk),ossl_check_CMS_RecipientEncryptedKey_freefunc_type(freefunc))
+#define sk_CMS_RecipientEncryptedKey_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_type(ptr), (idx))
+#define sk_CMS_RecipientEncryptedKey_set(sk, idx, ptr) ((CMS_RecipientEncryptedKey *)OPENSSL_sk_set(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), (idx), ossl_check_CMS_RecipientEncryptedKey_type(ptr)))
+#define sk_CMS_RecipientEncryptedKey_find(sk, ptr) OPENSSL_sk_find(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_type(ptr))
+#define sk_CMS_RecipientEncryptedKey_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_type(ptr))
+#define sk_CMS_RecipientEncryptedKey_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_type(ptr), pnum)
+#define sk_CMS_RecipientEncryptedKey_sort(sk) OPENSSL_sk_sort(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk))
+#define sk_CMS_RecipientEncryptedKey_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_CMS_RecipientEncryptedKey_sk_type(sk))
+#define sk_CMS_RecipientEncryptedKey_dup(sk) ((STACK_OF(CMS_RecipientEncryptedKey) *)OPENSSL_sk_dup(ossl_check_const_CMS_RecipientEncryptedKey_sk_type(sk)))
+#define sk_CMS_RecipientEncryptedKey_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(CMS_RecipientEncryptedKey) *)OPENSSL_sk_deep_copy(ossl_check_const_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_copyfunc_type(copyfunc), ossl_check_CMS_RecipientEncryptedKey_freefunc_type(freefunc)))
+#define sk_CMS_RecipientEncryptedKey_set_cmp_func(sk, cmp) ((sk_CMS_RecipientEncryptedKey_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_CMS_RecipientEncryptedKey_sk_type(sk), ossl_check_CMS_RecipientEncryptedKey_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(CMS_RecipientInfo, CMS_RecipientInfo, CMS_RecipientInfo)
+#define sk_CMS_RecipientInfo_num(sk) OPENSSL_sk_num(ossl_check_const_CMS_RecipientInfo_sk_type(sk))
+#define sk_CMS_RecipientInfo_value(sk, idx) ((CMS_RecipientInfo *)OPENSSL_sk_value(ossl_check_const_CMS_RecipientInfo_sk_type(sk), (idx)))
+#define sk_CMS_RecipientInfo_new(cmp) ((STACK_OF(CMS_RecipientInfo) *)OPENSSL_sk_new(ossl_check_CMS_RecipientInfo_compfunc_type(cmp)))
+#define sk_CMS_RecipientInfo_new_null() ((STACK_OF(CMS_RecipientInfo) *)OPENSSL_sk_new_null())
+#define sk_CMS_RecipientInfo_new_reserve(cmp, n) ((STACK_OF(CMS_RecipientInfo) *)OPENSSL_sk_new_reserve(ossl_check_CMS_RecipientInfo_compfunc_type(cmp), (n)))
+#define sk_CMS_RecipientInfo_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_CMS_RecipientInfo_sk_type(sk), (n))
+#define sk_CMS_RecipientInfo_free(sk) OPENSSL_sk_free(ossl_check_CMS_RecipientInfo_sk_type(sk))
+#define sk_CMS_RecipientInfo_zero(sk) OPENSSL_sk_zero(ossl_check_CMS_RecipientInfo_sk_type(sk))
+#define sk_CMS_RecipientInfo_delete(sk, i) ((CMS_RecipientInfo *)OPENSSL_sk_delete(ossl_check_CMS_RecipientInfo_sk_type(sk), (i)))
+#define sk_CMS_RecipientInfo_delete_ptr(sk, ptr) ((CMS_RecipientInfo *)OPENSSL_sk_delete_ptr(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_type(ptr)))
+#define sk_CMS_RecipientInfo_push(sk, ptr) OPENSSL_sk_push(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_type(ptr))
+#define sk_CMS_RecipientInfo_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_type(ptr))
+#define sk_CMS_RecipientInfo_pop(sk) ((CMS_RecipientInfo *)OPENSSL_sk_pop(ossl_check_CMS_RecipientInfo_sk_type(sk)))
+#define sk_CMS_RecipientInfo_shift(sk) ((CMS_RecipientInfo *)OPENSSL_sk_shift(ossl_check_CMS_RecipientInfo_sk_type(sk)))
+#define sk_CMS_RecipientInfo_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_CMS_RecipientInfo_sk_type(sk),ossl_check_CMS_RecipientInfo_freefunc_type(freefunc))
+#define sk_CMS_RecipientInfo_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_type(ptr), (idx))
+#define sk_CMS_RecipientInfo_set(sk, idx, ptr) ((CMS_RecipientInfo *)OPENSSL_sk_set(ossl_check_CMS_RecipientInfo_sk_type(sk), (idx), ossl_check_CMS_RecipientInfo_type(ptr)))
+#define sk_CMS_RecipientInfo_find(sk, ptr) OPENSSL_sk_find(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_type(ptr))
+#define sk_CMS_RecipientInfo_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_type(ptr))
+#define sk_CMS_RecipientInfo_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_type(ptr), pnum)
+#define sk_CMS_RecipientInfo_sort(sk) OPENSSL_sk_sort(ossl_check_CMS_RecipientInfo_sk_type(sk))
+#define sk_CMS_RecipientInfo_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_CMS_RecipientInfo_sk_type(sk))
+#define sk_CMS_RecipientInfo_dup(sk) ((STACK_OF(CMS_RecipientInfo) *)OPENSSL_sk_dup(ossl_check_const_CMS_RecipientInfo_sk_type(sk)))
+#define sk_CMS_RecipientInfo_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(CMS_RecipientInfo) *)OPENSSL_sk_deep_copy(ossl_check_const_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_copyfunc_type(copyfunc), ossl_check_CMS_RecipientInfo_freefunc_type(freefunc)))
+#define sk_CMS_RecipientInfo_set_cmp_func(sk, cmp) ((sk_CMS_RecipientInfo_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_CMS_RecipientInfo_sk_type(sk), ossl_check_CMS_RecipientInfo_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(CMS_RevocationInfoChoice, CMS_RevocationInfoChoice, CMS_RevocationInfoChoice)
+#define sk_CMS_RevocationInfoChoice_num(sk) OPENSSL_sk_num(ossl_check_const_CMS_RevocationInfoChoice_sk_type(sk))
+#define sk_CMS_RevocationInfoChoice_value(sk, idx) ((CMS_RevocationInfoChoice *)OPENSSL_sk_value(ossl_check_const_CMS_RevocationInfoChoice_sk_type(sk), (idx)))
+#define sk_CMS_RevocationInfoChoice_new(cmp) ((STACK_OF(CMS_RevocationInfoChoice) *)OPENSSL_sk_new(ossl_check_CMS_RevocationInfoChoice_compfunc_type(cmp)))
+#define sk_CMS_RevocationInfoChoice_new_null() ((STACK_OF(CMS_RevocationInfoChoice) *)OPENSSL_sk_new_null())
+#define sk_CMS_RevocationInfoChoice_new_reserve(cmp, n) ((STACK_OF(CMS_RevocationInfoChoice) *)OPENSSL_sk_new_reserve(ossl_check_CMS_RevocationInfoChoice_compfunc_type(cmp), (n)))
+#define sk_CMS_RevocationInfoChoice_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), (n))
+#define sk_CMS_RevocationInfoChoice_free(sk) OPENSSL_sk_free(ossl_check_CMS_RevocationInfoChoice_sk_type(sk))
+#define sk_CMS_RevocationInfoChoice_zero(sk) OPENSSL_sk_zero(ossl_check_CMS_RevocationInfoChoice_sk_type(sk))
+#define sk_CMS_RevocationInfoChoice_delete(sk, i) ((CMS_RevocationInfoChoice *)OPENSSL_sk_delete(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), (i)))
+#define sk_CMS_RevocationInfoChoice_delete_ptr(sk, ptr) ((CMS_RevocationInfoChoice *)OPENSSL_sk_delete_ptr(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_type(ptr)))
+#define sk_CMS_RevocationInfoChoice_push(sk, ptr) OPENSSL_sk_push(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_type(ptr))
+#define sk_CMS_RevocationInfoChoice_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_type(ptr))
+#define sk_CMS_RevocationInfoChoice_pop(sk) ((CMS_RevocationInfoChoice *)OPENSSL_sk_pop(ossl_check_CMS_RevocationInfoChoice_sk_type(sk)))
+#define sk_CMS_RevocationInfoChoice_shift(sk) ((CMS_RevocationInfoChoice *)OPENSSL_sk_shift(ossl_check_CMS_RevocationInfoChoice_sk_type(sk)))
+#define sk_CMS_RevocationInfoChoice_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_CMS_RevocationInfoChoice_sk_type(sk),ossl_check_CMS_RevocationInfoChoice_freefunc_type(freefunc))
+#define sk_CMS_RevocationInfoChoice_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_type(ptr), (idx))
+#define sk_CMS_RevocationInfoChoice_set(sk, idx, ptr) ((CMS_RevocationInfoChoice *)OPENSSL_sk_set(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), (idx), ossl_check_CMS_RevocationInfoChoice_type(ptr)))
+#define sk_CMS_RevocationInfoChoice_find(sk, ptr) OPENSSL_sk_find(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_type(ptr))
+#define sk_CMS_RevocationInfoChoice_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_type(ptr))
+#define sk_CMS_RevocationInfoChoice_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_type(ptr), pnum)
+#define sk_CMS_RevocationInfoChoice_sort(sk) OPENSSL_sk_sort(ossl_check_CMS_RevocationInfoChoice_sk_type(sk))
+#define sk_CMS_RevocationInfoChoice_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_CMS_RevocationInfoChoice_sk_type(sk))
+#define sk_CMS_RevocationInfoChoice_dup(sk) ((STACK_OF(CMS_RevocationInfoChoice) *)OPENSSL_sk_dup(ossl_check_const_CMS_RevocationInfoChoice_sk_type(sk)))
+#define sk_CMS_RevocationInfoChoice_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(CMS_RevocationInfoChoice) *)OPENSSL_sk_deep_copy(ossl_check_const_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_copyfunc_type(copyfunc), ossl_check_CMS_RevocationInfoChoice_freefunc_type(freefunc)))
+#define sk_CMS_RevocationInfoChoice_set_cmp_func(sk, cmp) ((sk_CMS_RevocationInfoChoice_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_CMS_RevocationInfoChoice_sk_type(sk), ossl_check_CMS_RevocationInfoChoice_compfunc_type(cmp)))
+
+
+DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo)
+DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest)
+DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo)
+
+CMS_ContentInfo *CMS_ContentInfo_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+# define CMS_SIGNERINFO_ISSUER_SERIAL 0
+# define CMS_SIGNERINFO_KEYIDENTIFIER 1
+
+# define CMS_RECIPINFO_NONE -1
+# define CMS_RECIPINFO_TRANS 0
+# define CMS_RECIPINFO_AGREE 1
+# define CMS_RECIPINFO_KEK 2
+# define CMS_RECIPINFO_PASS 3
+# define CMS_RECIPINFO_OTHER 4
+
+/* S/MIME related flags */
+
+# define CMS_TEXT 0x1
+# define CMS_NOCERTS 0x2
+# define CMS_NO_CONTENT_VERIFY 0x4
+# define CMS_NO_ATTR_VERIFY 0x8
+# define CMS_NOSIGS \
+ (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY)
+# define CMS_NOINTERN 0x10
+# define CMS_NO_SIGNER_CERT_VERIFY 0x20
+# define CMS_NOVERIFY 0x20
+# define CMS_DETACHED 0x40
+# define CMS_BINARY 0x80
+# define CMS_NOATTR 0x100
+# define CMS_NOSMIMECAP 0x200
+# define CMS_NOOLDMIMETYPE 0x400
+# define CMS_CRLFEOL 0x800
+# define CMS_STREAM 0x1000
+# define CMS_NOCRL 0x2000
+# define CMS_PARTIAL 0x4000
+# define CMS_REUSE_DIGEST 0x8000
+# define CMS_USE_KEYID 0x10000
+# define CMS_DEBUG_DECRYPT 0x20000
+# define CMS_KEY_PARAM 0x40000
+# define CMS_ASCIICRLF 0x80000
+# define CMS_CADES 0x100000
+# define CMS_USE_ORIGINATOR_KEYID 0x200000
+
+const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms);
+
+BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont);
+int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio);
+
+ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms);
+int CMS_is_detached(CMS_ContentInfo *cms);
+int CMS_set_detached(CMS_ContentInfo *cms, int detached);
+
+# ifdef OPENSSL_PEM_H
+DECLARE_PEM_rw(CMS, CMS_ContentInfo)
+# endif
+int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms);
+CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms);
+int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms);
+
+BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms);
+int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags);
+int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in,
+ int flags);
+CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont);
+CMS_ContentInfo *SMIME_read_CMS_ex(BIO *bio, int flags, BIO **bcont, CMS_ContentInfo **ci);
+int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags);
+
+int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont,
+ unsigned int flags);
+
+CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey,
+ STACK_OF(X509) *certs, BIO *data,
+ unsigned int flags);
+CMS_ContentInfo *CMS_sign_ex(X509 *signcert, EVP_PKEY *pkey,
+ STACK_OF(X509) *certs, BIO *data,
+ unsigned int flags, OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si,
+ X509 *signcert, EVP_PKEY *pkey,
+ STACK_OF(X509) *certs, unsigned int flags);
+
+int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags);
+CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags);
+CMS_ContentInfo *CMS_data_create_ex(BIO *in, unsigned int flags,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
+ unsigned int flags);
+CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md,
+ unsigned int flags);
+CMS_ContentInfo *CMS_digest_create_ex(BIO *in, const EVP_MD *md,
+ unsigned int flags, OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms,
+ const unsigned char *key, size_t keylen,
+ BIO *dcont, BIO *out, unsigned int flags);
+
+CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher,
+ const unsigned char *key,
+ size_t keylen, unsigned int flags);
+CMS_ContentInfo *CMS_EncryptedData_encrypt_ex(BIO *in, const EVP_CIPHER *cipher,
+ const unsigned char *key,
+ size_t keylen, unsigned int flags,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph,
+ const unsigned char *key, size_t keylen);
+
+int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs,
+ X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags);
+
+int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms,
+ STACK_OF(X509) *certs,
+ X509_STORE *store, unsigned int flags);
+
+STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms);
+
+CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in,
+ const EVP_CIPHER *cipher, unsigned int flags);
+CMS_ContentInfo *CMS_encrypt_ex(STACK_OF(X509) *certs, BIO *in,
+ const EVP_CIPHER *cipher, unsigned int flags,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert,
+ BIO *dcont, BIO *out, unsigned int flags);
+
+int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert);
+int CMS_decrypt_set1_pkey_and_peer(CMS_ContentInfo *cms, EVP_PKEY *pk,
+ X509 *cert, X509 *peer);
+int CMS_decrypt_set1_key(CMS_ContentInfo *cms,
+ unsigned char *key, size_t keylen,
+ const unsigned char *id, size_t idlen);
+int CMS_decrypt_set1_password(CMS_ContentInfo *cms,
+ unsigned char *pass, ossl_ssize_t passlen);
+
+STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms);
+int CMS_RecipientInfo_type(CMS_RecipientInfo *ri);
+EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri);
+CMS_ContentInfo *CMS_AuthEnvelopedData_create(const EVP_CIPHER *cipher);
+CMS_ContentInfo *
+CMS_AuthEnvelopedData_create_ex(const EVP_CIPHER *cipher, OSSL_LIB_CTX *ctx,
+ const char *propq);
+CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher);
+CMS_ContentInfo *CMS_EnvelopedData_create_ex(const EVP_CIPHER *cipher,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms,
+ X509 *recip, unsigned int flags);
+CMS_RecipientInfo *CMS_add1_recipient(CMS_ContentInfo *cms, X509 *recip,
+ EVP_PKEY *originatorPrivKey, X509 * originator, unsigned int flags);
+int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey);
+int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert);
+int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
+ EVP_PKEY **pk, X509 **recip,
+ X509_ALGOR **palg);
+int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
+ ASN1_OCTET_STRING **keyid,
+ X509_NAME **issuer,
+ ASN1_INTEGER **sno);
+
+CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
+ unsigned char *key, size_t keylen,
+ unsigned char *id, size_t idlen,
+ ASN1_GENERALIZEDTIME *date,
+ ASN1_OBJECT *otherTypeId,
+ ASN1_TYPE *otherType);
+
+int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
+ X509_ALGOR **palg,
+ ASN1_OCTET_STRING **pid,
+ ASN1_GENERALIZEDTIME **pdate,
+ ASN1_OBJECT **potherid,
+ ASN1_TYPE **pothertype);
+
+int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
+ unsigned char *key, size_t keylen);
+
+int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
+ const unsigned char *id, size_t idlen);
+
+int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri,
+ unsigned char *pass,
+ ossl_ssize_t passlen);
+
+CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms,
+ int iter, int wrap_nid,
+ int pbe_nid,
+ unsigned char *pass,
+ ossl_ssize_t passlen,
+ const EVP_CIPHER *kekciph);
+
+int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri);
+int CMS_RecipientInfo_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri);
+
+int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
+ unsigned int flags);
+CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags);
+
+int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid);
+const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms);
+
+CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms);
+int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert);
+int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert);
+STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms);
+
+CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms);
+int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl);
+int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl);
+STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms);
+
+int CMS_SignedData_init(CMS_ContentInfo *cms);
+CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
+ X509 *signer, EVP_PKEY *pk, const EVP_MD *md,
+ unsigned int flags);
+EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si);
+EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si);
+STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms);
+
+void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer);
+int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
+ ASN1_OCTET_STRING **keyid,
+ X509_NAME **issuer, ASN1_INTEGER **sno);
+int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert);
+int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs,
+ unsigned int flags);
+void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
+ X509 **signer, X509_ALGOR **pdig,
+ X509_ALGOR **psig);
+ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si);
+int CMS_SignerInfo_sign(CMS_SignerInfo *si);
+int CMS_SignerInfo_verify(CMS_SignerInfo *si);
+int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain);
+
+int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs);
+int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
+ int algnid, int keysize);
+int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap);
+
+int CMS_signed_get_attr_count(const CMS_SignerInfo *si);
+int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid,
+ int lastpos);
+int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc);
+X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc);
+int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr);
+int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si,
+ const ASN1_OBJECT *obj, int type,
+ const void *bytes, int len);
+int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si,
+ int nid, int type,
+ const void *bytes, int len);
+int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si,
+ const char *attrname, int type,
+ const void *bytes, int len);
+void *CMS_signed_get0_data_by_OBJ(const CMS_SignerInfo *si,
+ const ASN1_OBJECT *oid,
+ int lastpos, int type);
+
+int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si);
+int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid,
+ int lastpos);
+int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si,
+ const ASN1_OBJECT *obj, int lastpos);
+X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc);
+X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc);
+int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr);
+int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si,
+ const ASN1_OBJECT *obj, int type,
+ const void *bytes, int len);
+int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si,
+ int nid, int type,
+ const void *bytes, int len);
+int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si,
+ const char *attrname, int type,
+ const void *bytes, int len);
+void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid,
+ int lastpos, int type);
+
+int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr);
+CMS_ReceiptRequest *CMS_ReceiptRequest_create0(
+ unsigned char *id, int idlen, int allorfirst,
+ STACK_OF(GENERAL_NAMES) *receiptList,
+ STACK_OF(GENERAL_NAMES) *receiptsTo);
+CMS_ReceiptRequest *CMS_ReceiptRequest_create0_ex(
+ unsigned char *id, int idlen, int allorfirst,
+ STACK_OF(GENERAL_NAMES) *receiptList,
+ STACK_OF(GENERAL_NAMES) *receiptsTo,
+ OSSL_LIB_CTX *ctx);
+
+int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr);
+void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr,
+ ASN1_STRING **pcid,
+ int *pallorfirst,
+ STACK_OF(GENERAL_NAMES) **plist,
+ STACK_OF(GENERAL_NAMES) **prto);
+int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
+ X509_ALGOR **palg,
+ ASN1_OCTET_STRING **pukm);
+STACK_OF(CMS_RecipientEncryptedKey)
+*CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri);
+
+int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
+ X509_ALGOR **pubalg,
+ ASN1_BIT_STRING **pubkey,
+ ASN1_OCTET_STRING **keyid,
+ X509_NAME **issuer,
+ ASN1_INTEGER **sno);
+
+int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert);
+
+int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
+ ASN1_OCTET_STRING **keyid,
+ ASN1_GENERALIZEDTIME **tm,
+ CMS_OtherKeyAttribute **other,
+ X509_NAME **issuer, ASN1_INTEGER **sno);
+int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
+ X509 *cert);
+int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk);
+int CMS_RecipientInfo_kari_set0_pkey_and_peer(CMS_RecipientInfo *ri, EVP_PKEY *pk, X509 *peer);
+EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri);
+int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
+ CMS_RecipientInfo *ri,
+ CMS_RecipientEncryptedKey *rek);
+
+int CMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg,
+ ASN1_OCTET_STRING *ukm, int keylen);
+
+/* Backward compatibility for spelling errors. */
+# define CMS_R_UNKNOWN_DIGEST_ALGORITM CMS_R_UNKNOWN_DIGEST_ALGORITHM
+# define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \
+ CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/cms.h.in b/include/openssl/cms.h.in
new file mode 100644
index 00000000..da20ddf2
--- /dev/null
+++ b/include/openssl/cms.h.in
@@ -0,0 +1,395 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2008-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_CMS_H
+# define OPENSSL_CMS_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CMS_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CMS
+# include <openssl/x509.h>
+# include <openssl/x509v3.h>
+# include <openssl/cmserr.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+typedef struct CMS_ContentInfo_st CMS_ContentInfo;
+typedef struct CMS_SignerInfo_st CMS_SignerInfo;
+typedef struct CMS_CertificateChoices CMS_CertificateChoices;
+typedef struct CMS_RevocationInfoChoice_st CMS_RevocationInfoChoice;
+typedef struct CMS_RecipientInfo_st CMS_RecipientInfo;
+typedef struct CMS_ReceiptRequest_st CMS_ReceiptRequest;
+typedef struct CMS_Receipt_st CMS_Receipt;
+typedef struct CMS_RecipientEncryptedKey_st CMS_RecipientEncryptedKey;
+typedef struct CMS_OtherKeyAttribute_st CMS_OtherKeyAttribute;
+
+{-
+ generate_stack_macros("CMS_SignerInfo")
+ .generate_stack_macros("CMS_RecipientEncryptedKey")
+ .generate_stack_macros("CMS_RecipientInfo")
+ .generate_stack_macros("CMS_RevocationInfoChoice");
+-}
+
+DECLARE_ASN1_FUNCTIONS(CMS_ContentInfo)
+DECLARE_ASN1_FUNCTIONS(CMS_ReceiptRequest)
+DECLARE_ASN1_PRINT_FUNCTION(CMS_ContentInfo)
+
+CMS_ContentInfo *CMS_ContentInfo_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+# define CMS_SIGNERINFO_ISSUER_SERIAL 0
+# define CMS_SIGNERINFO_KEYIDENTIFIER 1
+
+# define CMS_RECIPINFO_NONE -1
+# define CMS_RECIPINFO_TRANS 0
+# define CMS_RECIPINFO_AGREE 1
+# define CMS_RECIPINFO_KEK 2
+# define CMS_RECIPINFO_PASS 3
+# define CMS_RECIPINFO_OTHER 4
+
+/* S/MIME related flags */
+
+# define CMS_TEXT 0x1
+# define CMS_NOCERTS 0x2
+# define CMS_NO_CONTENT_VERIFY 0x4
+# define CMS_NO_ATTR_VERIFY 0x8
+# define CMS_NOSIGS \
+ (CMS_NO_CONTENT_VERIFY|CMS_NO_ATTR_VERIFY)
+# define CMS_NOINTERN 0x10
+# define CMS_NO_SIGNER_CERT_VERIFY 0x20
+# define CMS_NOVERIFY 0x20
+# define CMS_DETACHED 0x40
+# define CMS_BINARY 0x80
+# define CMS_NOATTR 0x100
+# define CMS_NOSMIMECAP 0x200
+# define CMS_NOOLDMIMETYPE 0x400
+# define CMS_CRLFEOL 0x800
+# define CMS_STREAM 0x1000
+# define CMS_NOCRL 0x2000
+# define CMS_PARTIAL 0x4000
+# define CMS_REUSE_DIGEST 0x8000
+# define CMS_USE_KEYID 0x10000
+# define CMS_DEBUG_DECRYPT 0x20000
+# define CMS_KEY_PARAM 0x40000
+# define CMS_ASCIICRLF 0x80000
+# define CMS_CADES 0x100000
+# define CMS_USE_ORIGINATOR_KEYID 0x200000
+
+const ASN1_OBJECT *CMS_get0_type(const CMS_ContentInfo *cms);
+
+BIO *CMS_dataInit(CMS_ContentInfo *cms, BIO *icont);
+int CMS_dataFinal(CMS_ContentInfo *cms, BIO *bio);
+
+ASN1_OCTET_STRING **CMS_get0_content(CMS_ContentInfo *cms);
+int CMS_is_detached(CMS_ContentInfo *cms);
+int CMS_set_detached(CMS_ContentInfo *cms, int detached);
+
+# ifdef OPENSSL_PEM_H
+DECLARE_PEM_rw(CMS, CMS_ContentInfo)
+# endif
+int CMS_stream(unsigned char ***boundary, CMS_ContentInfo *cms);
+CMS_ContentInfo *d2i_CMS_bio(BIO *bp, CMS_ContentInfo **cms);
+int i2d_CMS_bio(BIO *bp, CMS_ContentInfo *cms);
+
+BIO *BIO_new_CMS(BIO *out, CMS_ContentInfo *cms);
+int i2d_CMS_bio_stream(BIO *out, CMS_ContentInfo *cms, BIO *in, int flags);
+int PEM_write_bio_CMS_stream(BIO *out, CMS_ContentInfo *cms, BIO *in,
+ int flags);
+CMS_ContentInfo *SMIME_read_CMS(BIO *bio, BIO **bcont);
+CMS_ContentInfo *SMIME_read_CMS_ex(BIO *bio, int flags, BIO **bcont, CMS_ContentInfo **ci);
+int SMIME_write_CMS(BIO *bio, CMS_ContentInfo *cms, BIO *data, int flags);
+
+int CMS_final(CMS_ContentInfo *cms, BIO *data, BIO *dcont,
+ unsigned int flags);
+
+CMS_ContentInfo *CMS_sign(X509 *signcert, EVP_PKEY *pkey,
+ STACK_OF(X509) *certs, BIO *data,
+ unsigned int flags);
+CMS_ContentInfo *CMS_sign_ex(X509 *signcert, EVP_PKEY *pkey,
+ STACK_OF(X509) *certs, BIO *data,
+ unsigned int flags, OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+CMS_ContentInfo *CMS_sign_receipt(CMS_SignerInfo *si,
+ X509 *signcert, EVP_PKEY *pkey,
+ STACK_OF(X509) *certs, unsigned int flags);
+
+int CMS_data(CMS_ContentInfo *cms, BIO *out, unsigned int flags);
+CMS_ContentInfo *CMS_data_create(BIO *in, unsigned int flags);
+CMS_ContentInfo *CMS_data_create_ex(BIO *in, unsigned int flags,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int CMS_digest_verify(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
+ unsigned int flags);
+CMS_ContentInfo *CMS_digest_create(BIO *in, const EVP_MD *md,
+ unsigned int flags);
+CMS_ContentInfo *CMS_digest_create_ex(BIO *in, const EVP_MD *md,
+ unsigned int flags, OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+int CMS_EncryptedData_decrypt(CMS_ContentInfo *cms,
+ const unsigned char *key, size_t keylen,
+ BIO *dcont, BIO *out, unsigned int flags);
+
+CMS_ContentInfo *CMS_EncryptedData_encrypt(BIO *in, const EVP_CIPHER *cipher,
+ const unsigned char *key,
+ size_t keylen, unsigned int flags);
+CMS_ContentInfo *CMS_EncryptedData_encrypt_ex(BIO *in, const EVP_CIPHER *cipher,
+ const unsigned char *key,
+ size_t keylen, unsigned int flags,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+int CMS_EncryptedData_set1_key(CMS_ContentInfo *cms, const EVP_CIPHER *ciph,
+ const unsigned char *key, size_t keylen);
+
+int CMS_verify(CMS_ContentInfo *cms, STACK_OF(X509) *certs,
+ X509_STORE *store, BIO *dcont, BIO *out, unsigned int flags);
+
+int CMS_verify_receipt(CMS_ContentInfo *rcms, CMS_ContentInfo *ocms,
+ STACK_OF(X509) *certs,
+ X509_STORE *store, unsigned int flags);
+
+STACK_OF(X509) *CMS_get0_signers(CMS_ContentInfo *cms);
+
+CMS_ContentInfo *CMS_encrypt(STACK_OF(X509) *certs, BIO *in,
+ const EVP_CIPHER *cipher, unsigned int flags);
+CMS_ContentInfo *CMS_encrypt_ex(STACK_OF(X509) *certs, BIO *in,
+ const EVP_CIPHER *cipher, unsigned int flags,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int CMS_decrypt(CMS_ContentInfo *cms, EVP_PKEY *pkey, X509 *cert,
+ BIO *dcont, BIO *out, unsigned int flags);
+
+int CMS_decrypt_set1_pkey(CMS_ContentInfo *cms, EVP_PKEY *pk, X509 *cert);
+int CMS_decrypt_set1_pkey_and_peer(CMS_ContentInfo *cms, EVP_PKEY *pk,
+ X509 *cert, X509 *peer);
+int CMS_decrypt_set1_key(CMS_ContentInfo *cms,
+ unsigned char *key, size_t keylen,
+ const unsigned char *id, size_t idlen);
+int CMS_decrypt_set1_password(CMS_ContentInfo *cms,
+ unsigned char *pass, ossl_ssize_t passlen);
+
+STACK_OF(CMS_RecipientInfo) *CMS_get0_RecipientInfos(CMS_ContentInfo *cms);
+int CMS_RecipientInfo_type(CMS_RecipientInfo *ri);
+EVP_PKEY_CTX *CMS_RecipientInfo_get0_pkey_ctx(CMS_RecipientInfo *ri);
+CMS_ContentInfo *CMS_AuthEnvelopedData_create(const EVP_CIPHER *cipher);
+CMS_ContentInfo *
+CMS_AuthEnvelopedData_create_ex(const EVP_CIPHER *cipher, OSSL_LIB_CTX *ctx,
+ const char *propq);
+CMS_ContentInfo *CMS_EnvelopedData_create(const EVP_CIPHER *cipher);
+CMS_ContentInfo *CMS_EnvelopedData_create_ex(const EVP_CIPHER *cipher,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+CMS_RecipientInfo *CMS_add1_recipient_cert(CMS_ContentInfo *cms,
+ X509 *recip, unsigned int flags);
+CMS_RecipientInfo *CMS_add1_recipient(CMS_ContentInfo *cms, X509 *recip,
+ EVP_PKEY *originatorPrivKey, X509 * originator, unsigned int flags);
+int CMS_RecipientInfo_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pkey);
+int CMS_RecipientInfo_ktri_cert_cmp(CMS_RecipientInfo *ri, X509 *cert);
+int CMS_RecipientInfo_ktri_get0_algs(CMS_RecipientInfo *ri,
+ EVP_PKEY **pk, X509 **recip,
+ X509_ALGOR **palg);
+int CMS_RecipientInfo_ktri_get0_signer_id(CMS_RecipientInfo *ri,
+ ASN1_OCTET_STRING **keyid,
+ X509_NAME **issuer,
+ ASN1_INTEGER **sno);
+
+CMS_RecipientInfo *CMS_add0_recipient_key(CMS_ContentInfo *cms, int nid,
+ unsigned char *key, size_t keylen,
+ unsigned char *id, size_t idlen,
+ ASN1_GENERALIZEDTIME *date,
+ ASN1_OBJECT *otherTypeId,
+ ASN1_TYPE *otherType);
+
+int CMS_RecipientInfo_kekri_get0_id(CMS_RecipientInfo *ri,
+ X509_ALGOR **palg,
+ ASN1_OCTET_STRING **pid,
+ ASN1_GENERALIZEDTIME **pdate,
+ ASN1_OBJECT **potherid,
+ ASN1_TYPE **pothertype);
+
+int CMS_RecipientInfo_set0_key(CMS_RecipientInfo *ri,
+ unsigned char *key, size_t keylen);
+
+int CMS_RecipientInfo_kekri_id_cmp(CMS_RecipientInfo *ri,
+ const unsigned char *id, size_t idlen);
+
+int CMS_RecipientInfo_set0_password(CMS_RecipientInfo *ri,
+ unsigned char *pass,
+ ossl_ssize_t passlen);
+
+CMS_RecipientInfo *CMS_add0_recipient_password(CMS_ContentInfo *cms,
+ int iter, int wrap_nid,
+ int pbe_nid,
+ unsigned char *pass,
+ ossl_ssize_t passlen,
+ const EVP_CIPHER *kekciph);
+
+int CMS_RecipientInfo_decrypt(CMS_ContentInfo *cms, CMS_RecipientInfo *ri);
+int CMS_RecipientInfo_encrypt(const CMS_ContentInfo *cms, CMS_RecipientInfo *ri);
+
+int CMS_uncompress(CMS_ContentInfo *cms, BIO *dcont, BIO *out,
+ unsigned int flags);
+CMS_ContentInfo *CMS_compress(BIO *in, int comp_nid, unsigned int flags);
+
+int CMS_set1_eContentType(CMS_ContentInfo *cms, const ASN1_OBJECT *oid);
+const ASN1_OBJECT *CMS_get0_eContentType(CMS_ContentInfo *cms);
+
+CMS_CertificateChoices *CMS_add0_CertificateChoices(CMS_ContentInfo *cms);
+int CMS_add0_cert(CMS_ContentInfo *cms, X509 *cert);
+int CMS_add1_cert(CMS_ContentInfo *cms, X509 *cert);
+STACK_OF(X509) *CMS_get1_certs(CMS_ContentInfo *cms);
+
+CMS_RevocationInfoChoice *CMS_add0_RevocationInfoChoice(CMS_ContentInfo *cms);
+int CMS_add0_crl(CMS_ContentInfo *cms, X509_CRL *crl);
+int CMS_add1_crl(CMS_ContentInfo *cms, X509_CRL *crl);
+STACK_OF(X509_CRL) *CMS_get1_crls(CMS_ContentInfo *cms);
+
+int CMS_SignedData_init(CMS_ContentInfo *cms);
+CMS_SignerInfo *CMS_add1_signer(CMS_ContentInfo *cms,
+ X509 *signer, EVP_PKEY *pk, const EVP_MD *md,
+ unsigned int flags);
+EVP_PKEY_CTX *CMS_SignerInfo_get0_pkey_ctx(CMS_SignerInfo *si);
+EVP_MD_CTX *CMS_SignerInfo_get0_md_ctx(CMS_SignerInfo *si);
+STACK_OF(CMS_SignerInfo) *CMS_get0_SignerInfos(CMS_ContentInfo *cms);
+
+void CMS_SignerInfo_set1_signer_cert(CMS_SignerInfo *si, X509 *signer);
+int CMS_SignerInfo_get0_signer_id(CMS_SignerInfo *si,
+ ASN1_OCTET_STRING **keyid,
+ X509_NAME **issuer, ASN1_INTEGER **sno);
+int CMS_SignerInfo_cert_cmp(CMS_SignerInfo *si, X509 *cert);
+int CMS_set1_signers_certs(CMS_ContentInfo *cms, STACK_OF(X509) *certs,
+ unsigned int flags);
+void CMS_SignerInfo_get0_algs(CMS_SignerInfo *si, EVP_PKEY **pk,
+ X509 **signer, X509_ALGOR **pdig,
+ X509_ALGOR **psig);
+ASN1_OCTET_STRING *CMS_SignerInfo_get0_signature(CMS_SignerInfo *si);
+int CMS_SignerInfo_sign(CMS_SignerInfo *si);
+int CMS_SignerInfo_verify(CMS_SignerInfo *si);
+int CMS_SignerInfo_verify_content(CMS_SignerInfo *si, BIO *chain);
+
+int CMS_add_smimecap(CMS_SignerInfo *si, STACK_OF(X509_ALGOR) *algs);
+int CMS_add_simple_smimecap(STACK_OF(X509_ALGOR) **algs,
+ int algnid, int keysize);
+int CMS_add_standard_smimecap(STACK_OF(X509_ALGOR) **smcap);
+
+int CMS_signed_get_attr_count(const CMS_SignerInfo *si);
+int CMS_signed_get_attr_by_NID(const CMS_SignerInfo *si, int nid,
+ int lastpos);
+int CMS_signed_get_attr_by_OBJ(const CMS_SignerInfo *si, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_ATTRIBUTE *CMS_signed_get_attr(const CMS_SignerInfo *si, int loc);
+X509_ATTRIBUTE *CMS_signed_delete_attr(CMS_SignerInfo *si, int loc);
+int CMS_signed_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr);
+int CMS_signed_add1_attr_by_OBJ(CMS_SignerInfo *si,
+ const ASN1_OBJECT *obj, int type,
+ const void *bytes, int len);
+int CMS_signed_add1_attr_by_NID(CMS_SignerInfo *si,
+ int nid, int type,
+ const void *bytes, int len);
+int CMS_signed_add1_attr_by_txt(CMS_SignerInfo *si,
+ const char *attrname, int type,
+ const void *bytes, int len);
+void *CMS_signed_get0_data_by_OBJ(const CMS_SignerInfo *si,
+ const ASN1_OBJECT *oid,
+ int lastpos, int type);
+
+int CMS_unsigned_get_attr_count(const CMS_SignerInfo *si);
+int CMS_unsigned_get_attr_by_NID(const CMS_SignerInfo *si, int nid,
+ int lastpos);
+int CMS_unsigned_get_attr_by_OBJ(const CMS_SignerInfo *si,
+ const ASN1_OBJECT *obj, int lastpos);
+X509_ATTRIBUTE *CMS_unsigned_get_attr(const CMS_SignerInfo *si, int loc);
+X509_ATTRIBUTE *CMS_unsigned_delete_attr(CMS_SignerInfo *si, int loc);
+int CMS_unsigned_add1_attr(CMS_SignerInfo *si, X509_ATTRIBUTE *attr);
+int CMS_unsigned_add1_attr_by_OBJ(CMS_SignerInfo *si,
+ const ASN1_OBJECT *obj, int type,
+ const void *bytes, int len);
+int CMS_unsigned_add1_attr_by_NID(CMS_SignerInfo *si,
+ int nid, int type,
+ const void *bytes, int len);
+int CMS_unsigned_add1_attr_by_txt(CMS_SignerInfo *si,
+ const char *attrname, int type,
+ const void *bytes, int len);
+void *CMS_unsigned_get0_data_by_OBJ(CMS_SignerInfo *si, ASN1_OBJECT *oid,
+ int lastpos, int type);
+
+int CMS_get1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest **prr);
+CMS_ReceiptRequest *CMS_ReceiptRequest_create0(
+ unsigned char *id, int idlen, int allorfirst,
+ STACK_OF(GENERAL_NAMES) *receiptList,
+ STACK_OF(GENERAL_NAMES) *receiptsTo);
+CMS_ReceiptRequest *CMS_ReceiptRequest_create0_ex(
+ unsigned char *id, int idlen, int allorfirst,
+ STACK_OF(GENERAL_NAMES) *receiptList,
+ STACK_OF(GENERAL_NAMES) *receiptsTo,
+ OSSL_LIB_CTX *ctx);
+
+int CMS_add1_ReceiptRequest(CMS_SignerInfo *si, CMS_ReceiptRequest *rr);
+void CMS_ReceiptRequest_get0_values(CMS_ReceiptRequest *rr,
+ ASN1_STRING **pcid,
+ int *pallorfirst,
+ STACK_OF(GENERAL_NAMES) **plist,
+ STACK_OF(GENERAL_NAMES) **prto);
+int CMS_RecipientInfo_kari_get0_alg(CMS_RecipientInfo *ri,
+ X509_ALGOR **palg,
+ ASN1_OCTET_STRING **pukm);
+STACK_OF(CMS_RecipientEncryptedKey)
+*CMS_RecipientInfo_kari_get0_reks(CMS_RecipientInfo *ri);
+
+int CMS_RecipientInfo_kari_get0_orig_id(CMS_RecipientInfo *ri,
+ X509_ALGOR **pubalg,
+ ASN1_BIT_STRING **pubkey,
+ ASN1_OCTET_STRING **keyid,
+ X509_NAME **issuer,
+ ASN1_INTEGER **sno);
+
+int CMS_RecipientInfo_kari_orig_id_cmp(CMS_RecipientInfo *ri, X509 *cert);
+
+int CMS_RecipientEncryptedKey_get0_id(CMS_RecipientEncryptedKey *rek,
+ ASN1_OCTET_STRING **keyid,
+ ASN1_GENERALIZEDTIME **tm,
+ CMS_OtherKeyAttribute **other,
+ X509_NAME **issuer, ASN1_INTEGER **sno);
+int CMS_RecipientEncryptedKey_cert_cmp(CMS_RecipientEncryptedKey *rek,
+ X509 *cert);
+int CMS_RecipientInfo_kari_set0_pkey(CMS_RecipientInfo *ri, EVP_PKEY *pk);
+int CMS_RecipientInfo_kari_set0_pkey_and_peer(CMS_RecipientInfo *ri, EVP_PKEY *pk, X509 *peer);
+EVP_CIPHER_CTX *CMS_RecipientInfo_kari_get0_ctx(CMS_RecipientInfo *ri);
+int CMS_RecipientInfo_kari_decrypt(CMS_ContentInfo *cms,
+ CMS_RecipientInfo *ri,
+ CMS_RecipientEncryptedKey *rek);
+
+int CMS_SharedInfo_encode(unsigned char **pder, X509_ALGOR *kekalg,
+ ASN1_OCTET_STRING *ukm, int keylen);
+
+/* Backward compatibility for spelling errors. */
+# define CMS_R_UNKNOWN_DIGEST_ALGORITM CMS_R_UNKNOWN_DIGEST_ALGORITHM
+# define CMS_R_UNSUPPORTED_RECPIENTINFO_TYPE \
+ CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/cmserr.h b/include/openssl/cmserr.h
new file mode 100644
index 00000000..1c4f4c79
--- /dev/null
+++ b/include/openssl/cmserr.h
@@ -0,0 +1,122 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CMSERR_H
+# define OPENSSL_CMSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_CMS
+
+
+/*
+ * CMS reason codes.
+ */
+# define CMS_R_ADD_SIGNER_ERROR 99
+# define CMS_R_ATTRIBUTE_ERROR 161
+# define CMS_R_CERTIFICATE_ALREADY_PRESENT 175
+# define CMS_R_CERTIFICATE_HAS_NO_KEYID 160
+# define CMS_R_CERTIFICATE_VERIFY_ERROR 100
+# define CMS_R_CIPHER_AEAD_SET_TAG_ERROR 184
+# define CMS_R_CIPHER_GET_TAG 185
+# define CMS_R_CIPHER_INITIALISATION_ERROR 101
+# define CMS_R_CIPHER_PARAMETER_INITIALISATION_ERROR 102
+# define CMS_R_CMS_DATAFINAL_ERROR 103
+# define CMS_R_CMS_LIB 104
+# define CMS_R_CONTENTIDENTIFIER_MISMATCH 170
+# define CMS_R_CONTENT_NOT_FOUND 105
+# define CMS_R_CONTENT_TYPE_MISMATCH 171
+# define CMS_R_CONTENT_TYPE_NOT_COMPRESSED_DATA 106
+# define CMS_R_CONTENT_TYPE_NOT_ENVELOPED_DATA 107
+# define CMS_R_CONTENT_TYPE_NOT_SIGNED_DATA 108
+# define CMS_R_CONTENT_VERIFY_ERROR 109
+# define CMS_R_CTRL_ERROR 110
+# define CMS_R_CTRL_FAILURE 111
+# define CMS_R_DECODE_ERROR 187
+# define CMS_R_DECRYPT_ERROR 112
+# define CMS_R_ERROR_GETTING_PUBLIC_KEY 113
+# define CMS_R_ERROR_READING_MESSAGEDIGEST_ATTRIBUTE 114
+# define CMS_R_ERROR_SETTING_KEY 115
+# define CMS_R_ERROR_SETTING_RECIPIENTINFO 116
+# define CMS_R_ESS_SIGNING_CERTID_MISMATCH_ERROR 183
+# define CMS_R_INVALID_ENCRYPTED_KEY_LENGTH 117
+# define CMS_R_INVALID_KEY_ENCRYPTION_PARAMETER 176
+# define CMS_R_INVALID_KEY_LENGTH 118
+# define CMS_R_INVALID_LABEL 190
+# define CMS_R_INVALID_OAEP_PARAMETERS 191
+# define CMS_R_KDF_PARAMETER_ERROR 186
+# define CMS_R_MD_BIO_INIT_ERROR 119
+# define CMS_R_MESSAGEDIGEST_ATTRIBUTE_WRONG_LENGTH 120
+# define CMS_R_MESSAGEDIGEST_WRONG_LENGTH 121
+# define CMS_R_MSGSIGDIGEST_ERROR 172
+# define CMS_R_MSGSIGDIGEST_VERIFICATION_FAILURE 162
+# define CMS_R_MSGSIGDIGEST_WRONG_LENGTH 163
+# define CMS_R_NEED_ONE_SIGNER 164
+# define CMS_R_NOT_A_SIGNED_RECEIPT 165
+# define CMS_R_NOT_ENCRYPTED_DATA 122
+# define CMS_R_NOT_KEK 123
+# define CMS_R_NOT_KEY_AGREEMENT 181
+# define CMS_R_NOT_KEY_TRANSPORT 124
+# define CMS_R_NOT_PWRI 177
+# define CMS_R_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 125
+# define CMS_R_NO_CIPHER 126
+# define CMS_R_NO_CONTENT 127
+# define CMS_R_NO_CONTENT_TYPE 173
+# define CMS_R_NO_DEFAULT_DIGEST 128
+# define CMS_R_NO_DIGEST_SET 129
+# define CMS_R_NO_KEY 130
+# define CMS_R_NO_KEY_OR_CERT 174
+# define CMS_R_NO_MATCHING_DIGEST 131
+# define CMS_R_NO_MATCHING_RECIPIENT 132
+# define CMS_R_NO_MATCHING_SIGNATURE 166
+# define CMS_R_NO_MSGSIGDIGEST 167
+# define CMS_R_NO_PASSWORD 178
+# define CMS_R_NO_PRIVATE_KEY 133
+# define CMS_R_NO_PUBLIC_KEY 134
+# define CMS_R_NO_RECEIPT_REQUEST 168
+# define CMS_R_NO_SIGNERS 135
+# define CMS_R_PEER_KEY_ERROR 188
+# define CMS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 136
+# define CMS_R_RECEIPT_DECODE_ERROR 169
+# define CMS_R_RECIPIENT_ERROR 137
+# define CMS_R_SHARED_INFO_ERROR 189
+# define CMS_R_SIGNER_CERTIFICATE_NOT_FOUND 138
+# define CMS_R_SIGNFINAL_ERROR 139
+# define CMS_R_SMIME_TEXT_ERROR 140
+# define CMS_R_STORE_INIT_ERROR 141
+# define CMS_R_TYPE_NOT_COMPRESSED_DATA 142
+# define CMS_R_TYPE_NOT_DATA 143
+# define CMS_R_TYPE_NOT_DIGESTED_DATA 144
+# define CMS_R_TYPE_NOT_ENCRYPTED_DATA 145
+# define CMS_R_TYPE_NOT_ENVELOPED_DATA 146
+# define CMS_R_UNABLE_TO_FINALIZE_CONTEXT 147
+# define CMS_R_UNKNOWN_CIPHER 148
+# define CMS_R_UNKNOWN_DIGEST_ALGORITHM 149
+# define CMS_R_UNKNOWN_ID 150
+# define CMS_R_UNSUPPORTED_COMPRESSION_ALGORITHM 151
+# define CMS_R_UNSUPPORTED_CONTENT_TYPE 152
+# define CMS_R_UNSUPPORTED_ENCRYPTION_TYPE 192
+# define CMS_R_UNSUPPORTED_KEK_ALGORITHM 153
+# define CMS_R_UNSUPPORTED_KEY_ENCRYPTION_ALGORITHM 179
+# define CMS_R_UNSUPPORTED_LABEL_SOURCE 193
+# define CMS_R_UNSUPPORTED_RECIPIENTINFO_TYPE 155
+# define CMS_R_UNSUPPORTED_RECIPIENT_TYPE 154
+# define CMS_R_UNSUPPORTED_TYPE 156
+# define CMS_R_UNWRAP_ERROR 157
+# define CMS_R_UNWRAP_FAILURE 180
+# define CMS_R_VERIFICATION_FAILURE 158
+# define CMS_R_WRAP_ERROR 159
+
+# endif
+#endif
diff --git a/include/openssl/comp.h b/include/openssl/comp.h
new file mode 100644
index 00000000..06ff5810
--- /dev/null
+++ b/include/openssl/comp.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright 2015-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_COMP_H
+# define OPENSSL_COMP_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_COMP_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_COMP
+# include <openssl/crypto.h>
+# include <openssl/comperr.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+
+
+COMP_CTX *COMP_CTX_new(COMP_METHOD *meth);
+const COMP_METHOD *COMP_CTX_get_method(const COMP_CTX *ctx);
+int COMP_CTX_get_type(const COMP_CTX* comp);
+int COMP_get_type(const COMP_METHOD *meth);
+const char *COMP_get_name(const COMP_METHOD *meth);
+void COMP_CTX_free(COMP_CTX *ctx);
+
+int COMP_compress_block(COMP_CTX *ctx, unsigned char *out, int olen,
+ unsigned char *in, int ilen);
+int COMP_expand_block(COMP_CTX *ctx, unsigned char *out, int olen,
+ unsigned char *in, int ilen);
+
+COMP_METHOD *COMP_zlib(void);
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define COMP_zlib_cleanup() while(0) continue
+#endif
+
+# ifdef OPENSSL_BIO_H
+# ifdef ZLIB
+const BIO_METHOD *BIO_f_zlib(void);
+# endif
+# endif
+
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/comperr.h b/include/openssl/comperr.h
new file mode 100644
index 00000000..01dd3e6b
--- /dev/null
+++ b/include/openssl/comperr.h
@@ -0,0 +1,31 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_COMPERR_H
+# define OPENSSL_COMPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_COMP
+
+
+/*
+ * COMP reason codes.
+ */
+# define COMP_R_ZLIB_DEFLATE_ERROR 99
+# define COMP_R_ZLIB_INFLATE_ERROR 100
+# define COMP_R_ZLIB_NOT_SUPPORTED 101
+
+# endif
+#endif
diff --git a/include/openssl/conf.h b/include/openssl/conf.h
new file mode 100644
index 00000000..07793f17
--- /dev/null
+++ b/include/openssl/conf.h
@@ -0,0 +1,211 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\conf.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_CONF_H
+# define OPENSSL_CONF_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CONF_H
+# endif
+
+# include <openssl/bio.h>
+# include <openssl/lhash.h>
+# include <openssl/safestack.h>
+# include <openssl/e_os2.h>
+# include <openssl/types.h>
+# include <openssl/conferr.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ char *section;
+ char *name;
+ char *value;
+} CONF_VALUE;
+
+SKM_DEFINE_STACK_OF_INTERNAL(CONF_VALUE, CONF_VALUE, CONF_VALUE)
+#define sk_CONF_VALUE_num(sk) OPENSSL_sk_num(ossl_check_const_CONF_VALUE_sk_type(sk))
+#define sk_CONF_VALUE_value(sk, idx) ((CONF_VALUE *)OPENSSL_sk_value(ossl_check_const_CONF_VALUE_sk_type(sk), (idx)))
+#define sk_CONF_VALUE_new(cmp) ((STACK_OF(CONF_VALUE) *)OPENSSL_sk_new(ossl_check_CONF_VALUE_compfunc_type(cmp)))
+#define sk_CONF_VALUE_new_null() ((STACK_OF(CONF_VALUE) *)OPENSSL_sk_new_null())
+#define sk_CONF_VALUE_new_reserve(cmp, n) ((STACK_OF(CONF_VALUE) *)OPENSSL_sk_new_reserve(ossl_check_CONF_VALUE_compfunc_type(cmp), (n)))
+#define sk_CONF_VALUE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_CONF_VALUE_sk_type(sk), (n))
+#define sk_CONF_VALUE_free(sk) OPENSSL_sk_free(ossl_check_CONF_VALUE_sk_type(sk))
+#define sk_CONF_VALUE_zero(sk) OPENSSL_sk_zero(ossl_check_CONF_VALUE_sk_type(sk))
+#define sk_CONF_VALUE_delete(sk, i) ((CONF_VALUE *)OPENSSL_sk_delete(ossl_check_CONF_VALUE_sk_type(sk), (i)))
+#define sk_CONF_VALUE_delete_ptr(sk, ptr) ((CONF_VALUE *)OPENSSL_sk_delete_ptr(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_type(ptr)))
+#define sk_CONF_VALUE_push(sk, ptr) OPENSSL_sk_push(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_type(ptr))
+#define sk_CONF_VALUE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_type(ptr))
+#define sk_CONF_VALUE_pop(sk) ((CONF_VALUE *)OPENSSL_sk_pop(ossl_check_CONF_VALUE_sk_type(sk)))
+#define sk_CONF_VALUE_shift(sk) ((CONF_VALUE *)OPENSSL_sk_shift(ossl_check_CONF_VALUE_sk_type(sk)))
+#define sk_CONF_VALUE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_CONF_VALUE_sk_type(sk),ossl_check_CONF_VALUE_freefunc_type(freefunc))
+#define sk_CONF_VALUE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_type(ptr), (idx))
+#define sk_CONF_VALUE_set(sk, idx, ptr) ((CONF_VALUE *)OPENSSL_sk_set(ossl_check_CONF_VALUE_sk_type(sk), (idx), ossl_check_CONF_VALUE_type(ptr)))
+#define sk_CONF_VALUE_find(sk, ptr) OPENSSL_sk_find(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_type(ptr))
+#define sk_CONF_VALUE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_type(ptr))
+#define sk_CONF_VALUE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_type(ptr), pnum)
+#define sk_CONF_VALUE_sort(sk) OPENSSL_sk_sort(ossl_check_CONF_VALUE_sk_type(sk))
+#define sk_CONF_VALUE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_CONF_VALUE_sk_type(sk))
+#define sk_CONF_VALUE_dup(sk) ((STACK_OF(CONF_VALUE) *)OPENSSL_sk_dup(ossl_check_const_CONF_VALUE_sk_type(sk)))
+#define sk_CONF_VALUE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(CONF_VALUE) *)OPENSSL_sk_deep_copy(ossl_check_const_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_copyfunc_type(copyfunc), ossl_check_CONF_VALUE_freefunc_type(freefunc)))
+#define sk_CONF_VALUE_set_cmp_func(sk, cmp) ((sk_CONF_VALUE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_CONF_VALUE_sk_type(sk), ossl_check_CONF_VALUE_compfunc_type(cmp)))
+DEFINE_LHASH_OF_INTERNAL(CONF_VALUE);
+#define lh_CONF_VALUE_new(hfn, cmp) ((LHASH_OF(CONF_VALUE) *)OPENSSL_LH_new(ossl_check_CONF_VALUE_lh_hashfunc_type(hfn), ossl_check_CONF_VALUE_lh_compfunc_type(cmp)))
+#define lh_CONF_VALUE_free(lh) OPENSSL_LH_free(ossl_check_CONF_VALUE_lh_type(lh))
+#define lh_CONF_VALUE_flush(lh) OPENSSL_LH_flush(ossl_check_CONF_VALUE_lh_type(lh))
+#define lh_CONF_VALUE_insert(lh, ptr) ((CONF_VALUE *)OPENSSL_LH_insert(ossl_check_CONF_VALUE_lh_type(lh), ossl_check_CONF_VALUE_lh_plain_type(ptr)))
+#define lh_CONF_VALUE_delete(lh, ptr) ((CONF_VALUE *)OPENSSL_LH_delete(ossl_check_CONF_VALUE_lh_type(lh), ossl_check_const_CONF_VALUE_lh_plain_type(ptr)))
+#define lh_CONF_VALUE_retrieve(lh, ptr) ((CONF_VALUE *)OPENSSL_LH_retrieve(ossl_check_CONF_VALUE_lh_type(lh), ossl_check_const_CONF_VALUE_lh_plain_type(ptr)))
+#define lh_CONF_VALUE_error(lh) OPENSSL_LH_error(ossl_check_CONF_VALUE_lh_type(lh))
+#define lh_CONF_VALUE_num_items(lh) OPENSSL_LH_num_items(ossl_check_CONF_VALUE_lh_type(lh))
+#define lh_CONF_VALUE_node_stats_bio(lh, out) OPENSSL_LH_node_stats_bio(ossl_check_const_CONF_VALUE_lh_type(lh), out)
+#define lh_CONF_VALUE_node_usage_stats_bio(lh, out) OPENSSL_LH_node_usage_stats_bio(ossl_check_const_CONF_VALUE_lh_type(lh), out)
+#define lh_CONF_VALUE_stats_bio(lh, out) OPENSSL_LH_stats_bio(ossl_check_const_CONF_VALUE_lh_type(lh), out)
+#define lh_CONF_VALUE_get_down_load(lh) OPENSSL_LH_get_down_load(ossl_check_CONF_VALUE_lh_type(lh))
+#define lh_CONF_VALUE_set_down_load(lh, dl) OPENSSL_LH_set_down_load(ossl_check_CONF_VALUE_lh_type(lh), dl)
+#define lh_CONF_VALUE_doall(lh, dfn) OPENSSL_LH_doall(ossl_check_CONF_VALUE_lh_type(lh), ossl_check_CONF_VALUE_lh_doallfunc_type(dfn))
+
+
+struct conf_st;
+struct conf_method_st;
+typedef struct conf_method_st CONF_METHOD;
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# include <openssl/conftypes.h>
+# endif
+
+/* Module definitions */
+typedef struct conf_imodule_st CONF_IMODULE;
+typedef struct conf_module_st CONF_MODULE;
+
+STACK_OF(CONF_MODULE);
+STACK_OF(CONF_IMODULE);
+
+/* DSO module function typedefs */
+typedef int conf_init_func (CONF_IMODULE *md, const CONF *cnf);
+typedef void conf_finish_func (CONF_IMODULE *md);
+
+# define CONF_MFLAGS_IGNORE_ERRORS 0x1
+# define CONF_MFLAGS_IGNORE_RETURN_CODES 0x2
+# define CONF_MFLAGS_SILENT 0x4
+# define CONF_MFLAGS_NO_DSO 0x8
+# define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10
+# define CONF_MFLAGS_DEFAULT_SECTION 0x20
+
+int CONF_set_default_method(CONF_METHOD *meth);
+void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash);
+LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file,
+ long *eline);
+# ifndef OPENSSL_NO_STDIO
+LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp,
+ long *eline);
+# endif
+LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp,
+ long *eline);
+STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf,
+ const char *section);
+char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group,
+ const char *name);
+long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group,
+ const char *name);
+void CONF_free(LHASH_OF(CONF_VALUE) *conf);
+#ifndef OPENSSL_NO_STDIO
+int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out);
+#endif
+int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out);
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void OPENSSL_config(const char *config_name);
+#endif
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OPENSSL_no_config() \
+ OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, NULL)
+#endif
+
+/*
+ * New conf code. The semantics are different from the functions above. If
+ * that wasn't the case, the above functions would have been replaced
+ */
+
+CONF *NCONF_new_ex(OSSL_LIB_CTX *libctx, CONF_METHOD *meth);
+OSSL_LIB_CTX *NCONF_get0_libctx(const CONF *conf);
+CONF *NCONF_new(CONF_METHOD *meth);
+CONF_METHOD *NCONF_default(void);
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 CONF_METHOD *NCONF_WIN32(void);
+#endif
+void NCONF_free(CONF *conf);
+void NCONF_free_data(CONF *conf);
+
+int NCONF_load(CONF *conf, const char *file, long *eline);
+# ifndef OPENSSL_NO_STDIO
+int NCONF_load_fp(CONF *conf, FILE *fp, long *eline);
+# endif
+int NCONF_load_bio(CONF *conf, BIO *bp, long *eline);
+STACK_OF(OPENSSL_CSTRING) *NCONF_get_section_names(const CONF *conf);
+STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf,
+ const char *section);
+char *NCONF_get_string(const CONF *conf, const char *group, const char *name);
+int NCONF_get_number_e(const CONF *conf, const char *group, const char *name,
+ long *result);
+#ifndef OPENSSL_NO_STDIO
+int NCONF_dump_fp(const CONF *conf, FILE *out);
+#endif
+int NCONF_dump_bio(const CONF *conf, BIO *out);
+
+#define NCONF_get_number(c,g,n,r) NCONF_get_number_e(c,g,n,r)
+
+/* Module functions */
+
+int CONF_modules_load(const CONF *cnf, const char *appname,
+ unsigned long flags);
+int CONF_modules_load_file_ex(OSSL_LIB_CTX *libctx, const char *filename,
+ const char *appname, unsigned long flags);
+int CONF_modules_load_file(const char *filename, const char *appname,
+ unsigned long flags);
+void CONF_modules_unload(int all);
+void CONF_modules_finish(void);
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define CONF_modules_free() while(0) continue
+#endif
+int CONF_module_add(const char *name, conf_init_func *ifunc,
+ conf_finish_func *ffunc);
+
+const char *CONF_imodule_get_name(const CONF_IMODULE *md);
+const char *CONF_imodule_get_value(const CONF_IMODULE *md);
+void *CONF_imodule_get_usr_data(const CONF_IMODULE *md);
+void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data);
+CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md);
+unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md);
+void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags);
+void *CONF_module_get_usr_data(CONF_MODULE *pmod);
+void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data);
+
+char *CONF_get1_default_config_file(void);
+
+int CONF_parse_list(const char *list, int sep, int nospc,
+ int (*list_cb) (const char *elem, int len, void *usr),
+ void *arg);
+
+void OPENSSL_load_builtin_modules(void);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/conf.h.in b/include/openssl/conf.h.in
new file mode 100644
index 00000000..b0bd579a
--- /dev/null
+++ b/include/openssl/conf.h.in
@@ -0,0 +1,174 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros generate_lhash_macros);
+-}
+
+#ifndef OPENSSL_CONF_H
+# define OPENSSL_CONF_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CONF_H
+# endif
+
+# include <openssl/bio.h>
+# include <openssl/lhash.h>
+# include <openssl/safestack.h>
+# include <openssl/e_os2.h>
+# include <openssl/types.h>
+# include <openssl/conferr.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct {
+ char *section;
+ char *name;
+ char *value;
+} CONF_VALUE;
+
+{-
+ generate_stack_macros("CONF_VALUE")
+ .generate_lhash_macros("CONF_VALUE");
+-}
+
+struct conf_st;
+struct conf_method_st;
+typedef struct conf_method_st CONF_METHOD;
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# include <openssl/conftypes.h>
+# endif
+
+/* Module definitions */
+typedef struct conf_imodule_st CONF_IMODULE;
+typedef struct conf_module_st CONF_MODULE;
+
+STACK_OF(CONF_MODULE);
+STACK_OF(CONF_IMODULE);
+
+/* DSO module function typedefs */
+typedef int conf_init_func (CONF_IMODULE *md, const CONF *cnf);
+typedef void conf_finish_func (CONF_IMODULE *md);
+
+# define CONF_MFLAGS_IGNORE_ERRORS 0x1
+# define CONF_MFLAGS_IGNORE_RETURN_CODES 0x2
+# define CONF_MFLAGS_SILENT 0x4
+# define CONF_MFLAGS_NO_DSO 0x8
+# define CONF_MFLAGS_IGNORE_MISSING_FILE 0x10
+# define CONF_MFLAGS_DEFAULT_SECTION 0x20
+
+int CONF_set_default_method(CONF_METHOD *meth);
+void CONF_set_nconf(CONF *conf, LHASH_OF(CONF_VALUE) *hash);
+LHASH_OF(CONF_VALUE) *CONF_load(LHASH_OF(CONF_VALUE) *conf, const char *file,
+ long *eline);
+# ifndef OPENSSL_NO_STDIO
+LHASH_OF(CONF_VALUE) *CONF_load_fp(LHASH_OF(CONF_VALUE) *conf, FILE *fp,
+ long *eline);
+# endif
+LHASH_OF(CONF_VALUE) *CONF_load_bio(LHASH_OF(CONF_VALUE) *conf, BIO *bp,
+ long *eline);
+STACK_OF(CONF_VALUE) *CONF_get_section(LHASH_OF(CONF_VALUE) *conf,
+ const char *section);
+char *CONF_get_string(LHASH_OF(CONF_VALUE) *conf, const char *group,
+ const char *name);
+long CONF_get_number(LHASH_OF(CONF_VALUE) *conf, const char *group,
+ const char *name);
+void CONF_free(LHASH_OF(CONF_VALUE) *conf);
+#ifndef OPENSSL_NO_STDIO
+int CONF_dump_fp(LHASH_OF(CONF_VALUE) *conf, FILE *out);
+#endif
+int CONF_dump_bio(LHASH_OF(CONF_VALUE) *conf, BIO *out);
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void OPENSSL_config(const char *config_name);
+#endif
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OPENSSL_no_config() \
+ OPENSSL_init_crypto(OPENSSL_INIT_NO_LOAD_CONFIG, NULL)
+#endif
+
+/*
+ * New conf code. The semantics are different from the functions above. If
+ * that wasn't the case, the above functions would have been replaced
+ */
+
+CONF *NCONF_new_ex(OSSL_LIB_CTX *libctx, CONF_METHOD *meth);
+OSSL_LIB_CTX *NCONF_get0_libctx(const CONF *conf);
+CONF *NCONF_new(CONF_METHOD *meth);
+CONF_METHOD *NCONF_default(void);
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 CONF_METHOD *NCONF_WIN32(void);
+#endif
+void NCONF_free(CONF *conf);
+void NCONF_free_data(CONF *conf);
+
+int NCONF_load(CONF *conf, const char *file, long *eline);
+# ifndef OPENSSL_NO_STDIO
+int NCONF_load_fp(CONF *conf, FILE *fp, long *eline);
+# endif
+int NCONF_load_bio(CONF *conf, BIO *bp, long *eline);
+STACK_OF(OPENSSL_CSTRING) *NCONF_get_section_names(const CONF *conf);
+STACK_OF(CONF_VALUE) *NCONF_get_section(const CONF *conf,
+ const char *section);
+char *NCONF_get_string(const CONF *conf, const char *group, const char *name);
+int NCONF_get_number_e(const CONF *conf, const char *group, const char *name,
+ long *result);
+#ifndef OPENSSL_NO_STDIO
+int NCONF_dump_fp(const CONF *conf, FILE *out);
+#endif
+int NCONF_dump_bio(const CONF *conf, BIO *out);
+
+#define NCONF_get_number(c,g,n,r) NCONF_get_number_e(c,g,n,r)
+
+/* Module functions */
+
+int CONF_modules_load(const CONF *cnf, const char *appname,
+ unsigned long flags);
+int CONF_modules_load_file_ex(OSSL_LIB_CTX *libctx, const char *filename,
+ const char *appname, unsigned long flags);
+int CONF_modules_load_file(const char *filename, const char *appname,
+ unsigned long flags);
+void CONF_modules_unload(int all);
+void CONF_modules_finish(void);
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define CONF_modules_free() while(0) continue
+#endif
+int CONF_module_add(const char *name, conf_init_func *ifunc,
+ conf_finish_func *ffunc);
+
+const char *CONF_imodule_get_name(const CONF_IMODULE *md);
+const char *CONF_imodule_get_value(const CONF_IMODULE *md);
+void *CONF_imodule_get_usr_data(const CONF_IMODULE *md);
+void CONF_imodule_set_usr_data(CONF_IMODULE *md, void *usr_data);
+CONF_MODULE *CONF_imodule_get_module(const CONF_IMODULE *md);
+unsigned long CONF_imodule_get_flags(const CONF_IMODULE *md);
+void CONF_imodule_set_flags(CONF_IMODULE *md, unsigned long flags);
+void *CONF_module_get_usr_data(CONF_MODULE *pmod);
+void CONF_module_set_usr_data(CONF_MODULE *pmod, void *usr_data);
+
+char *CONF_get1_default_config_file(void);
+
+int CONF_parse_list(const char *list, int sep, int nospc,
+ int (*list_cb) (const char *elem, int len, void *usr),
+ void *arg);
+
+void OPENSSL_load_builtin_modules(void);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/conf_api.h b/include/openssl/conf_api.h
new file mode 100644
index 00000000..ed67d577
--- /dev/null
+++ b/include/openssl/conf_api.h
@@ -0,0 +1,46 @@
+/*
+ * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CONF_API_H
+# define OPENSSL_CONF_API_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CONF_API_H
+# endif
+
+# include <openssl/lhash.h>
+# include <openssl/conf.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Up until OpenSSL 0.9.5a, this was new_section */
+CONF_VALUE *_CONF_new_section(CONF *conf, const char *section);
+/* Up until OpenSSL 0.9.5a, this was get_section */
+CONF_VALUE *_CONF_get_section(const CONF *conf, const char *section);
+/* Up until OpenSSL 0.9.5a, this was CONF_get_section */
+STACK_OF(CONF_VALUE) *_CONF_get_section_values(const CONF *conf,
+ const char *section);
+
+int _CONF_add_string(CONF *conf, CONF_VALUE *section, CONF_VALUE *value);
+char *_CONF_get_string(const CONF *conf, const char *section,
+ const char *name);
+long _CONF_get_number(const CONF *conf, const char *section,
+ const char *name);
+
+int _CONF_new_data(CONF *conf);
+void _CONF_free_data(CONF *conf);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/conferr.h b/include/openssl/conferr.h
new file mode 100644
index 00000000..496e2e1e
--- /dev/null
+++ b/include/openssl/conferr.h
@@ -0,0 +1,51 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CONFERR_H
+# define OPENSSL_CONFERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * CONF reason codes.
+ */
+# define CONF_R_ERROR_LOADING_DSO 110
+# define CONF_R_INVALID_PRAGMA 122
+# define CONF_R_LIST_CANNOT_BE_NULL 115
+# define CONF_R_MANDATORY_BRACES_IN_VARIABLE_EXPANSION 123
+# define CONF_R_MISSING_CLOSE_SQUARE_BRACKET 100
+# define CONF_R_MISSING_EQUAL_SIGN 101
+# define CONF_R_MISSING_INIT_FUNCTION 112
+# define CONF_R_MODULE_INITIALIZATION_ERROR 109
+# define CONF_R_NO_CLOSE_BRACE 102
+# define CONF_R_NO_CONF 105
+# define CONF_R_NO_CONF_OR_ENVIRONMENT_VARIABLE 106
+# define CONF_R_NO_SECTION 107
+# define CONF_R_NO_SUCH_FILE 114
+# define CONF_R_NO_VALUE 108
+# define CONF_R_NUMBER_TOO_LARGE 121
+# define CONF_R_OPENSSL_CONF_REFERENCES_MISSING_SECTION 124
+# define CONF_R_RECURSIVE_DIRECTORY_INCLUDE 111
+# define CONF_R_RELATIVE_PATH 125
+# define CONF_R_SSL_COMMAND_SECTION_EMPTY 117
+# define CONF_R_SSL_COMMAND_SECTION_NOT_FOUND 118
+# define CONF_R_SSL_SECTION_EMPTY 119
+# define CONF_R_SSL_SECTION_NOT_FOUND 120
+# define CONF_R_UNABLE_TO_CREATE_NEW_SECTION 103
+# define CONF_R_UNKNOWN_MODULE_NAME 113
+# define CONF_R_VARIABLE_EXPANSION_TOO_LONG 116
+# define CONF_R_VARIABLE_HAS_NO_VALUE 104
+
+#endif
diff --git a/include/openssl/configuration.h b/include/openssl/configuration.h
new file mode 100644
index 00000000..d9662edd
--- /dev/null
+++ b/include/openssl/configuration.h
@@ -0,0 +1,133 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\configuration.h.in
+ *
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CONFIGURATION_H
+# define OPENSSL_CONFIGURATION_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifdef OPENSSL_ALGORITHM_DEFINES
+# error OPENSSL_ALGORITHM_DEFINES no longer supported
+# endif
+
+/*
+ * OpenSSL was configured with the following options:
+ */
+
+# ifndef OPENSSL_SYS_WIN64A
+# define OPENSSL_SYS_WIN64A 1
+# endif
+# define OPENSSL_CONFIGURED_API 30000
+# ifndef OPENSSL_RAND_SEED_OS
+# define OPENSSL_RAND_SEED_OS
+# endif
+# ifndef OPENSSL_THREADS
+# define OPENSSL_THREADS
+# endif
+# ifndef OPENSSL_NO_ACVP_TESTS
+# define OPENSSL_NO_ACVP_TESTS
+# endif
+# ifndef OPENSSL_NO_AFALGENG
+# define OPENSSL_NO_AFALGENG
+# endif
+# ifndef OPENSSL_NO_ASAN
+# define OPENSSL_NO_ASAN
+# endif
+# ifndef OPENSSL_NO_CRYPTO_MDEBUG
+# define OPENSSL_NO_CRYPTO_MDEBUG
+# endif
+# ifndef OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
+# define OPENSSL_NO_CRYPTO_MDEBUG_BACKTRACE
+# endif
+# ifndef OPENSSL_NO_DEVCRYPTOENG
+# define OPENSSL_NO_DEVCRYPTOENG
+# endif
+# ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
+# define OPENSSL_NO_EC_NISTP_64_GCC_128
+# endif
+# ifndef OPENSSL_NO_EGD
+# define OPENSSL_NO_EGD
+# endif
+# ifndef OPENSSL_NO_EXTERNAL_TESTS
+# define OPENSSL_NO_EXTERNAL_TESTS
+# endif
+# ifndef OPENSSL_NO_FIPS_SECURITYCHECKS
+# define OPENSSL_NO_FIPS_SECURITYCHECKS
+# endif
+# ifndef OPENSSL_NO_FUZZ_AFL
+# define OPENSSL_NO_FUZZ_AFL
+# endif
+# ifndef OPENSSL_NO_FUZZ_LIBFUZZER
+# define OPENSSL_NO_FUZZ_LIBFUZZER
+# endif
+# ifndef OPENSSL_NO_KTLS
+# define OPENSSL_NO_KTLS
+# endif
+# ifndef OPENSSL_NO_MD2
+# define OPENSSL_NO_MD2
+# endif
+# ifndef OPENSSL_NO_MSAN
+# define OPENSSL_NO_MSAN
+# endif
+# ifndef OPENSSL_NO_RC5
+# define OPENSSL_NO_RC5
+# endif
+# ifndef OPENSSL_NO_SCTP
+# define OPENSSL_NO_SCTP
+# endif
+# ifndef OPENSSL_NO_SSL3
+# define OPENSSL_NO_SSL3
+# endif
+# ifndef OPENSSL_NO_SSL3_METHOD
+# define OPENSSL_NO_SSL3_METHOD
+# endif
+# ifndef OPENSSL_NO_TRACE
+# define OPENSSL_NO_TRACE
+# endif
+# ifndef OPENSSL_NO_UBSAN
+# define OPENSSL_NO_UBSAN
+# endif
+# ifndef OPENSSL_NO_UNIT_TEST
+# define OPENSSL_NO_UNIT_TEST
+# endif
+# ifndef OPENSSL_NO_WEAK_SSL_CIPHERS
+# define OPENSSL_NO_WEAK_SSL_CIPHERS
+# endif
+# ifndef OPENSSL_NO_STATIC_ENGINE
+# define OPENSSL_NO_STATIC_ENGINE
+# endif
+
+
+/* Generate 80386 code? */
+# undef I386_ONLY
+
+/*
+ * The following are cipher-specific, but are part of the public API.
+ */
+# if !defined(OPENSSL_SYS_UEFI)
+# undef BN_LLONG
+/* Only one for the following should be defined */
+# undef SIXTY_FOUR_BIT_LONG
+# define SIXTY_FOUR_BIT
+# undef THIRTY_TWO_BIT
+# endif
+
+# define RC4_INT unsigned int
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif /* OPENSSL_CONFIGURATION_H */
diff --git a/include/openssl/configuration.h.in b/include/openssl/configuration.h.in
new file mode 100644
index 00000000..b84dc1df
--- /dev/null
+++ b/include/openssl/configuration.h.in
@@ -0,0 +1,69 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CONFIGURATION_H
+# define OPENSSL_CONFIGURATION_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifdef OPENSSL_ALGORITHM_DEFINES
+# error OPENSSL_ALGORITHM_DEFINES no longer supported
+# endif
+
+/*
+ * OpenSSL was configured with the following options:
+ */
+
+{- if (@{$config{openssl_sys_defines}}) {
+ foreach (@{$config{openssl_sys_defines}}) {
+ $OUT .= "# ifndef $_\n";
+ $OUT .= "# define $_ 1\n";
+ $OUT .= "# endif\n";
+ }
+ }
+ foreach (@{$config{openssl_api_defines}}) {
+ (my $macro, my $value) = $_ =~ /^(.*?)=(.*?)$/;
+ $OUT .= "# define $macro $value\n";
+ }
+ if (@{$config{openssl_feature_defines}}) {
+ foreach (@{$config{openssl_feature_defines}}) {
+ $OUT .= "# ifndef $_\n";
+ $OUT .= "# define $_\n";
+ $OUT .= "# endif\n";
+ }
+ }
+ "";
+-}
+
+/* Generate 80386 code? */
+{- $config{processor} eq "386" ? "# define" : "# undef" -} I386_ONLY
+
+/*
+ * The following are cipher-specific, but are part of the public API.
+ */
+# if !defined(OPENSSL_SYS_UEFI)
+{- $config{bn_ll} ? "# define" : "# undef" -} BN_LLONG
+/* Only one for the following should be defined */
+{- $config{b64l} ? "# define" : "# undef" -} SIXTY_FOUR_BIT_LONG
+{- $config{b64} ? "# define" : "# undef" -} SIXTY_FOUR_BIT
+{- $config{b32} ? "# define" : "# undef" -} THIRTY_TWO_BIT
+# endif
+
+# define RC4_INT {- $config{rc4_int} -}
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif /* OPENSSL_CONFIGURATION_H */
diff --git a/include/openssl/conftypes.h b/include/openssl/conftypes.h
new file mode 100644
index 00000000..17cefaa4
--- /dev/null
+++ b/include/openssl/conftypes.h
@@ -0,0 +1,44 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CONFTYPES_H
+# define OPENSSL_CONFTYPES_H
+# pragma once
+
+#ifndef OPENSSL_CONF_H
+# include <openssl/conf.h>
+#endif
+
+/*
+ * The contents of this file are deprecated and will be made opaque
+ */
+struct conf_method_st {
+ const char *name;
+ CONF *(*create) (CONF_METHOD *meth);
+ int (*init) (CONF *conf);
+ int (*destroy) (CONF *conf);
+ int (*destroy_data) (CONF *conf);
+ int (*load_bio) (CONF *conf, BIO *bp, long *eline);
+ int (*dump) (const CONF *conf, BIO *bp);
+ int (*is_number) (const CONF *conf, char c);
+ int (*to_int) (const CONF *conf, char c);
+ int (*load) (CONF *conf, const char *name, long *eline);
+};
+
+struct conf_st {
+ CONF_METHOD *meth;
+ void *meth_data;
+ LHASH_OF(CONF_VALUE) *data;
+ int flag_dollarid;
+ int flag_abspath;
+ char *includedir;
+ OSSL_LIB_CTX *libctx;
+};
+
+#endif
diff --git a/include/openssl/core.h b/include/openssl/core.h
new file mode 100644
index 00000000..9683ac70
--- /dev/null
+++ b/include/openssl/core.h
@@ -0,0 +1,233 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CORE_H
+# define OPENSSL_CORE_H
+# pragma once
+
+# include <stddef.h>
+# include <openssl/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*-
+ * Base types
+ * ----------
+ *
+ * These are the types that the OpenSSL core and providers have in common
+ * to communicate data between them.
+ */
+
+/* Opaque handles to be used with core upcall functions from providers */
+typedef struct ossl_core_handle_st OSSL_CORE_HANDLE;
+typedef struct openssl_core_ctx_st OPENSSL_CORE_CTX;
+typedef struct ossl_core_bio_st OSSL_CORE_BIO;
+
+/*
+ * Dispatch table element. function_id numbers and the functions are defined
+ * in core_dispatch.h, see macros with 'OSSL_CORE_MAKE_FUNC' in their names.
+ *
+ * An array of these is always terminated by function_id == 0
+ */
+struct ossl_dispatch_st {
+ int function_id;
+ void (*function)(void);
+};
+
+/*
+ * Other items, essentially an int<->pointer map element.
+ *
+ * We make this type distinct from OSSL_DISPATCH to ensure that dispatch
+ * tables remain tables with function pointers only.
+ *
+ * This is used whenever we need to pass things like a table of error reason
+ * codes <-> reason string maps, ...
+ *
+ * Usage determines which field works as key if any, rather than field order.
+ *
+ * An array of these is always terminated by id == 0 && ptr == NULL
+ */
+struct ossl_item_st {
+ unsigned int id;
+ void *ptr;
+};
+
+/*
+ * Type to tie together algorithm names, property definition string and
+ * the algorithm implementation in the form of a dispatch table.
+ *
+ * An array of these is always terminated by algorithm_names == NULL
+ */
+struct ossl_algorithm_st {
+ const char *algorithm_names; /* key */
+ const char *property_definition; /* key */
+ const OSSL_DISPATCH *implementation;
+ const char *algorithm_description;
+};
+
+/*
+ * Type to pass object data in a uniform way, without exposing the object
+ * structure.
+ *
+ * An array of these is always terminated by key == NULL
+ */
+struct ossl_param_st {
+ const char *key; /* the name of the parameter */
+ unsigned int data_type; /* declare what kind of content is in buffer */
+ void *data; /* value being passed in or out */
+ size_t data_size; /* data size */
+ size_t return_size; /* returned content size */
+};
+
+/* Currently supported OSSL_PARAM data types */
+/*
+ * OSSL_PARAM_INTEGER and OSSL_PARAM_UNSIGNED_INTEGER
+ * are arbitrary length and therefore require an arbitrarily sized buffer,
+ * since they may be used to pass numbers larger than what is natively
+ * available.
+ *
+ * The number must be buffered in native form, i.e. MSB first on B_ENDIAN
+ * systems and LSB first on L_ENDIAN systems. This means that arbitrary
+ * native integers can be stored in the buffer, just make sure that the
+ * buffer size is correct and the buffer itself is properly aligned (for
+ * example by having the buffer field point at a C integer).
+ */
+# define OSSL_PARAM_INTEGER 1
+# define OSSL_PARAM_UNSIGNED_INTEGER 2
+/*-
+ * OSSL_PARAM_REAL
+ * is a C binary floating point values in native form and alignment.
+ */
+# define OSSL_PARAM_REAL 3
+/*-
+ * OSSL_PARAM_UTF8_STRING
+ * is a printable string. It is expected to be printed as it is.
+ */
+# define OSSL_PARAM_UTF8_STRING 4
+/*-
+ * OSSL_PARAM_OCTET_STRING
+ * is a string of bytes with no further specification. It is expected to be
+ * printed as a hexdump.
+ */
+# define OSSL_PARAM_OCTET_STRING 5
+/*-
+ * OSSL_PARAM_UTF8_PTR
+ * is a pointer to a printable string. It is expected to be printed as it is.
+ *
+ * The difference between this and OSSL_PARAM_UTF8_STRING is that only pointers
+ * are manipulated for this type.
+ *
+ * This is more relevant for parameter requests, where the responding
+ * function doesn't need to copy the data to the provided buffer, but
+ * sets the provided buffer to point at the actual data instead.
+ *
+ * WARNING! Using these is FRAGILE, as it assumes that the actual
+ * data and its location are constant.
+ *
+ * EXTRA WARNING! If you are not completely sure you most likely want
+ * to use the OSSL_PARAM_UTF8_STRING type.
+ */
+# define OSSL_PARAM_UTF8_PTR 6
+/*-
+ * OSSL_PARAM_OCTET_PTR
+ * is a pointer to a string of bytes with no further specification. It is
+ * expected to be printed as a hexdump.
+ *
+ * The difference between this and OSSL_PARAM_OCTET_STRING is that only pointers
+ * are manipulated for this type.
+ *
+ * This is more relevant for parameter requests, where the responding
+ * function doesn't need to copy the data to the provided buffer, but
+ * sets the provided buffer to point at the actual data instead.
+ *
+ * WARNING! Using these is FRAGILE, as it assumes that the actual
+ * data and its location are constant.
+ *
+ * EXTRA WARNING! If you are not completely sure you most likely want
+ * to use the OSSL_PARAM_OCTET_STRING type.
+ */
+# define OSSL_PARAM_OCTET_PTR 7
+
+/*
+ * Typedef for the thread stop handling callback. Used both internally and by
+ * providers.
+ *
+ * Providers may register for notifications about threads stopping by
+ * registering a callback to hear about such events. Providers register the
+ * callback using the OSSL_FUNC_CORE_THREAD_START function in the |in| dispatch
+ * table passed to OSSL_provider_init(). The arg passed back to a provider will
+ * be the provider side context object.
+ */
+typedef void (*OSSL_thread_stop_handler_fn)(void *arg);
+
+
+/*-
+ * Provider entry point
+ * --------------------
+ *
+ * This function is expected to be present in any dynamically loadable
+ * provider module. By definition, if this function doesn't exist in a
+ * module, that module is not an OpenSSL provider module.
+ */
+/*-
+ * |handle| pointer to opaque type OSSL_CORE_HANDLE. This can be used
+ * together with some functions passed via |in| to query data.
+ * |in| is the array of functions that the Core passes to the provider.
+ * |out| will be the array of base functions that the provider passes
+ * back to the Core.
+ * |provctx| a provider side context object, optionally created if the
+ * provider needs it. This value is passed to other provider
+ * functions, notably other context constructors.
+ */
+typedef int (OSSL_provider_init_fn)(const OSSL_CORE_HANDLE *handle,
+ const OSSL_DISPATCH *in,
+ const OSSL_DISPATCH **out,
+ void **provctx);
+# ifdef __VMS
+# pragma names save
+# pragma names uppercase,truncated
+# endif
+OPENSSL_EXPORT OSSL_provider_init_fn OSSL_provider_init;
+# ifdef __VMS
+# pragma names restore
+# endif
+
+/*
+ * Generic callback function signature.
+ *
+ * The expectation is that any provider function that wants to offer
+ * a callback / hook can do so by taking an argument with this type,
+ * as well as a pointer to caller-specific data. When calling the
+ * callback, the provider function can populate an OSSL_PARAM array
+ * with data of its choice and pass that in the callback call, along
+ * with the caller data argument.
+ *
+ * libcrypto may use the OSSL_PARAM array to create arguments for an
+ * application callback it knows about.
+ */
+typedef int (OSSL_CALLBACK)(const OSSL_PARAM params[], void *arg);
+typedef int (OSSL_INOUT_CALLBACK)(const OSSL_PARAM in_params[],
+ OSSL_PARAM out_params[], void *arg);
+/*
+ * Passphrase callback function signature
+ *
+ * This is similar to the generic callback function above, but adds a
+ * result parameter.
+ */
+typedef int (OSSL_PASSPHRASE_CALLBACK)(char *pass, size_t pass_size,
+ size_t *pass_len,
+ const OSSL_PARAM params[], void *arg);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/core_dispatch.h b/include/openssl/core_dispatch.h
new file mode 100644
index 00000000..99fcda00
--- /dev/null
+++ b/include/openssl/core_dispatch.h
@@ -0,0 +1,943 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CORE_NUMBERS_H
+# define OPENSSL_CORE_NUMBERS_H
+# pragma once
+
+# include <stdarg.h>
+# include <openssl/core.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*-
+ * Identities
+ * ----------
+ *
+ * All series start with 1, to allow 0 to be an array terminator.
+ * For any FUNC identity, we also provide a function signature typedef
+ * and a static inline function to extract a function pointer from a
+ * OSSL_DISPATCH element in a type safe manner.
+ *
+ * Names:
+ * for any function base name 'foo' (uppercase form 'FOO'), we will have
+ * the following:
+ * - a macro for the identity with the name OSSL_FUNC_'FOO' or derivatives
+ * thereof (to be specified further down)
+ * - a function signature typedef with the name OSSL_FUNC_'foo'_fn
+ * - a function pointer extractor function with the name OSSL_FUNC_'foo'
+ */
+
+/*
+ * Helper macro to create the function signature typedef and the extractor
+ * |type| is the return-type of the function, |name| is the name of the
+ * function to fetch, and |args| is a parenthesized list of parameters
+ * for the function (that is, it is |name|'s function signature).
+ * Note: This is considered a "reserved" internal macro. Applications should
+ * not use this or assume its existence.
+ */
+#define OSSL_CORE_MAKE_FUNC(type,name,args) \
+ typedef type (OSSL_FUNC_##name##_fn)args; \
+ static ossl_unused ossl_inline \
+ OSSL_FUNC_##name##_fn *OSSL_FUNC_##name(const OSSL_DISPATCH *opf) \
+ { \
+ return (OSSL_FUNC_##name##_fn *)opf->function; \
+ }
+
+/*
+ * Core function identities, for the two OSSL_DISPATCH tables being passed
+ * in the OSSL_provider_init call.
+ *
+ * 0 serves as a marker for the end of the OSSL_DISPATCH array, and must
+ * therefore NEVER be used as a function identity.
+ */
+/* Functions provided by the Core to the provider, reserved numbers 1-1023 */
+# define OSSL_FUNC_CORE_GETTABLE_PARAMS 1
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *,
+ core_gettable_params,(const OSSL_CORE_HANDLE *prov))
+# define OSSL_FUNC_CORE_GET_PARAMS 2
+OSSL_CORE_MAKE_FUNC(int,core_get_params,(const OSSL_CORE_HANDLE *prov,
+ OSSL_PARAM params[]))
+# define OSSL_FUNC_CORE_THREAD_START 3
+OSSL_CORE_MAKE_FUNC(int,core_thread_start,(const OSSL_CORE_HANDLE *prov,
+ OSSL_thread_stop_handler_fn handfn,
+ void *arg))
+# define OSSL_FUNC_CORE_GET_LIBCTX 4
+OSSL_CORE_MAKE_FUNC(OPENSSL_CORE_CTX *,core_get_libctx,
+ (const OSSL_CORE_HANDLE *prov))
+# define OSSL_FUNC_CORE_NEW_ERROR 5
+OSSL_CORE_MAKE_FUNC(void,core_new_error,(const OSSL_CORE_HANDLE *prov))
+# define OSSL_FUNC_CORE_SET_ERROR_DEBUG 6
+OSSL_CORE_MAKE_FUNC(void,core_set_error_debug,
+ (const OSSL_CORE_HANDLE *prov,
+ const char *file, int line, const char *func))
+# define OSSL_FUNC_CORE_VSET_ERROR 7
+OSSL_CORE_MAKE_FUNC(void,core_vset_error,
+ (const OSSL_CORE_HANDLE *prov,
+ uint32_t reason, const char *fmt, va_list args))
+# define OSSL_FUNC_CORE_SET_ERROR_MARK 8
+OSSL_CORE_MAKE_FUNC(int, core_set_error_mark, (const OSSL_CORE_HANDLE *prov))
+# define OSSL_FUNC_CORE_CLEAR_LAST_ERROR_MARK 9
+OSSL_CORE_MAKE_FUNC(int, core_clear_last_error_mark,
+ (const OSSL_CORE_HANDLE *prov))
+# define OSSL_FUNC_CORE_POP_ERROR_TO_MARK 10
+OSSL_CORE_MAKE_FUNC(int, core_pop_error_to_mark, (const OSSL_CORE_HANDLE *prov))
+
+
+/* Functions to access the OBJ database */
+
+#define OSSL_FUNC_CORE_OBJ_ADD_SIGID 11
+#define OSSL_FUNC_CORE_OBJ_CREATE 12
+
+OSSL_CORE_MAKE_FUNC(int, core_obj_add_sigid,
+ (const OSSL_CORE_HANDLE *prov, const char *sign_name,
+ const char *digest_name, const char *pkey_name))
+OSSL_CORE_MAKE_FUNC(int, core_obj_create,
+ (const OSSL_CORE_HANDLE *prov, const char *oid,
+ const char *sn, const char *ln))
+
+/* Memory allocation, freeing, clearing. */
+#define OSSL_FUNC_CRYPTO_MALLOC 20
+OSSL_CORE_MAKE_FUNC(void *,
+ CRYPTO_malloc, (size_t num, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_ZALLOC 21
+OSSL_CORE_MAKE_FUNC(void *,
+ CRYPTO_zalloc, (size_t num, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_FREE 22
+OSSL_CORE_MAKE_FUNC(void,
+ CRYPTO_free, (void *ptr, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_CLEAR_FREE 23
+OSSL_CORE_MAKE_FUNC(void,
+ CRYPTO_clear_free, (void *ptr, size_t num, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_REALLOC 24
+OSSL_CORE_MAKE_FUNC(void *,
+ CRYPTO_realloc, (void *addr, size_t num, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_CLEAR_REALLOC 25
+OSSL_CORE_MAKE_FUNC(void *,
+ CRYPTO_clear_realloc, (void *addr, size_t old_num, size_t num,
+ const char *file, int line))
+#define OSSL_FUNC_CRYPTO_SECURE_MALLOC 26
+OSSL_CORE_MAKE_FUNC(void *,
+ CRYPTO_secure_malloc, (size_t num, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_SECURE_ZALLOC 27
+OSSL_CORE_MAKE_FUNC(void *,
+ CRYPTO_secure_zalloc, (size_t num, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_SECURE_FREE 28
+OSSL_CORE_MAKE_FUNC(void,
+ CRYPTO_secure_free, (void *ptr, const char *file, int line))
+#define OSSL_FUNC_CRYPTO_SECURE_CLEAR_FREE 29
+OSSL_CORE_MAKE_FUNC(void,
+ CRYPTO_secure_clear_free, (void *ptr, size_t num, const char *file,
+ int line))
+#define OSSL_FUNC_CRYPTO_SECURE_ALLOCATED 30
+OSSL_CORE_MAKE_FUNC(int,
+ CRYPTO_secure_allocated, (const void *ptr))
+#define OSSL_FUNC_OPENSSL_CLEANSE 31
+OSSL_CORE_MAKE_FUNC(void,
+ OPENSSL_cleanse, (void *ptr, size_t len))
+
+/* Bio functions provided by the core */
+#define OSSL_FUNC_BIO_NEW_FILE 40
+#define OSSL_FUNC_BIO_NEW_MEMBUF 41
+#define OSSL_FUNC_BIO_READ_EX 42
+#define OSSL_FUNC_BIO_WRITE_EX 43
+#define OSSL_FUNC_BIO_UP_REF 44
+#define OSSL_FUNC_BIO_FREE 45
+#define OSSL_FUNC_BIO_VPRINTF 46
+#define OSSL_FUNC_BIO_VSNPRINTF 47
+#define OSSL_FUNC_BIO_PUTS 48
+#define OSSL_FUNC_BIO_GETS 49
+#define OSSL_FUNC_BIO_CTRL 50
+
+
+OSSL_CORE_MAKE_FUNC(OSSL_CORE_BIO *, BIO_new_file, (const char *filename,
+ const char *mode))
+OSSL_CORE_MAKE_FUNC(OSSL_CORE_BIO *, BIO_new_membuf, (const void *buf, int len))
+OSSL_CORE_MAKE_FUNC(int, BIO_read_ex, (OSSL_CORE_BIO *bio, void *data,
+ size_t data_len, size_t *bytes_read))
+OSSL_CORE_MAKE_FUNC(int, BIO_write_ex, (OSSL_CORE_BIO *bio, const void *data,
+ size_t data_len, size_t *written))
+OSSL_CORE_MAKE_FUNC(int, BIO_gets, (OSSL_CORE_BIO *bio, char *buf, int size))
+OSSL_CORE_MAKE_FUNC(int, BIO_puts, (OSSL_CORE_BIO *bio, const char *str))
+OSSL_CORE_MAKE_FUNC(int, BIO_up_ref, (OSSL_CORE_BIO *bio))
+OSSL_CORE_MAKE_FUNC(int, BIO_free, (OSSL_CORE_BIO *bio))
+OSSL_CORE_MAKE_FUNC(int, BIO_vprintf, (OSSL_CORE_BIO *bio, const char *format,
+ va_list args))
+OSSL_CORE_MAKE_FUNC(int, BIO_vsnprintf,
+ (char *buf, size_t n, const char *fmt, va_list args))
+OSSL_CORE_MAKE_FUNC(int, BIO_ctrl, (OSSL_CORE_BIO *bio,
+ int cmd, long num, void *ptr))
+
+#define OSSL_FUNC_SELF_TEST_CB 100
+OSSL_CORE_MAKE_FUNC(void, self_test_cb, (OPENSSL_CORE_CTX *ctx, OSSL_CALLBACK **cb,
+ void **cbarg))
+
+/* Functions to get seed material from the operating system */
+#define OSSL_FUNC_GET_ENTROPY 101
+#define OSSL_FUNC_CLEANUP_ENTROPY 102
+#define OSSL_FUNC_GET_NONCE 103
+#define OSSL_FUNC_CLEANUP_NONCE 104
+OSSL_CORE_MAKE_FUNC(size_t, get_entropy, (const OSSL_CORE_HANDLE *handle,
+ unsigned char **pout, int entropy,
+ size_t min_len, size_t max_len))
+OSSL_CORE_MAKE_FUNC(void, cleanup_entropy, (const OSSL_CORE_HANDLE *handle,
+ unsigned char *buf, size_t len))
+OSSL_CORE_MAKE_FUNC(size_t, get_nonce, (const OSSL_CORE_HANDLE *handle,
+ unsigned char **pout, size_t min_len,
+ size_t max_len, const void *salt,
+ size_t salt_len))
+OSSL_CORE_MAKE_FUNC(void, cleanup_nonce, (const OSSL_CORE_HANDLE *handle,
+ unsigned char *buf, size_t len))
+
+/* Functions to access the core's providers */
+#define OSSL_FUNC_PROVIDER_REGISTER_CHILD_CB 105
+#define OSSL_FUNC_PROVIDER_DEREGISTER_CHILD_CB 106
+#define OSSL_FUNC_PROVIDER_NAME 107
+#define OSSL_FUNC_PROVIDER_GET0_PROVIDER_CTX 108
+#define OSSL_FUNC_PROVIDER_GET0_DISPATCH 109
+#define OSSL_FUNC_PROVIDER_UP_REF 110
+#define OSSL_FUNC_PROVIDER_FREE 111
+
+OSSL_CORE_MAKE_FUNC(int, provider_register_child_cb,
+ (const OSSL_CORE_HANDLE *handle,
+ int (*create_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata),
+ int (*remove_cb)(const OSSL_CORE_HANDLE *provider, void *cbdata),
+ int (*global_props_cb)(const char *props, void *cbdata),
+ void *cbdata))
+OSSL_CORE_MAKE_FUNC(void, provider_deregister_child_cb,
+ (const OSSL_CORE_HANDLE *handle))
+OSSL_CORE_MAKE_FUNC(const char *, provider_name,
+ (const OSSL_CORE_HANDLE *prov))
+OSSL_CORE_MAKE_FUNC(void *, provider_get0_provider_ctx,
+ (const OSSL_CORE_HANDLE *prov))
+OSSL_CORE_MAKE_FUNC(const OSSL_DISPATCH *, provider_get0_dispatch,
+ (const OSSL_CORE_HANDLE *prov))
+OSSL_CORE_MAKE_FUNC(int, provider_up_ref,
+ (const OSSL_CORE_HANDLE *prov, int activate))
+OSSL_CORE_MAKE_FUNC(int, provider_free,
+ (const OSSL_CORE_HANDLE *prov, int deactivate))
+
+/* Functions provided by the provider to the Core, reserved numbers 1024-1535 */
+# define OSSL_FUNC_PROVIDER_TEARDOWN 1024
+OSSL_CORE_MAKE_FUNC(void,provider_teardown,(void *provctx))
+# define OSSL_FUNC_PROVIDER_GETTABLE_PARAMS 1025
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *,
+ provider_gettable_params,(void *provctx))
+# define OSSL_FUNC_PROVIDER_GET_PARAMS 1026
+OSSL_CORE_MAKE_FUNC(int,provider_get_params,(void *provctx,
+ OSSL_PARAM params[]))
+# define OSSL_FUNC_PROVIDER_QUERY_OPERATION 1027
+OSSL_CORE_MAKE_FUNC(const OSSL_ALGORITHM *,provider_query_operation,
+ (void *provctx, int operation_id, int *no_store))
+# define OSSL_FUNC_PROVIDER_UNQUERY_OPERATION 1028
+OSSL_CORE_MAKE_FUNC(void, provider_unquery_operation,
+ (void *provctx, int operation_id, const OSSL_ALGORITHM *))
+# define OSSL_FUNC_PROVIDER_GET_REASON_STRINGS 1029
+OSSL_CORE_MAKE_FUNC(const OSSL_ITEM *,provider_get_reason_strings,
+ (void *provctx))
+# define OSSL_FUNC_PROVIDER_GET_CAPABILITIES 1030
+OSSL_CORE_MAKE_FUNC(int, provider_get_capabilities, (void *provctx,
+ const char *capability, OSSL_CALLBACK *cb, void *arg))
+# define OSSL_FUNC_PROVIDER_SELF_TEST 1031
+OSSL_CORE_MAKE_FUNC(int, provider_self_test, (void *provctx))
+
+/* Operations */
+
+# define OSSL_OP_DIGEST 1
+# define OSSL_OP_CIPHER 2 /* Symmetric Ciphers */
+# define OSSL_OP_MAC 3
+# define OSSL_OP_KDF 4
+# define OSSL_OP_RAND 5
+# define OSSL_OP_KEYMGMT 10
+# define OSSL_OP_KEYEXCH 11
+# define OSSL_OP_SIGNATURE 12
+# define OSSL_OP_ASYM_CIPHER 13
+# define OSSL_OP_KEM 14
+/* New section for non-EVP operations */
+# define OSSL_OP_ENCODER 20
+# define OSSL_OP_DECODER 21
+# define OSSL_OP_STORE 22
+/* Highest known operation number */
+# define OSSL_OP__HIGHEST 22
+
+/* Digests */
+
+# define OSSL_FUNC_DIGEST_NEWCTX 1
+# define OSSL_FUNC_DIGEST_INIT 2
+# define OSSL_FUNC_DIGEST_UPDATE 3
+# define OSSL_FUNC_DIGEST_FINAL 4
+# define OSSL_FUNC_DIGEST_DIGEST 5
+# define OSSL_FUNC_DIGEST_FREECTX 6
+# define OSSL_FUNC_DIGEST_DUPCTX 7
+# define OSSL_FUNC_DIGEST_GET_PARAMS 8
+# define OSSL_FUNC_DIGEST_SET_CTX_PARAMS 9
+# define OSSL_FUNC_DIGEST_GET_CTX_PARAMS 10
+# define OSSL_FUNC_DIGEST_GETTABLE_PARAMS 11
+# define OSSL_FUNC_DIGEST_SETTABLE_CTX_PARAMS 12
+# define OSSL_FUNC_DIGEST_GETTABLE_CTX_PARAMS 13
+
+OSSL_CORE_MAKE_FUNC(void *, digest_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, digest_init, (void *dctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, digest_update,
+ (void *dctx, const unsigned char *in, size_t inl))
+OSSL_CORE_MAKE_FUNC(int, digest_final,
+ (void *dctx,
+ unsigned char *out, size_t *outl, size_t outsz))
+OSSL_CORE_MAKE_FUNC(int, digest_digest,
+ (void *provctx, const unsigned char *in, size_t inl,
+ unsigned char *out, size_t *outl, size_t outsz))
+
+OSSL_CORE_MAKE_FUNC(void, digest_freectx, (void *dctx))
+OSSL_CORE_MAKE_FUNC(void *, digest_dupctx, (void *dctx))
+
+OSSL_CORE_MAKE_FUNC(int, digest_get_params, (OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, digest_set_ctx_params,
+ (void *vctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, digest_get_ctx_params,
+ (void *vctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, digest_gettable_params,
+ (void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, digest_settable_ctx_params,
+ (void *dctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, digest_gettable_ctx_params,
+ (void *dctx, void *provctx))
+
+/* Symmetric Ciphers */
+
+# define OSSL_FUNC_CIPHER_NEWCTX 1
+# define OSSL_FUNC_CIPHER_ENCRYPT_INIT 2
+# define OSSL_FUNC_CIPHER_DECRYPT_INIT 3
+# define OSSL_FUNC_CIPHER_UPDATE 4
+# define OSSL_FUNC_CIPHER_FINAL 5
+# define OSSL_FUNC_CIPHER_CIPHER 6
+# define OSSL_FUNC_CIPHER_FREECTX 7
+# define OSSL_FUNC_CIPHER_DUPCTX 8
+# define OSSL_FUNC_CIPHER_GET_PARAMS 9
+# define OSSL_FUNC_CIPHER_GET_CTX_PARAMS 10
+# define OSSL_FUNC_CIPHER_SET_CTX_PARAMS 11
+# define OSSL_FUNC_CIPHER_GETTABLE_PARAMS 12
+# define OSSL_FUNC_CIPHER_GETTABLE_CTX_PARAMS 13
+# define OSSL_FUNC_CIPHER_SETTABLE_CTX_PARAMS 14
+
+OSSL_CORE_MAKE_FUNC(void *, cipher_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, cipher_encrypt_init, (void *cctx,
+ const unsigned char *key,
+ size_t keylen,
+ const unsigned char *iv,
+ size_t ivlen,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, cipher_decrypt_init, (void *cctx,
+ const unsigned char *key,
+ size_t keylen,
+ const unsigned char *iv,
+ size_t ivlen,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, cipher_update,
+ (void *cctx,
+ unsigned char *out, size_t *outl, size_t outsize,
+ const unsigned char *in, size_t inl))
+OSSL_CORE_MAKE_FUNC(int, cipher_final,
+ (void *cctx,
+ unsigned char *out, size_t *outl, size_t outsize))
+OSSL_CORE_MAKE_FUNC(int, cipher_cipher,
+ (void *cctx,
+ unsigned char *out, size_t *outl, size_t outsize,
+ const unsigned char *in, size_t inl))
+OSSL_CORE_MAKE_FUNC(void, cipher_freectx, (void *cctx))
+OSSL_CORE_MAKE_FUNC(void *, cipher_dupctx, (void *cctx))
+OSSL_CORE_MAKE_FUNC(int, cipher_get_params, (OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, cipher_get_ctx_params, (void *cctx,
+ OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, cipher_set_ctx_params, (void *cctx,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, cipher_gettable_params,
+ (void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, cipher_settable_ctx_params,
+ (void *cctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, cipher_gettable_ctx_params,
+ (void *cctx, void *provctx))
+
+/* MACs */
+
+# define OSSL_FUNC_MAC_NEWCTX 1
+# define OSSL_FUNC_MAC_DUPCTX 2
+# define OSSL_FUNC_MAC_FREECTX 3
+# define OSSL_FUNC_MAC_INIT 4
+# define OSSL_FUNC_MAC_UPDATE 5
+# define OSSL_FUNC_MAC_FINAL 6
+# define OSSL_FUNC_MAC_GET_PARAMS 7
+# define OSSL_FUNC_MAC_GET_CTX_PARAMS 8
+# define OSSL_FUNC_MAC_SET_CTX_PARAMS 9
+# define OSSL_FUNC_MAC_GETTABLE_PARAMS 10
+# define OSSL_FUNC_MAC_GETTABLE_CTX_PARAMS 11
+# define OSSL_FUNC_MAC_SETTABLE_CTX_PARAMS 12
+
+OSSL_CORE_MAKE_FUNC(void *, mac_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(void *, mac_dupctx, (void *src))
+OSSL_CORE_MAKE_FUNC(void, mac_freectx, (void *mctx))
+OSSL_CORE_MAKE_FUNC(int, mac_init, (void *mctx, const unsigned char *key,
+ size_t keylen, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, mac_update,
+ (void *mctx, const unsigned char *in, size_t inl))
+OSSL_CORE_MAKE_FUNC(int, mac_final,
+ (void *mctx,
+ unsigned char *out, size_t *outl, size_t outsize))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, mac_gettable_params, (void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, mac_gettable_ctx_params,
+ (void *mctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, mac_settable_ctx_params,
+ (void *mctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int, mac_get_params, (OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, mac_get_ctx_params,
+ (void *mctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, mac_set_ctx_params,
+ (void *mctx, const OSSL_PARAM params[]))
+
+/* KDFs and PRFs */
+
+# define OSSL_FUNC_KDF_NEWCTX 1
+# define OSSL_FUNC_KDF_DUPCTX 2
+# define OSSL_FUNC_KDF_FREECTX 3
+# define OSSL_FUNC_KDF_RESET 4
+# define OSSL_FUNC_KDF_DERIVE 5
+# define OSSL_FUNC_KDF_GETTABLE_PARAMS 6
+# define OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS 7
+# define OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS 8
+# define OSSL_FUNC_KDF_GET_PARAMS 9
+# define OSSL_FUNC_KDF_GET_CTX_PARAMS 10
+# define OSSL_FUNC_KDF_SET_CTX_PARAMS 11
+
+OSSL_CORE_MAKE_FUNC(void *, kdf_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(void *, kdf_dupctx, (void *src))
+OSSL_CORE_MAKE_FUNC(void, kdf_freectx, (void *kctx))
+OSSL_CORE_MAKE_FUNC(void, kdf_reset, (void *kctx))
+OSSL_CORE_MAKE_FUNC(int, kdf_derive, (void *kctx, unsigned char *key,
+ size_t keylen, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, kdf_gettable_params, (void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, kdf_gettable_ctx_params,
+ (void *kctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, kdf_settable_ctx_params,
+ (void *kctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int, kdf_get_params, (OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, kdf_get_ctx_params,
+ (void *kctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, kdf_set_ctx_params,
+ (void *kctx, const OSSL_PARAM params[]))
+
+/* RAND */
+
+# define OSSL_FUNC_RAND_NEWCTX 1
+# define OSSL_FUNC_RAND_FREECTX 2
+# define OSSL_FUNC_RAND_INSTANTIATE 3
+# define OSSL_FUNC_RAND_UNINSTANTIATE 4
+# define OSSL_FUNC_RAND_GENERATE 5
+# define OSSL_FUNC_RAND_RESEED 6
+# define OSSL_FUNC_RAND_NONCE 7
+# define OSSL_FUNC_RAND_ENABLE_LOCKING 8
+# define OSSL_FUNC_RAND_LOCK 9
+# define OSSL_FUNC_RAND_UNLOCK 10
+# define OSSL_FUNC_RAND_GETTABLE_PARAMS 11
+# define OSSL_FUNC_RAND_GETTABLE_CTX_PARAMS 12
+# define OSSL_FUNC_RAND_SETTABLE_CTX_PARAMS 13
+# define OSSL_FUNC_RAND_GET_PARAMS 14
+# define OSSL_FUNC_RAND_GET_CTX_PARAMS 15
+# define OSSL_FUNC_RAND_SET_CTX_PARAMS 16
+# define OSSL_FUNC_RAND_VERIFY_ZEROIZATION 17
+# define OSSL_FUNC_RAND_GET_SEED 18
+# define OSSL_FUNC_RAND_CLEAR_SEED 19
+
+OSSL_CORE_MAKE_FUNC(void *,rand_newctx,
+ (void *provctx, void *parent,
+ const OSSL_DISPATCH *parent_calls))
+OSSL_CORE_MAKE_FUNC(void,rand_freectx, (void *vctx))
+OSSL_CORE_MAKE_FUNC(int,rand_instantiate,
+ (void *vdrbg, unsigned int strength,
+ int prediction_resistance,
+ const unsigned char *pstr, size_t pstr_len,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int,rand_uninstantiate, (void *vdrbg))
+OSSL_CORE_MAKE_FUNC(int,rand_generate,
+ (void *vctx, unsigned char *out, size_t outlen,
+ unsigned int strength, int prediction_resistance,
+ const unsigned char *addin, size_t addin_len))
+OSSL_CORE_MAKE_FUNC(int,rand_reseed,
+ (void *vctx, int prediction_resistance,
+ const unsigned char *ent, size_t ent_len,
+ const unsigned char *addin, size_t addin_len))
+OSSL_CORE_MAKE_FUNC(size_t,rand_nonce,
+ (void *vctx, unsigned char *out, unsigned int strength,
+ size_t min_noncelen, size_t max_noncelen))
+OSSL_CORE_MAKE_FUNC(int,rand_enable_locking, (void *vctx))
+OSSL_CORE_MAKE_FUNC(int,rand_lock, (void *vctx))
+OSSL_CORE_MAKE_FUNC(void,rand_unlock, (void *vctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *,rand_gettable_params, (void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *,rand_gettable_ctx_params,
+ (void *vctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *,rand_settable_ctx_params,
+ (void *vctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int,rand_get_params, (OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int,rand_get_ctx_params,
+ (void *vctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int,rand_set_ctx_params,
+ (void *vctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(void,rand_set_callbacks,
+ (void *vctx, OSSL_INOUT_CALLBACK *get_entropy,
+ OSSL_CALLBACK *cleanup_entropy,
+ OSSL_INOUT_CALLBACK *get_nonce,
+ OSSL_CALLBACK *cleanup_nonce, void *arg))
+OSSL_CORE_MAKE_FUNC(int,rand_verify_zeroization,
+ (void *vctx))
+OSSL_CORE_MAKE_FUNC(size_t,rand_get_seed,
+ (void *vctx, unsigned char **buffer,
+ int entropy, size_t min_len, size_t max_len,
+ int prediction_resistance,
+ const unsigned char *adin, size_t adin_len))
+OSSL_CORE_MAKE_FUNC(void,rand_clear_seed,
+ (void *vctx, unsigned char *buffer, size_t b_len))
+
+/*-
+ * Key management
+ *
+ * The Key Management takes care of provider side key objects, and includes
+ * all current functionality to create them, destroy them, set parameters
+ * and key material, etc, essentially everything that manipulates the keys
+ * themselves and their parameters.
+ *
+ * The key objects are commonly refered to as |keydata|, and it MUST be able
+ * to contain parameters if the key has any, the public key and the private
+ * key. All parts are optional, but their presence determines what can be
+ * done with the key object in terms of encryption, signature, and so on.
+ * The assumption from libcrypto is that the key object contains any of the
+ * following data combinations:
+ *
+ * - parameters only
+ * - public key only
+ * - public key + private key
+ * - parameters + public key
+ * - parameters + public key + private key
+ *
+ * What "parameters", "public key" and "private key" means in detail is left
+ * to the implementation. In the case of DH and DSA, they would typically
+ * include domain parameters, while for certain variants of RSA, they would
+ * typically include PSS or OAEP parameters.
+ *
+ * Key objects are created with OSSL_FUNC_keymgmt_new() and destroyed with
+ * OSSL_FUNC_keymgmt_free(). Key objects can have data filled in with
+ * OSSL_FUNC_keymgmt_import().
+ *
+ * Three functions are made available to check what selection of data is
+ * present in a key object: OSSL_FUNC_keymgmt_has_parameters(),
+ * OSSL_FUNC_keymgmt_has_public_key(), and OSSL_FUNC_keymgmt_has_private_key(),
+ */
+
+/* Key data subset selection - individual bits */
+# define OSSL_KEYMGMT_SELECT_PRIVATE_KEY 0x01
+# define OSSL_KEYMGMT_SELECT_PUBLIC_KEY 0x02
+# define OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS 0x04
+# define OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS 0x80
+
+/* Key data subset selection - combinations */
+# define OSSL_KEYMGMT_SELECT_ALL_PARAMETERS \
+ ( OSSL_KEYMGMT_SELECT_DOMAIN_PARAMETERS \
+ | OSSL_KEYMGMT_SELECT_OTHER_PARAMETERS)
+# define OSSL_KEYMGMT_SELECT_KEYPAIR \
+ ( OSSL_KEYMGMT_SELECT_PRIVATE_KEY | OSSL_KEYMGMT_SELECT_PUBLIC_KEY )
+# define OSSL_KEYMGMT_SELECT_ALL \
+ ( OSSL_KEYMGMT_SELECT_KEYPAIR | OSSL_KEYMGMT_SELECT_ALL_PARAMETERS )
+
+# define OSSL_KEYMGMT_VALIDATE_FULL_CHECK 0
+# define OSSL_KEYMGMT_VALIDATE_QUICK_CHECK 1
+
+/* Basic key object creation */
+# define OSSL_FUNC_KEYMGMT_NEW 1
+OSSL_CORE_MAKE_FUNC(void *, keymgmt_new, (void *provctx))
+
+/* Generation, a more complex constructor */
+# define OSSL_FUNC_KEYMGMT_GEN_INIT 2
+# define OSSL_FUNC_KEYMGMT_GEN_SET_TEMPLATE 3
+# define OSSL_FUNC_KEYMGMT_GEN_SET_PARAMS 4
+# define OSSL_FUNC_KEYMGMT_GEN_SETTABLE_PARAMS 5
+# define OSSL_FUNC_KEYMGMT_GEN 6
+# define OSSL_FUNC_KEYMGMT_GEN_CLEANUP 7
+OSSL_CORE_MAKE_FUNC(void *, keymgmt_gen_init,
+ (void *provctx, int selection, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, keymgmt_gen_set_template,
+ (void *genctx, void *templ))
+OSSL_CORE_MAKE_FUNC(int, keymgmt_gen_set_params,
+ (void *genctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *,
+ keymgmt_gen_settable_params,
+ (void *genctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(void *, keymgmt_gen,
+ (void *genctx, OSSL_CALLBACK *cb, void *cbarg))
+OSSL_CORE_MAKE_FUNC(void, keymgmt_gen_cleanup, (void *genctx))
+
+/* Key loading by object reference */
+# define OSSL_FUNC_KEYMGMT_LOAD 8
+OSSL_CORE_MAKE_FUNC(void *, keymgmt_load,
+ (const void *reference, size_t reference_sz))
+
+/* Basic key object destruction */
+# define OSSL_FUNC_KEYMGMT_FREE 10
+OSSL_CORE_MAKE_FUNC(void, keymgmt_free, (void *keydata))
+
+/* Key object information, with discovery */
+#define OSSL_FUNC_KEYMGMT_GET_PARAMS 11
+#define OSSL_FUNC_KEYMGMT_GETTABLE_PARAMS 12
+OSSL_CORE_MAKE_FUNC(int, keymgmt_get_params,
+ (void *keydata, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, keymgmt_gettable_params,
+ (void *provctx))
+
+#define OSSL_FUNC_KEYMGMT_SET_PARAMS 13
+#define OSSL_FUNC_KEYMGMT_SETTABLE_PARAMS 14
+OSSL_CORE_MAKE_FUNC(int, keymgmt_set_params,
+ (void *keydata, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, keymgmt_settable_params,
+ (void *provctx))
+
+/* Key checks - discovery of supported operations */
+# define OSSL_FUNC_KEYMGMT_QUERY_OPERATION_NAME 20
+OSSL_CORE_MAKE_FUNC(const char *, keymgmt_query_operation_name,
+ (int operation_id))
+
+/* Key checks - key data content checks */
+# define OSSL_FUNC_KEYMGMT_HAS 21
+OSSL_CORE_MAKE_FUNC(int, keymgmt_has, (const void *keydata, int selection))
+
+/* Key checks - validation */
+# define OSSL_FUNC_KEYMGMT_VALIDATE 22
+OSSL_CORE_MAKE_FUNC(int, keymgmt_validate, (const void *keydata, int selection,
+ int checktype))
+
+/* Key checks - matching */
+# define OSSL_FUNC_KEYMGMT_MATCH 23
+OSSL_CORE_MAKE_FUNC(int, keymgmt_match,
+ (const void *keydata1, const void *keydata2,
+ int selection))
+
+/* Import and export functions, with discovery */
+# define OSSL_FUNC_KEYMGMT_IMPORT 40
+# define OSSL_FUNC_KEYMGMT_IMPORT_TYPES 41
+# define OSSL_FUNC_KEYMGMT_EXPORT 42
+# define OSSL_FUNC_KEYMGMT_EXPORT_TYPES 43
+OSSL_CORE_MAKE_FUNC(int, keymgmt_import,
+ (void *keydata, int selection, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, keymgmt_import_types,
+ (int selection))
+OSSL_CORE_MAKE_FUNC(int, keymgmt_export,
+ (void *keydata, int selection,
+ OSSL_CALLBACK *param_cb, void *cbarg))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, keymgmt_export_types,
+ (int selection))
+
+/* Dup function, constructor */
+# define OSSL_FUNC_KEYMGMT_DUP 44
+OSSL_CORE_MAKE_FUNC(void *, keymgmt_dup,
+ (const void *keydata_from, int selection))
+
+/* Key Exchange */
+
+# define OSSL_FUNC_KEYEXCH_NEWCTX 1
+# define OSSL_FUNC_KEYEXCH_INIT 2
+# define OSSL_FUNC_KEYEXCH_DERIVE 3
+# define OSSL_FUNC_KEYEXCH_SET_PEER 4
+# define OSSL_FUNC_KEYEXCH_FREECTX 5
+# define OSSL_FUNC_KEYEXCH_DUPCTX 6
+# define OSSL_FUNC_KEYEXCH_SET_CTX_PARAMS 7
+# define OSSL_FUNC_KEYEXCH_SETTABLE_CTX_PARAMS 8
+# define OSSL_FUNC_KEYEXCH_GET_CTX_PARAMS 9
+# define OSSL_FUNC_KEYEXCH_GETTABLE_CTX_PARAMS 10
+
+OSSL_CORE_MAKE_FUNC(void *, keyexch_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, keyexch_init, (void *ctx, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, keyexch_derive, (void *ctx, unsigned char *secret,
+ size_t *secretlen, size_t outlen))
+OSSL_CORE_MAKE_FUNC(int, keyexch_set_peer, (void *ctx, void *provkey))
+OSSL_CORE_MAKE_FUNC(void, keyexch_freectx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(void *, keyexch_dupctx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(int, keyexch_set_ctx_params, (void *ctx,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, keyexch_settable_ctx_params,
+ (void *ctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int, keyexch_get_ctx_params, (void *ctx,
+ OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, keyexch_gettable_ctx_params,
+ (void *ctx, void *provctx))
+
+/* Signature */
+
+# define OSSL_FUNC_SIGNATURE_NEWCTX 1
+# define OSSL_FUNC_SIGNATURE_SIGN_INIT 2
+# define OSSL_FUNC_SIGNATURE_SIGN 3
+# define OSSL_FUNC_SIGNATURE_VERIFY_INIT 4
+# define OSSL_FUNC_SIGNATURE_VERIFY 5
+# define OSSL_FUNC_SIGNATURE_VERIFY_RECOVER_INIT 6
+# define OSSL_FUNC_SIGNATURE_VERIFY_RECOVER 7
+# define OSSL_FUNC_SIGNATURE_DIGEST_SIGN_INIT 8
+# define OSSL_FUNC_SIGNATURE_DIGEST_SIGN_UPDATE 9
+# define OSSL_FUNC_SIGNATURE_DIGEST_SIGN_FINAL 10
+# define OSSL_FUNC_SIGNATURE_DIGEST_SIGN 11
+# define OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_INIT 12
+# define OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_UPDATE 13
+# define OSSL_FUNC_SIGNATURE_DIGEST_VERIFY_FINAL 14
+# define OSSL_FUNC_SIGNATURE_DIGEST_VERIFY 15
+# define OSSL_FUNC_SIGNATURE_FREECTX 16
+# define OSSL_FUNC_SIGNATURE_DUPCTX 17
+# define OSSL_FUNC_SIGNATURE_GET_CTX_PARAMS 18
+# define OSSL_FUNC_SIGNATURE_GETTABLE_CTX_PARAMS 19
+# define OSSL_FUNC_SIGNATURE_SET_CTX_PARAMS 20
+# define OSSL_FUNC_SIGNATURE_SETTABLE_CTX_PARAMS 21
+# define OSSL_FUNC_SIGNATURE_GET_CTX_MD_PARAMS 22
+# define OSSL_FUNC_SIGNATURE_GETTABLE_CTX_MD_PARAMS 23
+# define OSSL_FUNC_SIGNATURE_SET_CTX_MD_PARAMS 24
+# define OSSL_FUNC_SIGNATURE_SETTABLE_CTX_MD_PARAMS 25
+
+OSSL_CORE_MAKE_FUNC(void *, signature_newctx, (void *provctx,
+ const char *propq))
+OSSL_CORE_MAKE_FUNC(int, signature_sign_init, (void *ctx, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, signature_sign, (void *ctx, unsigned char *sig,
+ size_t *siglen, size_t sigsize,
+ const unsigned char *tbs,
+ size_t tbslen))
+OSSL_CORE_MAKE_FUNC(int, signature_verify_init, (void *ctx, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, signature_verify, (void *ctx,
+ const unsigned char *sig,
+ size_t siglen,
+ const unsigned char *tbs,
+ size_t tbslen))
+OSSL_CORE_MAKE_FUNC(int, signature_verify_recover_init,
+ (void *ctx, void *provkey, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, signature_verify_recover,
+ (void *ctx, unsigned char *rout, size_t *routlen,
+ size_t routsize, const unsigned char *sig, size_t siglen))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_sign_init,
+ (void *ctx, const char *mdname, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_sign_update,
+ (void *ctx, const unsigned char *data, size_t datalen))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_sign_final,
+ (void *ctx, unsigned char *sig, size_t *siglen,
+ size_t sigsize))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_sign,
+ (void *ctx, unsigned char *sigret, size_t *siglen,
+ size_t sigsize, const unsigned char *tbs, size_t tbslen))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_verify_init,
+ (void *ctx, const char *mdname, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_verify_update,
+ (void *ctx, const unsigned char *data, size_t datalen))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_verify_final,
+ (void *ctx, const unsigned char *sig, size_t siglen))
+OSSL_CORE_MAKE_FUNC(int, signature_digest_verify,
+ (void *ctx, const unsigned char *sig, size_t siglen,
+ const unsigned char *tbs, size_t tbslen))
+OSSL_CORE_MAKE_FUNC(void, signature_freectx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(void *, signature_dupctx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(int, signature_get_ctx_params,
+ (void *ctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, signature_gettable_ctx_params,
+ (void *ctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int, signature_set_ctx_params,
+ (void *ctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, signature_settable_ctx_params,
+ (void *ctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int, signature_get_ctx_md_params,
+ (void *ctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, signature_gettable_ctx_md_params,
+ (void *ctx))
+OSSL_CORE_MAKE_FUNC(int, signature_set_ctx_md_params,
+ (void *ctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, signature_settable_ctx_md_params,
+ (void *ctx))
+
+
+/* Asymmetric Ciphers */
+
+# define OSSL_FUNC_ASYM_CIPHER_NEWCTX 1
+# define OSSL_FUNC_ASYM_CIPHER_ENCRYPT_INIT 2
+# define OSSL_FUNC_ASYM_CIPHER_ENCRYPT 3
+# define OSSL_FUNC_ASYM_CIPHER_DECRYPT_INIT 4
+# define OSSL_FUNC_ASYM_CIPHER_DECRYPT 5
+# define OSSL_FUNC_ASYM_CIPHER_FREECTX 6
+# define OSSL_FUNC_ASYM_CIPHER_DUPCTX 7
+# define OSSL_FUNC_ASYM_CIPHER_GET_CTX_PARAMS 8
+# define OSSL_FUNC_ASYM_CIPHER_GETTABLE_CTX_PARAMS 9
+# define OSSL_FUNC_ASYM_CIPHER_SET_CTX_PARAMS 10
+# define OSSL_FUNC_ASYM_CIPHER_SETTABLE_CTX_PARAMS 11
+
+OSSL_CORE_MAKE_FUNC(void *, asym_cipher_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, asym_cipher_encrypt_init, (void *ctx, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, asym_cipher_encrypt, (void *ctx, unsigned char *out,
+ size_t *outlen,
+ size_t outsize,
+ const unsigned char *in,
+ size_t inlen))
+OSSL_CORE_MAKE_FUNC(int, asym_cipher_decrypt_init, (void *ctx, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, asym_cipher_decrypt, (void *ctx, unsigned char *out,
+ size_t *outlen,
+ size_t outsize,
+ const unsigned char *in,
+ size_t inlen))
+OSSL_CORE_MAKE_FUNC(void, asym_cipher_freectx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(void *, asym_cipher_dupctx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(int, asym_cipher_get_ctx_params,
+ (void *ctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, asym_cipher_gettable_ctx_params,
+ (void *ctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int, asym_cipher_set_ctx_params,
+ (void *ctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, asym_cipher_settable_ctx_params,
+ (void *ctx, void *provctx))
+
+/* Asymmetric Key encapsulation */
+# define OSSL_FUNC_KEM_NEWCTX 1
+# define OSSL_FUNC_KEM_ENCAPSULATE_INIT 2
+# define OSSL_FUNC_KEM_ENCAPSULATE 3
+# define OSSL_FUNC_KEM_DECAPSULATE_INIT 4
+# define OSSL_FUNC_KEM_DECAPSULATE 5
+# define OSSL_FUNC_KEM_FREECTX 6
+# define OSSL_FUNC_KEM_DUPCTX 7
+# define OSSL_FUNC_KEM_GET_CTX_PARAMS 8
+# define OSSL_FUNC_KEM_GETTABLE_CTX_PARAMS 9
+# define OSSL_FUNC_KEM_SET_CTX_PARAMS 10
+# define OSSL_FUNC_KEM_SETTABLE_CTX_PARAMS 11
+
+OSSL_CORE_MAKE_FUNC(void *, kem_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, kem_encapsulate_init, (void *ctx, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, kem_encapsulate, (void *ctx,
+ unsigned char *out, size_t *outlen,
+ unsigned char *secret,
+ size_t *secretlen))
+OSSL_CORE_MAKE_FUNC(int, kem_decapsulate_init, (void *ctx, void *provkey,
+ const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, kem_decapsulate, (void *ctx,
+ unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen))
+OSSL_CORE_MAKE_FUNC(void, kem_freectx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(void *, kem_dupctx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(int, kem_get_ctx_params, (void *ctx, OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, kem_gettable_ctx_params,
+ (void *ctx, void *provctx))
+OSSL_CORE_MAKE_FUNC(int, kem_set_ctx_params,
+ (void *ctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, kem_settable_ctx_params,
+ (void *ctx, void *provctx))
+
+/* Encoders and decoders */
+# define OSSL_FUNC_ENCODER_NEWCTX 1
+# define OSSL_FUNC_ENCODER_FREECTX 2
+# define OSSL_FUNC_ENCODER_GET_PARAMS 3
+# define OSSL_FUNC_ENCODER_GETTABLE_PARAMS 4
+# define OSSL_FUNC_ENCODER_SET_CTX_PARAMS 5
+# define OSSL_FUNC_ENCODER_SETTABLE_CTX_PARAMS 6
+# define OSSL_FUNC_ENCODER_DOES_SELECTION 10
+# define OSSL_FUNC_ENCODER_ENCODE 11
+# define OSSL_FUNC_ENCODER_IMPORT_OBJECT 20
+# define OSSL_FUNC_ENCODER_FREE_OBJECT 21
+OSSL_CORE_MAKE_FUNC(void *, encoder_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(void, encoder_freectx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(int, encoder_get_params, (OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, encoder_gettable_params,
+ (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, encoder_set_ctx_params,
+ (void *ctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, encoder_settable_ctx_params,
+ (void *provctx))
+
+OSSL_CORE_MAKE_FUNC(int, encoder_does_selection,
+ (void *provctx, int selection))
+OSSL_CORE_MAKE_FUNC(int, encoder_encode,
+ (void *ctx, OSSL_CORE_BIO *out,
+ const void *obj_raw, const OSSL_PARAM obj_abstract[],
+ int selection,
+ OSSL_PASSPHRASE_CALLBACK *cb, void *cbarg))
+
+OSSL_CORE_MAKE_FUNC(void *, encoder_import_object,
+ (void *ctx, int selection, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(void, encoder_free_object, (void *obj))
+
+# define OSSL_FUNC_DECODER_NEWCTX 1
+# define OSSL_FUNC_DECODER_FREECTX 2
+# define OSSL_FUNC_DECODER_GET_PARAMS 3
+# define OSSL_FUNC_DECODER_GETTABLE_PARAMS 4
+# define OSSL_FUNC_DECODER_SET_CTX_PARAMS 5
+# define OSSL_FUNC_DECODER_SETTABLE_CTX_PARAMS 6
+# define OSSL_FUNC_DECODER_DOES_SELECTION 10
+# define OSSL_FUNC_DECODER_DECODE 11
+# define OSSL_FUNC_DECODER_EXPORT_OBJECT 20
+OSSL_CORE_MAKE_FUNC(void *, decoder_newctx, (void *provctx))
+OSSL_CORE_MAKE_FUNC(void, decoder_freectx, (void *ctx))
+OSSL_CORE_MAKE_FUNC(int, decoder_get_params, (OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, decoder_gettable_params,
+ (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, decoder_set_ctx_params,
+ (void *ctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, decoder_settable_ctx_params,
+ (void *provctx))
+
+OSSL_CORE_MAKE_FUNC(int, decoder_does_selection,
+ (void *provctx, int selection))
+OSSL_CORE_MAKE_FUNC(int, decoder_decode,
+ (void *ctx, OSSL_CORE_BIO *in, int selection,
+ OSSL_CALLBACK *data_cb, void *data_cbarg,
+ OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg))
+OSSL_CORE_MAKE_FUNC(int, decoder_export_object,
+ (void *ctx, const void *objref, size_t objref_sz,
+ OSSL_CALLBACK *export_cb, void *export_cbarg))
+
+/*-
+ * Store
+ *
+ * Objects are scanned by using the 'open', 'load', 'eof' and 'close'
+ * functions, which implement an OSSL_STORE loader.
+ *
+ * store_load() works in a way that's very similar to the decoders, in
+ * that they pass an abstract object through a callback, either as a DER
+ * octet string or as an object reference, which libcrypto will have to
+ * deal with.
+ */
+
+#define OSSL_FUNC_STORE_OPEN 1
+#define OSSL_FUNC_STORE_ATTACH 2
+#define OSSL_FUNC_STORE_SETTABLE_CTX_PARAMS 3
+#define OSSL_FUNC_STORE_SET_CTX_PARAMS 4
+#define OSSL_FUNC_STORE_LOAD 5
+#define OSSL_FUNC_STORE_EOF 6
+#define OSSL_FUNC_STORE_CLOSE 7
+#define OSSL_FUNC_STORE_EXPORT_OBJECT 8
+OSSL_CORE_MAKE_FUNC(void *, store_open, (void *provctx, const char *uri))
+OSSL_CORE_MAKE_FUNC(void *, store_attach, (void *provctx, OSSL_CORE_BIO *in))
+OSSL_CORE_MAKE_FUNC(const OSSL_PARAM *, store_settable_ctx_params,
+ (void *provctx))
+OSSL_CORE_MAKE_FUNC(int, store_set_ctx_params,
+ (void *loaderctx, const OSSL_PARAM params[]))
+OSSL_CORE_MAKE_FUNC(int, store_load,
+ (void *loaderctx,
+ OSSL_CALLBACK *object_cb, void *object_cbarg,
+ OSSL_PASSPHRASE_CALLBACK *pw_cb, void *pw_cbarg))
+OSSL_CORE_MAKE_FUNC(int, store_eof, (void *loaderctx))
+OSSL_CORE_MAKE_FUNC(int, store_close, (void *loaderctx))
+OSSL_CORE_MAKE_FUNC(int, store_export_object,
+ (void *loaderctx, const void *objref, size_t objref_sz,
+ OSSL_CALLBACK *export_cb, void *export_cbarg))
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/core_names.h b/include/openssl/core_names.h
new file mode 100644
index 00000000..b549dae9
--- /dev/null
+++ b/include/openssl/core_names.h
@@ -0,0 +1,556 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CORE_NAMES_H
+# define OPENSSL_CORE_NAMES_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* Well known parameter names that core passes to providers */
+#define OSSL_PROV_PARAM_CORE_VERSION "openssl-version" /* utf8_ptr */
+#define OSSL_PROV_PARAM_CORE_PROV_NAME "provider-name" /* utf8_ptr */
+#define OSSL_PROV_PARAM_CORE_MODULE_FILENAME "module-filename" /* utf8_ptr */
+
+/* Well known parameter names that Providers can define */
+#define OSSL_PROV_PARAM_NAME "name" /* utf8_string */
+#define OSSL_PROV_PARAM_VERSION "version" /* utf8_string */
+#define OSSL_PROV_PARAM_BUILDINFO "buildinfo" /* utf8_string */
+#define OSSL_PROV_PARAM_STATUS "status" /* uint */
+#define OSSL_PROV_PARAM_SECURITY_CHECKS "security-checks" /* uint */
+
+/* Self test callback parameters */
+#define OSSL_PROV_PARAM_SELF_TEST_PHASE "st-phase" /* utf8_string */
+#define OSSL_PROV_PARAM_SELF_TEST_TYPE "st-type" /* utf8_string */
+#define OSSL_PROV_PARAM_SELF_TEST_DESC "st-desc" /* utf8_string */
+
+/*-
+ * Provider-native object abstractions
+ *
+ * These are used when a provider wants to pass object data or an object
+ * reference back to libcrypto. This is only useful for provider functions
+ * that take a callback to which an OSSL_PARAM array with these parameters
+ * can be passed.
+ *
+ * This set of parameter names is explained in detail in provider-object(7)
+ * (doc/man7/provider-object.pod)
+ */
+#define OSSL_OBJECT_PARAM_TYPE "type" /* INTEGER */
+#define OSSL_OBJECT_PARAM_DATA_TYPE "data-type" /* UTF8_STRING */
+#define OSSL_OBJECT_PARAM_DATA_STRUCTURE "data-structure" /* UTF8_STRING */
+#define OSSL_OBJECT_PARAM_REFERENCE "reference" /* OCTET_STRING */
+#define OSSL_OBJECT_PARAM_DATA "data" /* OCTET_STRING or UTF8_STRING */
+#define OSSL_OBJECT_PARAM_DESC "desc" /* UTF8_STRING */
+
+/*
+ * Algorithm parameters
+ * If "engine" or "properties" are specified, they should always be paired
+ * with the algorithm type.
+ * Note these are common names that are shared by many types (such as kdf, mac,
+ * and pkey) e.g: see OSSL_MAC_PARAM_DIGEST below.
+ */
+#define OSSL_ALG_PARAM_DIGEST "digest" /* utf8_string */
+#define OSSL_ALG_PARAM_CIPHER "cipher" /* utf8_string */
+#define OSSL_ALG_PARAM_ENGINE "engine" /* utf8_string */
+#define OSSL_ALG_PARAM_MAC "mac" /* utf8_string */
+#define OSSL_ALG_PARAM_PROPERTIES "properties"/* utf8_string */
+
+/* cipher parameters */
+#define OSSL_CIPHER_PARAM_PADDING "padding" /* uint */
+#define OSSL_CIPHER_PARAM_USE_BITS "use-bits" /* uint */
+#define OSSL_CIPHER_PARAM_TLS_VERSION "tls-version" /* uint */
+#define OSSL_CIPHER_PARAM_TLS_MAC "tls-mac" /* octet_ptr */
+#define OSSL_CIPHER_PARAM_TLS_MAC_SIZE "tls-mac-size" /* size_t */
+#define OSSL_CIPHER_PARAM_MODE "mode" /* uint */
+#define OSSL_CIPHER_PARAM_BLOCK_SIZE "blocksize" /* size_t */
+#define OSSL_CIPHER_PARAM_AEAD "aead" /* int, 0 or 1 */
+#define OSSL_CIPHER_PARAM_CUSTOM_IV "custom-iv" /* int, 0 or 1 */
+#define OSSL_CIPHER_PARAM_CTS "cts" /* int, 0 or 1 */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK "tls-multi" /* int, 0 or 1 */
+#define OSSL_CIPHER_PARAM_HAS_RAND_KEY "has-randkey" /* int, 0 or 1 */
+#define OSSL_CIPHER_PARAM_KEYLEN "keylen" /* size_t */
+#define OSSL_CIPHER_PARAM_IVLEN "ivlen" /* size_t */
+#define OSSL_CIPHER_PARAM_IV "iv" /* octet_string OR octet_ptr */
+#define OSSL_CIPHER_PARAM_UPDATED_IV "updated-iv" /* octet_string OR octet_ptr */
+#define OSSL_CIPHER_PARAM_NUM "num" /* uint */
+#define OSSL_CIPHER_PARAM_ROUNDS "rounds" /* uint */
+#define OSSL_CIPHER_PARAM_AEAD_TAG "tag" /* octet_string */
+#define OSSL_CIPHER_PARAM_AEAD_TLS1_AAD "tlsaad" /* octet_string */
+#define OSSL_CIPHER_PARAM_AEAD_TLS1_AAD_PAD "tlsaadpad" /* size_t */
+#define OSSL_CIPHER_PARAM_AEAD_TLS1_IV_FIXED "tlsivfixed" /* octet_string */
+#define OSSL_CIPHER_PARAM_AEAD_TLS1_GET_IV_GEN "tlsivgen" /* octet_string */
+#define OSSL_CIPHER_PARAM_AEAD_TLS1_SET_IV_INV "tlsivinv" /* octet_string */
+#define OSSL_CIPHER_PARAM_AEAD_IVLEN OSSL_CIPHER_PARAM_IVLEN
+#define OSSL_CIPHER_PARAM_AEAD_TAGLEN "taglen" /* size_t */
+#define OSSL_CIPHER_PARAM_AEAD_MAC_KEY "mackey" /* octet_string */
+#define OSSL_CIPHER_PARAM_RANDOM_KEY "randkey" /* octet_string */
+#define OSSL_CIPHER_PARAM_RC2_KEYBITS "keybits" /* size_t */
+#define OSSL_CIPHER_PARAM_SPEED "speed" /* uint */
+#define OSSL_CIPHER_PARAM_CTS_MODE "cts_mode" /* utf8_string */
+/* For passing the AlgorithmIdentifier parameter in DER form */
+#define OSSL_CIPHER_PARAM_ALGORITHM_ID_PARAMS "alg_id_param" /* octet_string */
+
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_SEND_FRAGMENT \
+ "tls1multi_maxsndfrag" /* uint */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_MAX_BUFSIZE \
+ "tls1multi_maxbufsz" /* size_t */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_INTERLEAVE \
+ "tls1multi_interleave" /* uint */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD \
+ "tls1multi_aad" /* octet_string */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_AAD_PACKLEN \
+ "tls1multi_aadpacklen" /* uint */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC \
+ "tls1multi_enc" /* octet_string */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_IN \
+ "tls1multi_encin" /* octet_string */
+#define OSSL_CIPHER_PARAM_TLS1_MULTIBLOCK_ENC_LEN \
+ "tls1multi_enclen" /* size_t */
+
+/* OSSL_CIPHER_PARAM_CTS_MODE Values */
+#define OSSL_CIPHER_CTS_MODE_CS1 "CS1"
+#define OSSL_CIPHER_CTS_MODE_CS2 "CS2"
+#define OSSL_CIPHER_CTS_MODE_CS3 "CS3"
+
+/* digest parameters */
+#define OSSL_DIGEST_PARAM_XOFLEN "xoflen" /* size_t */
+#define OSSL_DIGEST_PARAM_SSL3_MS "ssl3-ms" /* octet string */
+#define OSSL_DIGEST_PARAM_PAD_TYPE "pad-type" /* uint */
+#define OSSL_DIGEST_PARAM_MICALG "micalg" /* utf8 string */
+#define OSSL_DIGEST_PARAM_BLOCK_SIZE "blocksize" /* size_t */
+#define OSSL_DIGEST_PARAM_SIZE "size" /* size_t */
+#define OSSL_DIGEST_PARAM_XOF "xof" /* int, 0 or 1 */
+#define OSSL_DIGEST_PARAM_ALGID_ABSENT "algid-absent" /* int, 0 or 1 */
+
+/* Known DIGEST names (not a complete list) */
+#define OSSL_DIGEST_NAME_MD5 "MD5"
+#define OSSL_DIGEST_NAME_MD5_SHA1 "MD5-SHA1"
+#define OSSL_DIGEST_NAME_SHA1 "SHA1"
+#define OSSL_DIGEST_NAME_SHA2_224 "SHA2-224"
+#define OSSL_DIGEST_NAME_SHA2_256 "SHA2-256"
+#define OSSL_DIGEST_NAME_SHA2_384 "SHA2-384"
+#define OSSL_DIGEST_NAME_SHA2_512 "SHA2-512"
+#define OSSL_DIGEST_NAME_SHA2_512_224 "SHA2-512/224"
+#define OSSL_DIGEST_NAME_SHA2_512_256 "SHA2-512/256"
+#define OSSL_DIGEST_NAME_MD2 "MD2"
+#define OSSL_DIGEST_NAME_MD4 "MD4"
+#define OSSL_DIGEST_NAME_MDC2 "MDC2"
+#define OSSL_DIGEST_NAME_RIPEMD160 "RIPEMD160"
+#define OSSL_DIGEST_NAME_SHA3_224 "SHA3-224"
+#define OSSL_DIGEST_NAME_SHA3_256 "SHA3-256"
+#define OSSL_DIGEST_NAME_SHA3_384 "SHA3-384"
+#define OSSL_DIGEST_NAME_SHA3_512 "SHA3-512"
+#define OSSL_DIGEST_NAME_KECCAK_KMAC128 "KECCAK-KMAC-128"
+#define OSSL_DIGEST_NAME_KECCAK_KMAC256 "KECCAK-KMAC-256"
+#define OSSL_DIGEST_NAME_SM3 "SM3"
+
+/* MAC parameters */
+#define OSSL_MAC_PARAM_KEY "key" /* octet string */
+#define OSSL_MAC_PARAM_IV "iv" /* octet string */
+#define OSSL_MAC_PARAM_CUSTOM "custom" /* utf8 string */
+#define OSSL_MAC_PARAM_SALT "salt" /* octet string */
+#define OSSL_MAC_PARAM_XOF "xof" /* int, 0 or 1 */
+#define OSSL_MAC_PARAM_DIGEST_NOINIT "digest-noinit" /* int, 0 or 1 */
+#define OSSL_MAC_PARAM_DIGEST_ONESHOT "digest-oneshot" /* int, 0 or 1 */
+#define OSSL_MAC_PARAM_C_ROUNDS "c-rounds" /* unsigned int */
+#define OSSL_MAC_PARAM_D_ROUNDS "d-rounds" /* unsigned int */
+
+/*
+ * If "engine" or "properties" are specified, they should always be paired
+ * with "cipher" or "digest".
+ */
+#define OSSL_MAC_PARAM_CIPHER OSSL_ALG_PARAM_CIPHER /* utf8 string */
+#define OSSL_MAC_PARAM_DIGEST OSSL_ALG_PARAM_DIGEST /* utf8 string */
+#define OSSL_MAC_PARAM_PROPERTIES OSSL_ALG_PARAM_PROPERTIES /* utf8 string */
+#define OSSL_MAC_PARAM_SIZE "size" /* size_t */
+#define OSSL_MAC_PARAM_BLOCK_SIZE "block-size" /* size_t */
+#define OSSL_MAC_PARAM_TLS_DATA_SIZE "tls-data-size" /* size_t */
+
+/* Known MAC names */
+#define OSSL_MAC_NAME_BLAKE2BMAC "BLAKE2BMAC"
+#define OSSL_MAC_NAME_BLAKE2SMAC "BLAKE2SMAC"
+#define OSSL_MAC_NAME_CMAC "CMAC"
+#define OSSL_MAC_NAME_GMAC "GMAC"
+#define OSSL_MAC_NAME_HMAC "HMAC"
+#define OSSL_MAC_NAME_KMAC128 "KMAC128"
+#define OSSL_MAC_NAME_KMAC256 "KMAC256"
+#define OSSL_MAC_NAME_POLY1305 "POLY1305"
+#define OSSL_MAC_NAME_SIPHASH "SIPHASH"
+
+/* KDF / PRF parameters */
+#define OSSL_KDF_PARAM_SECRET "secret" /* octet string */
+#define OSSL_KDF_PARAM_KEY "key" /* octet string */
+#define OSSL_KDF_PARAM_SALT "salt" /* octet string */
+#define OSSL_KDF_PARAM_PASSWORD "pass" /* octet string */
+#define OSSL_KDF_PARAM_PREFIX "prefix" /* octet string */
+#define OSSL_KDF_PARAM_LABEL "label" /* octet string */
+#define OSSL_KDF_PARAM_DATA "data" /* octet string */
+#define OSSL_KDF_PARAM_DIGEST OSSL_ALG_PARAM_DIGEST /* utf8 string */
+#define OSSL_KDF_PARAM_CIPHER OSSL_ALG_PARAM_CIPHER /* utf8 string */
+#define OSSL_KDF_PARAM_MAC OSSL_ALG_PARAM_MAC /* utf8 string */
+#define OSSL_KDF_PARAM_MAC_SIZE "maclen" /* size_t */
+#define OSSL_KDF_PARAM_PROPERTIES OSSL_ALG_PARAM_PROPERTIES /* utf8 string */
+#define OSSL_KDF_PARAM_ITER "iter" /* unsigned int */
+#define OSSL_KDF_PARAM_MODE "mode" /* utf8 string or int */
+#define OSSL_KDF_PARAM_PKCS5 "pkcs5" /* int */
+#define OSSL_KDF_PARAM_UKM "ukm" /* octet string */
+#define OSSL_KDF_PARAM_CEK_ALG "cekalg" /* utf8 string */
+#define OSSL_KDF_PARAM_SCRYPT_N "n" /* uint64_t */
+#define OSSL_KDF_PARAM_SCRYPT_R "r" /* uint32_t */
+#define OSSL_KDF_PARAM_SCRYPT_P "p" /* uint32_t */
+#define OSSL_KDF_PARAM_SCRYPT_MAXMEM "maxmem_bytes" /* uint64_t */
+#define OSSL_KDF_PARAM_INFO "info" /* octet string */
+#define OSSL_KDF_PARAM_SEED "seed" /* octet string */
+#define OSSL_KDF_PARAM_SSHKDF_XCGHASH "xcghash" /* octet string */
+#define OSSL_KDF_PARAM_SSHKDF_SESSION_ID "session_id" /* octet string */
+#define OSSL_KDF_PARAM_SSHKDF_TYPE "type" /* int */
+#define OSSL_KDF_PARAM_SIZE "size" /* size_t */
+#define OSSL_KDF_PARAM_CONSTANT "constant" /* octet string */
+#define OSSL_KDF_PARAM_PKCS12_ID "id" /* int */
+#define OSSL_KDF_PARAM_KBKDF_USE_L "use-l" /* int */
+#define OSSL_KDF_PARAM_KBKDF_USE_SEPARATOR "use-separator" /* int */
+#define OSSL_KDF_PARAM_X942_ACVPINFO "acvp-info"
+#define OSSL_KDF_PARAM_X942_PARTYUINFO "partyu-info"
+#define OSSL_KDF_PARAM_X942_PARTYVINFO "partyv-info"
+#define OSSL_KDF_PARAM_X942_SUPP_PUBINFO "supp-pubinfo"
+#define OSSL_KDF_PARAM_X942_SUPP_PRIVINFO "supp-privinfo"
+#define OSSL_KDF_PARAM_X942_USE_KEYBITS "use-keybits"
+
+/* Known KDF names */
+#define OSSL_KDF_NAME_HKDF "HKDF"
+#define OSSL_KDF_NAME_TLS1_3_KDF "TLS13-KDF"
+#define OSSL_KDF_NAME_PBKDF1 "PBKDF1"
+#define OSSL_KDF_NAME_PBKDF2 "PBKDF2"
+#define OSSL_KDF_NAME_SCRYPT "SCRYPT"
+#define OSSL_KDF_NAME_SSHKDF "SSHKDF"
+#define OSSL_KDF_NAME_SSKDF "SSKDF"
+#define OSSL_KDF_NAME_TLS1_PRF "TLS1-PRF"
+#define OSSL_KDF_NAME_X942KDF_ASN1 "X942KDF-ASN1"
+#define OSSL_KDF_NAME_X942KDF_CONCAT "X942KDF-CONCAT"
+#define OSSL_KDF_NAME_X963KDF "X963KDF"
+#define OSSL_KDF_NAME_KBKDF "KBKDF"
+#define OSSL_KDF_NAME_KRB5KDF "KRB5KDF"
+
+/* Known RAND names */
+#define OSSL_RAND_PARAM_STATE "state"
+#define OSSL_RAND_PARAM_STRENGTH "strength"
+#define OSSL_RAND_PARAM_MAX_REQUEST "max_request"
+#define OSSL_RAND_PARAM_TEST_ENTROPY "test_entropy"
+#define OSSL_RAND_PARAM_TEST_NONCE "test_nonce"
+
+/* RAND/DRBG names */
+#define OSSL_DRBG_PARAM_RESEED_REQUESTS "reseed_requests"
+#define OSSL_DRBG_PARAM_RESEED_TIME_INTERVAL "reseed_time_interval"
+#define OSSL_DRBG_PARAM_MIN_ENTROPYLEN "min_entropylen"
+#define OSSL_DRBG_PARAM_MAX_ENTROPYLEN "max_entropylen"
+#define OSSL_DRBG_PARAM_MIN_NONCELEN "min_noncelen"
+#define OSSL_DRBG_PARAM_MAX_NONCELEN "max_noncelen"
+#define OSSL_DRBG_PARAM_MAX_PERSLEN "max_perslen"
+#define OSSL_DRBG_PARAM_MAX_ADINLEN "max_adinlen"
+#define OSSL_DRBG_PARAM_RESEED_COUNTER "reseed_counter"
+#define OSSL_DRBG_PARAM_RESEED_TIME "reseed_time"
+#define OSSL_DRBG_PARAM_PROPERTIES OSSL_ALG_PARAM_PROPERTIES
+#define OSSL_DRBG_PARAM_DIGEST OSSL_ALG_PARAM_DIGEST
+#define OSSL_DRBG_PARAM_CIPHER OSSL_ALG_PARAM_CIPHER
+#define OSSL_DRBG_PARAM_MAC OSSL_ALG_PARAM_MAC
+#define OSSL_DRBG_PARAM_USE_DF "use_derivation_function"
+
+/* DRBG call back parameters */
+#define OSSL_DRBG_PARAM_ENTROPY_REQUIRED "entropy_required"
+#define OSSL_DRBG_PARAM_PREDICTION_RESISTANCE "prediction_resistance"
+#define OSSL_DRBG_PARAM_MIN_LENGTH "minium_length"
+#define OSSL_DRBG_PARAM_MAX_LENGTH "maxium_length"
+#define OSSL_DRBG_PARAM_RANDOM_DATA "random_data"
+#define OSSL_DRBG_PARAM_SIZE "size"
+
+/* PKEY parameters */
+/* Common PKEY parameters */
+#define OSSL_PKEY_PARAM_BITS "bits" /* integer */
+#define OSSL_PKEY_PARAM_MAX_SIZE "max-size" /* integer */
+#define OSSL_PKEY_PARAM_SECURITY_BITS "security-bits" /* integer */
+#define OSSL_PKEY_PARAM_DIGEST OSSL_ALG_PARAM_DIGEST
+#define OSSL_PKEY_PARAM_CIPHER OSSL_ALG_PARAM_CIPHER /* utf8 string */
+#define OSSL_PKEY_PARAM_ENGINE OSSL_ALG_PARAM_ENGINE /* utf8 string */
+#define OSSL_PKEY_PARAM_PROPERTIES OSSL_ALG_PARAM_PROPERTIES
+#define OSSL_PKEY_PARAM_DEFAULT_DIGEST "default-digest" /* utf8 string */
+#define OSSL_PKEY_PARAM_MANDATORY_DIGEST "mandatory-digest" /* utf8 string */
+#define OSSL_PKEY_PARAM_PAD_MODE "pad-mode"
+#define OSSL_PKEY_PARAM_DIGEST_SIZE "digest-size"
+#define OSSL_PKEY_PARAM_MASKGENFUNC "mgf"
+#define OSSL_PKEY_PARAM_MGF1_DIGEST "mgf1-digest"
+#define OSSL_PKEY_PARAM_MGF1_PROPERTIES "mgf1-properties"
+#define OSSL_PKEY_PARAM_ENCODED_PUBLIC_KEY "encoded-pub-key"
+#define OSSL_PKEY_PARAM_GROUP_NAME "group"
+#define OSSL_PKEY_PARAM_DIST_ID "distid"
+#define OSSL_PKEY_PARAM_PUB_KEY "pub"
+#define OSSL_PKEY_PARAM_PRIV_KEY "priv"
+
+/* Diffie-Hellman/DSA Parameters */
+#define OSSL_PKEY_PARAM_FFC_P "p"
+#define OSSL_PKEY_PARAM_FFC_G "g"
+#define OSSL_PKEY_PARAM_FFC_Q "q"
+#define OSSL_PKEY_PARAM_FFC_GINDEX "gindex"
+#define OSSL_PKEY_PARAM_FFC_PCOUNTER "pcounter"
+#define OSSL_PKEY_PARAM_FFC_SEED "seed"
+#define OSSL_PKEY_PARAM_FFC_COFACTOR "j"
+#define OSSL_PKEY_PARAM_FFC_H "hindex"
+#define OSSL_PKEY_PARAM_FFC_VALIDATE_PQ "validate-pq"
+#define OSSL_PKEY_PARAM_FFC_VALIDATE_G "validate-g"
+#define OSSL_PKEY_PARAM_FFC_VALIDATE_LEGACY "validate-legacy"
+
+/* Diffie-Hellman params */
+#define OSSL_PKEY_PARAM_DH_GENERATOR "safeprime-generator"
+#define OSSL_PKEY_PARAM_DH_PRIV_LEN "priv_len"
+
+/* Elliptic Curve Domain Parameters */
+#define OSSL_PKEY_PARAM_EC_PUB_X "qx"
+#define OSSL_PKEY_PARAM_EC_PUB_Y "qy"
+
+/* Elliptic Curve Explicit Domain Parameters */
+#define OSSL_PKEY_PARAM_EC_FIELD_TYPE "field-type"
+#define OSSL_PKEY_PARAM_EC_P "p"
+#define OSSL_PKEY_PARAM_EC_A "a"
+#define OSSL_PKEY_PARAM_EC_B "b"
+#define OSSL_PKEY_PARAM_EC_GENERATOR "generator"
+#define OSSL_PKEY_PARAM_EC_ORDER "order"
+#define OSSL_PKEY_PARAM_EC_COFACTOR "cofactor"
+#define OSSL_PKEY_PARAM_EC_SEED "seed"
+#define OSSL_PKEY_PARAM_EC_CHAR2_M "m"
+#define OSSL_PKEY_PARAM_EC_CHAR2_TYPE "basis-type"
+#define OSSL_PKEY_PARAM_EC_CHAR2_TP_BASIS "tp"
+#define OSSL_PKEY_PARAM_EC_CHAR2_PP_K1 "k1"
+#define OSSL_PKEY_PARAM_EC_CHAR2_PP_K2 "k2"
+#define OSSL_PKEY_PARAM_EC_CHAR2_PP_K3 "k3"
+#define OSSL_PKEY_PARAM_EC_DECODED_FROM_EXPLICIT_PARAMS "decoded-from-explicit"
+
+/* Elliptic Curve Key Parameters */
+#define OSSL_PKEY_PARAM_USE_COFACTOR_FLAG "use-cofactor-flag"
+#define OSSL_PKEY_PARAM_USE_COFACTOR_ECDH \
+ OSSL_PKEY_PARAM_USE_COFACTOR_FLAG
+
+/* RSA Keys */
+/*
+ * n, e, d are the usual public and private key components
+ *
+ * rsa-num is the number of factors, including p and q
+ * rsa-factor is used for each factor: p, q, r_i (i = 3, ...)
+ * rsa-exponent is used for each exponent: dP, dQ, d_i (i = 3, ...)
+ * rsa-coefficient is used for each coefficient: qInv, t_i (i = 3, ...)
+ *
+ * The number of rsa-factor items must be equal to the number of rsa-exponent
+ * items, and the number of rsa-coefficients must be one less.
+ * (the base i for the coefficients is 2, not 1, at least as implied by
+ * RFC 8017)
+ */
+#define OSSL_PKEY_PARAM_RSA_N "n"
+#define OSSL_PKEY_PARAM_RSA_E "e"
+#define OSSL_PKEY_PARAM_RSA_D "d"
+#define OSSL_PKEY_PARAM_RSA_FACTOR "rsa-factor"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT "rsa-exponent"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT "rsa-coefficient"
+#define OSSL_PKEY_PARAM_RSA_FACTOR1 OSSL_PKEY_PARAM_RSA_FACTOR"1"
+#define OSSL_PKEY_PARAM_RSA_FACTOR2 OSSL_PKEY_PARAM_RSA_FACTOR"2"
+#define OSSL_PKEY_PARAM_RSA_FACTOR3 OSSL_PKEY_PARAM_RSA_FACTOR"3"
+#define OSSL_PKEY_PARAM_RSA_FACTOR4 OSSL_PKEY_PARAM_RSA_FACTOR"4"
+#define OSSL_PKEY_PARAM_RSA_FACTOR5 OSSL_PKEY_PARAM_RSA_FACTOR"5"
+#define OSSL_PKEY_PARAM_RSA_FACTOR6 OSSL_PKEY_PARAM_RSA_FACTOR"6"
+#define OSSL_PKEY_PARAM_RSA_FACTOR7 OSSL_PKEY_PARAM_RSA_FACTOR"7"
+#define OSSL_PKEY_PARAM_RSA_FACTOR8 OSSL_PKEY_PARAM_RSA_FACTOR"8"
+#define OSSL_PKEY_PARAM_RSA_FACTOR9 OSSL_PKEY_PARAM_RSA_FACTOR"9"
+#define OSSL_PKEY_PARAM_RSA_FACTOR10 OSSL_PKEY_PARAM_RSA_FACTOR"10"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT1 OSSL_PKEY_PARAM_RSA_EXPONENT"1"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT2 OSSL_PKEY_PARAM_RSA_EXPONENT"2"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT3 OSSL_PKEY_PARAM_RSA_EXPONENT"3"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT4 OSSL_PKEY_PARAM_RSA_EXPONENT"4"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT5 OSSL_PKEY_PARAM_RSA_EXPONENT"5"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT6 OSSL_PKEY_PARAM_RSA_EXPONENT"6"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT7 OSSL_PKEY_PARAM_RSA_EXPONENT"7"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT8 OSSL_PKEY_PARAM_RSA_EXPONENT"8"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT9 OSSL_PKEY_PARAM_RSA_EXPONENT"9"
+#define OSSL_PKEY_PARAM_RSA_EXPONENT10 OSSL_PKEY_PARAM_RSA_EXPONENT"10"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT1 OSSL_PKEY_PARAM_RSA_COEFFICIENT"1"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT2 OSSL_PKEY_PARAM_RSA_COEFFICIENT"2"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT3 OSSL_PKEY_PARAM_RSA_COEFFICIENT"3"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT4 OSSL_PKEY_PARAM_RSA_COEFFICIENT"4"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT5 OSSL_PKEY_PARAM_RSA_COEFFICIENT"5"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT6 OSSL_PKEY_PARAM_RSA_COEFFICIENT"6"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT7 OSSL_PKEY_PARAM_RSA_COEFFICIENT"7"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT8 OSSL_PKEY_PARAM_RSA_COEFFICIENT"8"
+#define OSSL_PKEY_PARAM_RSA_COEFFICIENT9 OSSL_PKEY_PARAM_RSA_COEFFICIENT"9"
+
+/* RSA padding modes */
+#define OSSL_PKEY_RSA_PAD_MODE_NONE "none"
+#define OSSL_PKEY_RSA_PAD_MODE_PKCSV15 "pkcs1"
+#define OSSL_PKEY_RSA_PAD_MODE_OAEP "oaep"
+#define OSSL_PKEY_RSA_PAD_MODE_X931 "x931"
+#define OSSL_PKEY_RSA_PAD_MODE_PSS "pss"
+
+/* RSA pss padding salt length */
+#define OSSL_PKEY_RSA_PSS_SALT_LEN_DIGEST "digest"
+#define OSSL_PKEY_RSA_PSS_SALT_LEN_MAX "max"
+#define OSSL_PKEY_RSA_PSS_SALT_LEN_AUTO "auto"
+
+/* Key generation parameters */
+#define OSSL_PKEY_PARAM_RSA_BITS OSSL_PKEY_PARAM_BITS
+#define OSSL_PKEY_PARAM_RSA_PRIMES "primes"
+#define OSSL_PKEY_PARAM_RSA_DIGEST OSSL_PKEY_PARAM_DIGEST
+#define OSSL_PKEY_PARAM_RSA_DIGEST_PROPS OSSL_PKEY_PARAM_PROPERTIES
+#define OSSL_PKEY_PARAM_RSA_MASKGENFUNC OSSL_PKEY_PARAM_MASKGENFUNC
+#define OSSL_PKEY_PARAM_RSA_MGF1_DIGEST OSSL_PKEY_PARAM_MGF1_DIGEST
+#define OSSL_PKEY_PARAM_RSA_PSS_SALTLEN "saltlen"
+
+/* Key generation parameters */
+#define OSSL_PKEY_PARAM_FFC_TYPE "type"
+#define OSSL_PKEY_PARAM_FFC_PBITS "pbits"
+#define OSSL_PKEY_PARAM_FFC_QBITS "qbits"
+#define OSSL_PKEY_PARAM_FFC_DIGEST OSSL_PKEY_PARAM_DIGEST
+#define OSSL_PKEY_PARAM_FFC_DIGEST_PROPS OSSL_PKEY_PARAM_PROPERTIES
+
+#define OSSL_PKEY_PARAM_EC_ENCODING "encoding" /* utf8_string */
+#define OSSL_PKEY_PARAM_EC_POINT_CONVERSION_FORMAT "point-format"
+#define OSSL_PKEY_PARAM_EC_GROUP_CHECK_TYPE "group-check"
+#define OSSL_PKEY_PARAM_EC_INCLUDE_PUBLIC "include-public"
+
+/* OSSL_PKEY_PARAM_EC_ENCODING values */
+#define OSSL_PKEY_EC_ENCODING_EXPLICIT "explicit"
+#define OSSL_PKEY_EC_ENCODING_GROUP "named_curve"
+
+#define OSSL_PKEY_EC_POINT_CONVERSION_FORMAT_UNCOMPRESSED "uncompressed"
+#define OSSL_PKEY_EC_POINT_CONVERSION_FORMAT_COMPRESSED "compressed"
+#define OSSL_PKEY_EC_POINT_CONVERSION_FORMAT_HYBRID "hybrid"
+
+#define OSSL_PKEY_EC_GROUP_CHECK_DEFAULT "default"
+#define OSSL_PKEY_EC_GROUP_CHECK_NAMED "named"
+#define OSSL_PKEY_EC_GROUP_CHECK_NAMED_NIST "named-nist"
+
+/* Key Exchange parameters */
+#define OSSL_EXCHANGE_PARAM_PAD "pad" /* uint */
+#define OSSL_EXCHANGE_PARAM_EC_ECDH_COFACTOR_MODE "ecdh-cofactor-mode" /* int */
+#define OSSL_EXCHANGE_PARAM_KDF_TYPE "kdf-type" /* utf8_string */
+#define OSSL_EXCHANGE_PARAM_KDF_DIGEST "kdf-digest" /* utf8_string */
+#define OSSL_EXCHANGE_PARAM_KDF_DIGEST_PROPS "kdf-digest-props" /* utf8_string */
+#define OSSL_EXCHANGE_PARAM_KDF_OUTLEN "kdf-outlen" /* size_t */
+/* The following parameter is an octet_string on set and an octet_ptr on get */
+#define OSSL_EXCHANGE_PARAM_KDF_UKM "kdf-ukm"
+
+/* Signature parameters */
+#define OSSL_SIGNATURE_PARAM_ALGORITHM_ID "algorithm-id"
+#define OSSL_SIGNATURE_PARAM_PAD_MODE OSSL_PKEY_PARAM_PAD_MODE
+#define OSSL_SIGNATURE_PARAM_DIGEST OSSL_PKEY_PARAM_DIGEST
+#define OSSL_SIGNATURE_PARAM_PROPERTIES OSSL_PKEY_PARAM_PROPERTIES
+#define OSSL_SIGNATURE_PARAM_PSS_SALTLEN "saltlen"
+#define OSSL_SIGNATURE_PARAM_MGF1_DIGEST OSSL_PKEY_PARAM_MGF1_DIGEST
+#define OSSL_SIGNATURE_PARAM_MGF1_PROPERTIES \
+ OSSL_PKEY_PARAM_MGF1_PROPERTIES
+#define OSSL_SIGNATURE_PARAM_DIGEST_SIZE OSSL_PKEY_PARAM_DIGEST_SIZE
+
+/* Asym cipher parameters */
+#define OSSL_ASYM_CIPHER_PARAM_DIGEST OSSL_PKEY_PARAM_DIGEST
+#define OSSL_ASYM_CIPHER_PARAM_PROPERTIES OSSL_PKEY_PARAM_PROPERTIES
+#define OSSL_ASYM_CIPHER_PARAM_ENGINE OSSL_PKEY_PARAM_ENGINE
+#define OSSL_ASYM_CIPHER_PARAM_PAD_MODE OSSL_PKEY_PARAM_PAD_MODE
+#define OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST \
+ OSSL_PKEY_PARAM_MGF1_DIGEST
+#define OSSL_ASYM_CIPHER_PARAM_MGF1_DIGEST_PROPS \
+ OSSL_PKEY_PARAM_MGF1_PROPERTIES
+#define OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST OSSL_ALG_PARAM_DIGEST
+#define OSSL_ASYM_CIPHER_PARAM_OAEP_DIGEST_PROPS "digest-props"
+/* The following parameter is an octet_string on set and an octet_ptr on get */
+#define OSSL_ASYM_CIPHER_PARAM_OAEP_LABEL "oaep-label"
+#define OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION "tls-client-version"
+#define OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION "tls-negotiated-version"
+
+/*
+ * Encoder / decoder parameters
+ */
+#define OSSL_ENCODER_PARAM_CIPHER OSSL_ALG_PARAM_CIPHER
+#define OSSL_ENCODER_PARAM_PROPERTIES OSSL_ALG_PARAM_PROPERTIES
+/* Currently PVK only, but reusable for others as needed */
+#define OSSL_ENCODER_PARAM_ENCRYPT_LEVEL "encrypt-level"
+#define OSSL_ENCODER_PARAM_SAVE_PARAMETERS "save-parameters" /* integer */
+
+#define OSSL_DECODER_PARAM_PROPERTIES OSSL_ALG_PARAM_PROPERTIES
+
+/* Passphrase callback parameters */
+#define OSSL_PASSPHRASE_PARAM_INFO "info"
+
+/* Keygen callback parameters, from provider to libcrypto */
+#define OSSL_GEN_PARAM_POTENTIAL "potential" /* integer */
+#define OSSL_GEN_PARAM_ITERATION "iteration" /* integer */
+
+/* ACVP Test parameters : These should not be used normally */
+#define OSSL_PKEY_PARAM_RSA_TEST_XP1 "xp1"
+#define OSSL_PKEY_PARAM_RSA_TEST_XP2 "xp2"
+#define OSSL_PKEY_PARAM_RSA_TEST_XP "xp"
+#define OSSL_PKEY_PARAM_RSA_TEST_XQ1 "xq1"
+#define OSSL_PKEY_PARAM_RSA_TEST_XQ2 "xq2"
+#define OSSL_PKEY_PARAM_RSA_TEST_XQ "xq"
+#define OSSL_PKEY_PARAM_RSA_TEST_P1 "p1"
+#define OSSL_PKEY_PARAM_RSA_TEST_P2 "p2"
+#define OSSL_PKEY_PARAM_RSA_TEST_Q1 "q1"
+#define OSSL_PKEY_PARAM_RSA_TEST_Q2 "q2"
+#define OSSL_SIGNATURE_PARAM_KAT "kat"
+
+/* KEM parameters */
+#define OSSL_KEM_PARAM_OPERATION "operation"
+
+/* OSSL_KEM_PARAM_OPERATION values */
+#define OSSL_KEM_PARAM_OPERATION_RSASVE "RSASVE"
+
+/* Capabilities */
+
+/* TLS-GROUP Capability */
+#define OSSL_CAPABILITY_TLS_GROUP_NAME "tls-group-name"
+#define OSSL_CAPABILITY_TLS_GROUP_NAME_INTERNAL "tls-group-name-internal"
+#define OSSL_CAPABILITY_TLS_GROUP_ID "tls-group-id"
+#define OSSL_CAPABILITY_TLS_GROUP_ALG "tls-group-alg"
+#define OSSL_CAPABILITY_TLS_GROUP_SECURITY_BITS "tls-group-sec-bits"
+#define OSSL_CAPABILITY_TLS_GROUP_IS_KEM "tls-group-is-kem"
+#define OSSL_CAPABILITY_TLS_GROUP_MIN_TLS "tls-min-tls"
+#define OSSL_CAPABILITY_TLS_GROUP_MAX_TLS "tls-max-tls"
+#define OSSL_CAPABILITY_TLS_GROUP_MIN_DTLS "tls-min-dtls"
+#define OSSL_CAPABILITY_TLS_GROUP_MAX_DTLS "tls-max-dtls"
+
+/*-
+ * storemgmt parameters
+ */
+
+/*
+ * Used by storemgmt_ctx_set_params():
+ *
+ * - OSSL_STORE_PARAM_EXPECT is an INTEGER, and the value is any of the
+ * OSSL_STORE_INFO numbers. This is used to set the expected type of
+ * object loaded.
+ *
+ * - OSSL_STORE_PARAM_SUBJECT, OSSL_STORE_PARAM_ISSUER,
+ * OSSL_STORE_PARAM_SERIAL, OSSL_STORE_PARAM_FINGERPRINT,
+ * OSSL_STORE_PARAM_DIGEST, OSSL_STORE_PARAM_ALIAS
+ * are used as search criteria.
+ * (OSSL_STORE_PARAM_DIGEST is used with OSSL_STORE_PARAM_FINGERPRINT)
+ */
+#define OSSL_STORE_PARAM_EXPECT "expect" /* INTEGER */
+#define OSSL_STORE_PARAM_SUBJECT "subject" /* DER blob => OCTET_STRING */
+#define OSSL_STORE_PARAM_ISSUER "name" /* DER blob => OCTET_STRING */
+#define OSSL_STORE_PARAM_SERIAL "serial" /* INTEGER */
+#define OSSL_STORE_PARAM_DIGEST "digest" /* UTF8_STRING */
+#define OSSL_STORE_PARAM_FINGERPRINT "fingerprint" /* OCTET_STRING */
+#define OSSL_STORE_PARAM_ALIAS "alias" /* UTF8_STRING */
+
+/* You may want to pass properties for the provider implementation to use */
+#define OSSL_STORE_PARAM_PROPERTIES "properties" /* utf8_string */
+/* OSSL_DECODER input type if a decoder is used by the store */
+#define OSSL_STORE_PARAM_INPUT_TYPE "input-type" /* UTF8_STRING */
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/core_object.h b/include/openssl/core_object.h
new file mode 100644
index 00000000..62ccf39d
--- /dev/null
+++ b/include/openssl/core_object.h
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CORE_OBJECT_H
+# define OPENSSL_CORE_OBJECT_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*-
+ * Known object types
+ *
+ * These numbers are used as values for the OSSL_PARAM parameter
+ * OSSL_OBJECT_PARAM_TYPE.
+ *
+ * For most of these types, there's a corresponding libcrypto object type.
+ * The corresponding type is indicated with a comment after the number.
+ */
+# define OSSL_OBJECT_UNKNOWN 0
+# define OSSL_OBJECT_NAME 1 /* char * */
+# define OSSL_OBJECT_PKEY 2 /* EVP_PKEY * */
+# define OSSL_OBJECT_CERT 3 /* X509 * */
+# define OSSL_OBJECT_CRL 4 /* X509_CRL * */
+
+/*
+ * The rest of the associated OSSL_PARAM elements is described in core_names.h
+ */
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/crmf.h b/include/openssl/crmf.h
new file mode 100644
index 00000000..b2a82edb
--- /dev/null
+++ b/include/openssl/crmf.h
@@ -0,0 +1,227 @@
+/*-
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\crmf.h.in
+ *
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright Nokia 2007-2019
+ * Copyright Siemens AG 2015-2019
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ *
+ * CRMF (RFC 4211) implementation by M. Peylo, M. Viljanen, and D. von Oheimb.
+ */
+
+
+
+#ifndef OPENSSL_CRMF_H
+# define OPENSSL_CRMF_H
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CRMF
+# include <openssl/opensslv.h>
+# include <openssl/safestack.h>
+# include <openssl/crmferr.h>
+# include <openssl/x509v3.h> /* for GENERAL_NAME etc. */
+
+/* explicit #includes not strictly needed since implied by the above: */
+# include <openssl/types.h>
+# include <openssl/x509.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define OSSL_CRMF_POPOPRIVKEY_THISMESSAGE 0
+# define OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE 1
+# define OSSL_CRMF_POPOPRIVKEY_DHMAC 2
+# define OSSL_CRMF_POPOPRIVKEY_AGREEMAC 3
+# define OSSL_CRMF_POPOPRIVKEY_ENCRYPTEDKEY 4
+
+# define OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT 0
+# define OSSL_CRMF_SUBSEQUENTMESSAGE_CHALLENGERESP 1
+
+typedef struct ossl_crmf_encryptedvalue_st OSSL_CRMF_ENCRYPTEDVALUE;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ENCRYPTEDVALUE)
+typedef struct ossl_crmf_msg_st OSSL_CRMF_MSG;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_MSG)
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_MSG)
+SKM_DEFINE_STACK_OF_INTERNAL(OSSL_CRMF_MSG, OSSL_CRMF_MSG, OSSL_CRMF_MSG)
+#define sk_OSSL_CRMF_MSG_num(sk) OPENSSL_sk_num(ossl_check_const_OSSL_CRMF_MSG_sk_type(sk))
+#define sk_OSSL_CRMF_MSG_value(sk, idx) ((OSSL_CRMF_MSG *)OPENSSL_sk_value(ossl_check_const_OSSL_CRMF_MSG_sk_type(sk), (idx)))
+#define sk_OSSL_CRMF_MSG_new(cmp) ((STACK_OF(OSSL_CRMF_MSG) *)OPENSSL_sk_new(ossl_check_OSSL_CRMF_MSG_compfunc_type(cmp)))
+#define sk_OSSL_CRMF_MSG_new_null() ((STACK_OF(OSSL_CRMF_MSG) *)OPENSSL_sk_new_null())
+#define sk_OSSL_CRMF_MSG_new_reserve(cmp, n) ((STACK_OF(OSSL_CRMF_MSG) *)OPENSSL_sk_new_reserve(ossl_check_OSSL_CRMF_MSG_compfunc_type(cmp), (n)))
+#define sk_OSSL_CRMF_MSG_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OSSL_CRMF_MSG_sk_type(sk), (n))
+#define sk_OSSL_CRMF_MSG_free(sk) OPENSSL_sk_free(ossl_check_OSSL_CRMF_MSG_sk_type(sk))
+#define sk_OSSL_CRMF_MSG_zero(sk) OPENSSL_sk_zero(ossl_check_OSSL_CRMF_MSG_sk_type(sk))
+#define sk_OSSL_CRMF_MSG_delete(sk, i) ((OSSL_CRMF_MSG *)OPENSSL_sk_delete(ossl_check_OSSL_CRMF_MSG_sk_type(sk), (i)))
+#define sk_OSSL_CRMF_MSG_delete_ptr(sk, ptr) ((OSSL_CRMF_MSG *)OPENSSL_sk_delete_ptr(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_type(ptr)))
+#define sk_OSSL_CRMF_MSG_push(sk, ptr) OPENSSL_sk_push(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_type(ptr))
+#define sk_OSSL_CRMF_MSG_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_type(ptr))
+#define sk_OSSL_CRMF_MSG_pop(sk) ((OSSL_CRMF_MSG *)OPENSSL_sk_pop(ossl_check_OSSL_CRMF_MSG_sk_type(sk)))
+#define sk_OSSL_CRMF_MSG_shift(sk) ((OSSL_CRMF_MSG *)OPENSSL_sk_shift(ossl_check_OSSL_CRMF_MSG_sk_type(sk)))
+#define sk_OSSL_CRMF_MSG_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OSSL_CRMF_MSG_sk_type(sk),ossl_check_OSSL_CRMF_MSG_freefunc_type(freefunc))
+#define sk_OSSL_CRMF_MSG_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_type(ptr), (idx))
+#define sk_OSSL_CRMF_MSG_set(sk, idx, ptr) ((OSSL_CRMF_MSG *)OPENSSL_sk_set(ossl_check_OSSL_CRMF_MSG_sk_type(sk), (idx), ossl_check_OSSL_CRMF_MSG_type(ptr)))
+#define sk_OSSL_CRMF_MSG_find(sk, ptr) OPENSSL_sk_find(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_type(ptr))
+#define sk_OSSL_CRMF_MSG_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_type(ptr))
+#define sk_OSSL_CRMF_MSG_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_type(ptr), pnum)
+#define sk_OSSL_CRMF_MSG_sort(sk) OPENSSL_sk_sort(ossl_check_OSSL_CRMF_MSG_sk_type(sk))
+#define sk_OSSL_CRMF_MSG_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OSSL_CRMF_MSG_sk_type(sk))
+#define sk_OSSL_CRMF_MSG_dup(sk) ((STACK_OF(OSSL_CRMF_MSG) *)OPENSSL_sk_dup(ossl_check_const_OSSL_CRMF_MSG_sk_type(sk)))
+#define sk_OSSL_CRMF_MSG_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OSSL_CRMF_MSG) *)OPENSSL_sk_deep_copy(ossl_check_const_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_copyfunc_type(copyfunc), ossl_check_OSSL_CRMF_MSG_freefunc_type(freefunc)))
+#define sk_OSSL_CRMF_MSG_set_cmp_func(sk, cmp) ((sk_OSSL_CRMF_MSG_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OSSL_CRMF_MSG_sk_type(sk), ossl_check_OSSL_CRMF_MSG_compfunc_type(cmp)))
+
+typedef struct ossl_crmf_attributetypeandvalue_st OSSL_CRMF_ATTRIBUTETYPEANDVALUE;
+typedef struct ossl_crmf_pbmparameter_st OSSL_CRMF_PBMPARAMETER;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PBMPARAMETER)
+typedef struct ossl_crmf_poposigningkey_st OSSL_CRMF_POPOSIGNINGKEY;
+typedef struct ossl_crmf_certrequest_st OSSL_CRMF_CERTREQUEST;
+typedef struct ossl_crmf_certid_st OSSL_CRMF_CERTID;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_CERTID)
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTID)
+SKM_DEFINE_STACK_OF_INTERNAL(OSSL_CRMF_CERTID, OSSL_CRMF_CERTID, OSSL_CRMF_CERTID)
+#define sk_OSSL_CRMF_CERTID_num(sk) OPENSSL_sk_num(ossl_check_const_OSSL_CRMF_CERTID_sk_type(sk))
+#define sk_OSSL_CRMF_CERTID_value(sk, idx) ((OSSL_CRMF_CERTID *)OPENSSL_sk_value(ossl_check_const_OSSL_CRMF_CERTID_sk_type(sk), (idx)))
+#define sk_OSSL_CRMF_CERTID_new(cmp) ((STACK_OF(OSSL_CRMF_CERTID) *)OPENSSL_sk_new(ossl_check_OSSL_CRMF_CERTID_compfunc_type(cmp)))
+#define sk_OSSL_CRMF_CERTID_new_null() ((STACK_OF(OSSL_CRMF_CERTID) *)OPENSSL_sk_new_null())
+#define sk_OSSL_CRMF_CERTID_new_reserve(cmp, n) ((STACK_OF(OSSL_CRMF_CERTID) *)OPENSSL_sk_new_reserve(ossl_check_OSSL_CRMF_CERTID_compfunc_type(cmp), (n)))
+#define sk_OSSL_CRMF_CERTID_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), (n))
+#define sk_OSSL_CRMF_CERTID_free(sk) OPENSSL_sk_free(ossl_check_OSSL_CRMF_CERTID_sk_type(sk))
+#define sk_OSSL_CRMF_CERTID_zero(sk) OPENSSL_sk_zero(ossl_check_OSSL_CRMF_CERTID_sk_type(sk))
+#define sk_OSSL_CRMF_CERTID_delete(sk, i) ((OSSL_CRMF_CERTID *)OPENSSL_sk_delete(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), (i)))
+#define sk_OSSL_CRMF_CERTID_delete_ptr(sk, ptr) ((OSSL_CRMF_CERTID *)OPENSSL_sk_delete_ptr(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_type(ptr)))
+#define sk_OSSL_CRMF_CERTID_push(sk, ptr) OPENSSL_sk_push(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_type(ptr))
+#define sk_OSSL_CRMF_CERTID_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_type(ptr))
+#define sk_OSSL_CRMF_CERTID_pop(sk) ((OSSL_CRMF_CERTID *)OPENSSL_sk_pop(ossl_check_OSSL_CRMF_CERTID_sk_type(sk)))
+#define sk_OSSL_CRMF_CERTID_shift(sk) ((OSSL_CRMF_CERTID *)OPENSSL_sk_shift(ossl_check_OSSL_CRMF_CERTID_sk_type(sk)))
+#define sk_OSSL_CRMF_CERTID_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OSSL_CRMF_CERTID_sk_type(sk),ossl_check_OSSL_CRMF_CERTID_freefunc_type(freefunc))
+#define sk_OSSL_CRMF_CERTID_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_type(ptr), (idx))
+#define sk_OSSL_CRMF_CERTID_set(sk, idx, ptr) ((OSSL_CRMF_CERTID *)OPENSSL_sk_set(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), (idx), ossl_check_OSSL_CRMF_CERTID_type(ptr)))
+#define sk_OSSL_CRMF_CERTID_find(sk, ptr) OPENSSL_sk_find(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_type(ptr))
+#define sk_OSSL_CRMF_CERTID_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_type(ptr))
+#define sk_OSSL_CRMF_CERTID_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_type(ptr), pnum)
+#define sk_OSSL_CRMF_CERTID_sort(sk) OPENSSL_sk_sort(ossl_check_OSSL_CRMF_CERTID_sk_type(sk))
+#define sk_OSSL_CRMF_CERTID_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OSSL_CRMF_CERTID_sk_type(sk))
+#define sk_OSSL_CRMF_CERTID_dup(sk) ((STACK_OF(OSSL_CRMF_CERTID) *)OPENSSL_sk_dup(ossl_check_const_OSSL_CRMF_CERTID_sk_type(sk)))
+#define sk_OSSL_CRMF_CERTID_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OSSL_CRMF_CERTID) *)OPENSSL_sk_deep_copy(ossl_check_const_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_copyfunc_type(copyfunc), ossl_check_OSSL_CRMF_CERTID_freefunc_type(freefunc)))
+#define sk_OSSL_CRMF_CERTID_set_cmp_func(sk, cmp) ((sk_OSSL_CRMF_CERTID_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OSSL_CRMF_CERTID_sk_type(sk), ossl_check_OSSL_CRMF_CERTID_compfunc_type(cmp)))
+
+
+typedef struct ossl_crmf_pkipublicationinfo_st OSSL_CRMF_PKIPUBLICATIONINFO;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PKIPUBLICATIONINFO)
+typedef struct ossl_crmf_singlepubinfo_st OSSL_CRMF_SINGLEPUBINFO;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_SINGLEPUBINFO)
+typedef struct ossl_crmf_certtemplate_st OSSL_CRMF_CERTTEMPLATE;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_CERTTEMPLATE)
+typedef STACK_OF(OSSL_CRMF_MSG) OSSL_CRMF_MSGS;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_MSGS)
+
+typedef struct ossl_crmf_optionalvalidity_st OSSL_CRMF_OPTIONALVALIDITY;
+
+/* crmf_pbm.c */
+OSSL_CRMF_PBMPARAMETER *OSSL_CRMF_pbmp_new(OSSL_LIB_CTX *libctx, size_t slen,
+ int owfnid, size_t itercnt,
+ int macnid);
+int OSSL_CRMF_pbm_new(OSSL_LIB_CTX *libctx, const char *propq,
+ const OSSL_CRMF_PBMPARAMETER *pbmp,
+ const unsigned char *msg, size_t msglen,
+ const unsigned char *sec, size_t seclen,
+ unsigned char **mac, size_t *maclen);
+
+/* crmf_lib.c */
+int OSSL_CRMF_MSG_set1_regCtrl_regToken(OSSL_CRMF_MSG *msg,
+ const ASN1_UTF8STRING *tok);
+ASN1_UTF8STRING
+*OSSL_CRMF_MSG_get0_regCtrl_regToken(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regCtrl_authenticator(OSSL_CRMF_MSG *msg,
+ const ASN1_UTF8STRING *auth);
+ASN1_UTF8STRING
+*OSSL_CRMF_MSG_get0_regCtrl_authenticator(const OSSL_CRMF_MSG *msg);
+int
+OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo(OSSL_CRMF_PKIPUBLICATIONINFO *pi,
+ OSSL_CRMF_SINGLEPUBINFO *spi);
+# define OSSL_CRMF_PUB_METHOD_DONTCARE 0
+# define OSSL_CRMF_PUB_METHOD_X500 1
+# define OSSL_CRMF_PUB_METHOD_WEB 2
+# define OSSL_CRMF_PUB_METHOD_LDAP 3
+int OSSL_CRMF_MSG_set0_SinglePubInfo(OSSL_CRMF_SINGLEPUBINFO *spi,
+ int method, GENERAL_NAME *nm);
+# define OSSL_CRMF_PUB_ACTION_DONTPUBLISH 0
+# define OSSL_CRMF_PUB_ACTION_PLEASEPUBLISH 1
+int OSSL_CRMF_MSG_set_PKIPublicationInfo_action(OSSL_CRMF_PKIPUBLICATIONINFO *pi,
+ int action);
+int OSSL_CRMF_MSG_set1_regCtrl_pkiPublicationInfo(OSSL_CRMF_MSG *msg,
+ const OSSL_CRMF_PKIPUBLICATIONINFO *pi);
+OSSL_CRMF_PKIPUBLICATIONINFO
+*OSSL_CRMF_MSG_get0_regCtrl_pkiPublicationInfo(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regCtrl_protocolEncrKey(OSSL_CRMF_MSG *msg,
+ const X509_PUBKEY *pubkey);
+X509_PUBKEY
+*OSSL_CRMF_MSG_get0_regCtrl_protocolEncrKey(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regCtrl_oldCertID(OSSL_CRMF_MSG *msg,
+ const OSSL_CRMF_CERTID *cid);
+OSSL_CRMF_CERTID
+*OSSL_CRMF_MSG_get0_regCtrl_oldCertID(const OSSL_CRMF_MSG *msg);
+OSSL_CRMF_CERTID *OSSL_CRMF_CERTID_gen(const X509_NAME *issuer,
+ const ASN1_INTEGER *serial);
+
+int OSSL_CRMF_MSG_set1_regInfo_utf8Pairs(OSSL_CRMF_MSG *msg,
+ const ASN1_UTF8STRING *utf8pairs);
+ASN1_UTF8STRING
+*OSSL_CRMF_MSG_get0_regInfo_utf8Pairs(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regInfo_certReq(OSSL_CRMF_MSG *msg,
+ const OSSL_CRMF_CERTREQUEST *cr);
+OSSL_CRMF_CERTREQUEST
+*OSSL_CRMF_MSG_get0_regInfo_certReq(const OSSL_CRMF_MSG *msg);
+
+int OSSL_CRMF_MSG_set0_validity(OSSL_CRMF_MSG *crm,
+ ASN1_TIME *notBefore, ASN1_TIME *notAfter);
+int OSSL_CRMF_MSG_set_certReqId(OSSL_CRMF_MSG *crm, int rid);
+int OSSL_CRMF_MSG_get_certReqId(const OSSL_CRMF_MSG *crm);
+int OSSL_CRMF_MSG_set0_extensions(OSSL_CRMF_MSG *crm, X509_EXTENSIONS *exts);
+
+int OSSL_CRMF_MSG_push0_extension(OSSL_CRMF_MSG *crm, X509_EXTENSION *ext);
+# define OSSL_CRMF_POPO_NONE -1
+# define OSSL_CRMF_POPO_RAVERIFIED 0
+# define OSSL_CRMF_POPO_SIGNATURE 1
+# define OSSL_CRMF_POPO_KEYENC 2
+# define OSSL_CRMF_POPO_KEYAGREE 3
+int OSSL_CRMF_MSG_create_popo(int meth, OSSL_CRMF_MSG *crm,
+ EVP_PKEY *pkey, const EVP_MD *digest,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int OSSL_CRMF_MSGS_verify_popo(const OSSL_CRMF_MSGS *reqs,
+ int rid, int acceptRAVerified,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_CRMF_CERTTEMPLATE *OSSL_CRMF_MSG_get0_tmpl(const OSSL_CRMF_MSG *crm);
+const ASN1_INTEGER
+*OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+const X509_NAME
+*OSSL_CRMF_CERTTEMPLATE_get0_subject(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+const X509_NAME
+*OSSL_CRMF_CERTTEMPLATE_get0_issuer(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+X509_EXTENSIONS
+*OSSL_CRMF_CERTTEMPLATE_get0_extensions(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+const X509_NAME
+*OSSL_CRMF_CERTID_get0_issuer(const OSSL_CRMF_CERTID *cid);
+const ASN1_INTEGER
+*OSSL_CRMF_CERTID_get0_serialNumber(const OSSL_CRMF_CERTID *cid);
+int OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_CERTTEMPLATE *tmpl,
+ EVP_PKEY *pubkey,
+ const X509_NAME *subject,
+ const X509_NAME *issuer,
+ const ASN1_INTEGER *serial);
+X509
+*OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(const OSSL_CRMF_ENCRYPTEDVALUE *ecert,
+ OSSL_LIB_CTX *libctx, const char *propq,
+ EVP_PKEY *pkey);
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* !defined(OPENSSL_NO_CRMF) */
+#endif /* !defined(OPENSSL_CRMF_H) */
diff --git a/include/openssl/crmf.h.in b/include/openssl/crmf.h.in
new file mode 100644
index 00000000..4d37ea6d
--- /dev/null
+++ b/include/openssl/crmf.h.in
@@ -0,0 +1,180 @@
+/*-
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2007-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright Nokia 2007-2019
+ * Copyright Siemens AG 2015-2019
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ *
+ * CRMF (RFC 4211) implementation by M. Peylo, M. Viljanen, and D. von Oheimb.
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_CRMF_H
+# define OPENSSL_CRMF_H
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CRMF
+# include <openssl/opensslv.h>
+# include <openssl/safestack.h>
+# include <openssl/crmferr.h>
+# include <openssl/x509v3.h> /* for GENERAL_NAME etc. */
+
+/* explicit #includes not strictly needed since implied by the above: */
+# include <openssl/types.h>
+# include <openssl/x509.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define OSSL_CRMF_POPOPRIVKEY_THISMESSAGE 0
+# define OSSL_CRMF_POPOPRIVKEY_SUBSEQUENTMESSAGE 1
+# define OSSL_CRMF_POPOPRIVKEY_DHMAC 2
+# define OSSL_CRMF_POPOPRIVKEY_AGREEMAC 3
+# define OSSL_CRMF_POPOPRIVKEY_ENCRYPTEDKEY 4
+
+# define OSSL_CRMF_SUBSEQUENTMESSAGE_ENCRCERT 0
+# define OSSL_CRMF_SUBSEQUENTMESSAGE_CHALLENGERESP 1
+
+typedef struct ossl_crmf_encryptedvalue_st OSSL_CRMF_ENCRYPTEDVALUE;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_ENCRYPTEDVALUE)
+typedef struct ossl_crmf_msg_st OSSL_CRMF_MSG;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_MSG)
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_MSG)
+{-
+ generate_stack_macros("OSSL_CRMF_MSG");
+-}
+typedef struct ossl_crmf_attributetypeandvalue_st OSSL_CRMF_ATTRIBUTETYPEANDVALUE;
+typedef struct ossl_crmf_pbmparameter_st OSSL_CRMF_PBMPARAMETER;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PBMPARAMETER)
+typedef struct ossl_crmf_poposigningkey_st OSSL_CRMF_POPOSIGNINGKEY;
+typedef struct ossl_crmf_certrequest_st OSSL_CRMF_CERTREQUEST;
+typedef struct ossl_crmf_certid_st OSSL_CRMF_CERTID;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_CERTID)
+DECLARE_ASN1_DUP_FUNCTION(OSSL_CRMF_CERTID)
+{-
+ generate_stack_macros("OSSL_CRMF_CERTID");
+-}
+
+typedef struct ossl_crmf_pkipublicationinfo_st OSSL_CRMF_PKIPUBLICATIONINFO;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_PKIPUBLICATIONINFO)
+typedef struct ossl_crmf_singlepubinfo_st OSSL_CRMF_SINGLEPUBINFO;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_SINGLEPUBINFO)
+typedef struct ossl_crmf_certtemplate_st OSSL_CRMF_CERTTEMPLATE;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_CERTTEMPLATE)
+typedef STACK_OF(OSSL_CRMF_MSG) OSSL_CRMF_MSGS;
+DECLARE_ASN1_FUNCTIONS(OSSL_CRMF_MSGS)
+
+typedef struct ossl_crmf_optionalvalidity_st OSSL_CRMF_OPTIONALVALIDITY;
+
+/* crmf_pbm.c */
+OSSL_CRMF_PBMPARAMETER *OSSL_CRMF_pbmp_new(OSSL_LIB_CTX *libctx, size_t slen,
+ int owfnid, size_t itercnt,
+ int macnid);
+int OSSL_CRMF_pbm_new(OSSL_LIB_CTX *libctx, const char *propq,
+ const OSSL_CRMF_PBMPARAMETER *pbmp,
+ const unsigned char *msg, size_t msglen,
+ const unsigned char *sec, size_t seclen,
+ unsigned char **mac, size_t *maclen);
+
+/* crmf_lib.c */
+int OSSL_CRMF_MSG_set1_regCtrl_regToken(OSSL_CRMF_MSG *msg,
+ const ASN1_UTF8STRING *tok);
+ASN1_UTF8STRING
+*OSSL_CRMF_MSG_get0_regCtrl_regToken(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regCtrl_authenticator(OSSL_CRMF_MSG *msg,
+ const ASN1_UTF8STRING *auth);
+ASN1_UTF8STRING
+*OSSL_CRMF_MSG_get0_regCtrl_authenticator(const OSSL_CRMF_MSG *msg);
+int
+OSSL_CRMF_MSG_PKIPublicationInfo_push0_SinglePubInfo(OSSL_CRMF_PKIPUBLICATIONINFO *pi,
+ OSSL_CRMF_SINGLEPUBINFO *spi);
+# define OSSL_CRMF_PUB_METHOD_DONTCARE 0
+# define OSSL_CRMF_PUB_METHOD_X500 1
+# define OSSL_CRMF_PUB_METHOD_WEB 2
+# define OSSL_CRMF_PUB_METHOD_LDAP 3
+int OSSL_CRMF_MSG_set0_SinglePubInfo(OSSL_CRMF_SINGLEPUBINFO *spi,
+ int method, GENERAL_NAME *nm);
+# define OSSL_CRMF_PUB_ACTION_DONTPUBLISH 0
+# define OSSL_CRMF_PUB_ACTION_PLEASEPUBLISH 1
+int OSSL_CRMF_MSG_set_PKIPublicationInfo_action(OSSL_CRMF_PKIPUBLICATIONINFO *pi,
+ int action);
+int OSSL_CRMF_MSG_set1_regCtrl_pkiPublicationInfo(OSSL_CRMF_MSG *msg,
+ const OSSL_CRMF_PKIPUBLICATIONINFO *pi);
+OSSL_CRMF_PKIPUBLICATIONINFO
+*OSSL_CRMF_MSG_get0_regCtrl_pkiPublicationInfo(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regCtrl_protocolEncrKey(OSSL_CRMF_MSG *msg,
+ const X509_PUBKEY *pubkey);
+X509_PUBKEY
+*OSSL_CRMF_MSG_get0_regCtrl_protocolEncrKey(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regCtrl_oldCertID(OSSL_CRMF_MSG *msg,
+ const OSSL_CRMF_CERTID *cid);
+OSSL_CRMF_CERTID
+*OSSL_CRMF_MSG_get0_regCtrl_oldCertID(const OSSL_CRMF_MSG *msg);
+OSSL_CRMF_CERTID *OSSL_CRMF_CERTID_gen(const X509_NAME *issuer,
+ const ASN1_INTEGER *serial);
+
+int OSSL_CRMF_MSG_set1_regInfo_utf8Pairs(OSSL_CRMF_MSG *msg,
+ const ASN1_UTF8STRING *utf8pairs);
+ASN1_UTF8STRING
+*OSSL_CRMF_MSG_get0_regInfo_utf8Pairs(const OSSL_CRMF_MSG *msg);
+int OSSL_CRMF_MSG_set1_regInfo_certReq(OSSL_CRMF_MSG *msg,
+ const OSSL_CRMF_CERTREQUEST *cr);
+OSSL_CRMF_CERTREQUEST
+*OSSL_CRMF_MSG_get0_regInfo_certReq(const OSSL_CRMF_MSG *msg);
+
+int OSSL_CRMF_MSG_set0_validity(OSSL_CRMF_MSG *crm,
+ ASN1_TIME *notBefore, ASN1_TIME *notAfter);
+int OSSL_CRMF_MSG_set_certReqId(OSSL_CRMF_MSG *crm, int rid);
+int OSSL_CRMF_MSG_get_certReqId(const OSSL_CRMF_MSG *crm);
+int OSSL_CRMF_MSG_set0_extensions(OSSL_CRMF_MSG *crm, X509_EXTENSIONS *exts);
+
+int OSSL_CRMF_MSG_push0_extension(OSSL_CRMF_MSG *crm, X509_EXTENSION *ext);
+# define OSSL_CRMF_POPO_NONE -1
+# define OSSL_CRMF_POPO_RAVERIFIED 0
+# define OSSL_CRMF_POPO_SIGNATURE 1
+# define OSSL_CRMF_POPO_KEYENC 2
+# define OSSL_CRMF_POPO_KEYAGREE 3
+int OSSL_CRMF_MSG_create_popo(int meth, OSSL_CRMF_MSG *crm,
+ EVP_PKEY *pkey, const EVP_MD *digest,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int OSSL_CRMF_MSGS_verify_popo(const OSSL_CRMF_MSGS *reqs,
+ int rid, int acceptRAVerified,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_CRMF_CERTTEMPLATE *OSSL_CRMF_MSG_get0_tmpl(const OSSL_CRMF_MSG *crm);
+const ASN1_INTEGER
+*OSSL_CRMF_CERTTEMPLATE_get0_serialNumber(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+const X509_NAME
+*OSSL_CRMF_CERTTEMPLATE_get0_subject(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+const X509_NAME
+*OSSL_CRMF_CERTTEMPLATE_get0_issuer(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+X509_EXTENSIONS
+*OSSL_CRMF_CERTTEMPLATE_get0_extensions(const OSSL_CRMF_CERTTEMPLATE *tmpl);
+const X509_NAME
+*OSSL_CRMF_CERTID_get0_issuer(const OSSL_CRMF_CERTID *cid);
+const ASN1_INTEGER
+*OSSL_CRMF_CERTID_get0_serialNumber(const OSSL_CRMF_CERTID *cid);
+int OSSL_CRMF_CERTTEMPLATE_fill(OSSL_CRMF_CERTTEMPLATE *tmpl,
+ EVP_PKEY *pubkey,
+ const X509_NAME *subject,
+ const X509_NAME *issuer,
+ const ASN1_INTEGER *serial);
+X509
+*OSSL_CRMF_ENCRYPTEDVALUE_get1_encCert(const OSSL_CRMF_ENCRYPTEDVALUE *ecert,
+ OSSL_LIB_CTX *libctx, const char *propq,
+ EVP_PKEY *pkey);
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* !defined(OPENSSL_NO_CRMF) */
+#endif /* !defined(OPENSSL_CRMF_H) */
diff --git a/include/openssl/crmferr.h b/include/openssl/crmferr.h
new file mode 100644
index 00000000..b242b922
--- /dev/null
+++ b/include/openssl/crmferr.h
@@ -0,0 +1,50 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CRMFERR_H
+# define OPENSSL_CRMFERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_CRMF
+
+
+/*
+ * CRMF reason codes.
+ */
+# define CRMF_R_BAD_PBM_ITERATIONCOUNT 100
+# define CRMF_R_CRMFERROR 102
+# define CRMF_R_ERROR 103
+# define CRMF_R_ERROR_DECODING_CERTIFICATE 104
+# define CRMF_R_ERROR_DECRYPTING_CERTIFICATE 105
+# define CRMF_R_ERROR_DECRYPTING_SYMMETRIC_KEY 106
+# define CRMF_R_FAILURE_OBTAINING_RANDOM 107
+# define CRMF_R_ITERATIONCOUNT_BELOW_100 108
+# define CRMF_R_MALFORMED_IV 101
+# define CRMF_R_NULL_ARGUMENT 109
+# define CRMF_R_POPOSKINPUT_NOT_SUPPORTED 113
+# define CRMF_R_POPO_INCONSISTENT_PUBLIC_KEY 117
+# define CRMF_R_POPO_MISSING 121
+# define CRMF_R_POPO_MISSING_PUBLIC_KEY 118
+# define CRMF_R_POPO_MISSING_SUBJECT 119
+# define CRMF_R_POPO_RAVERIFIED_NOT_ACCEPTED 120
+# define CRMF_R_SETTING_MAC_ALGOR_FAILURE 110
+# define CRMF_R_SETTING_OWF_ALGOR_FAILURE 111
+# define CRMF_R_UNSUPPORTED_ALGORITHM 112
+# define CRMF_R_UNSUPPORTED_CIPHER 114
+# define CRMF_R_UNSUPPORTED_METHOD_FOR_CREATING_POPO 115
+# define CRMF_R_UNSUPPORTED_POPO_METHOD 116
+
+# endif
+#endif
diff --git a/include/openssl/crypto.h b/include/openssl/crypto.h
new file mode 100644
index 00000000..ef327f20
--- /dev/null
+++ b/include/openssl/crypto.h
@@ -0,0 +1,556 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\crypto.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_CRYPTO_H
+# define OPENSSL_CRYPTO_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CRYPTO_H
+# endif
+
+# include <stdlib.h>
+# include <time.h>
+
+# include <openssl/e_os2.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+
+# include <openssl/safestack.h>
+# include <openssl/opensslv.h>
+# include <openssl/types.h>
+# include <openssl/opensslconf.h>
+# include <openssl/cryptoerr.h>
+# include <openssl/core.h>
+
+# ifdef CHARSET_EBCDIC
+# include <openssl/ebcdic.h>
+# endif
+
+/*
+ * Resolve problems on some operating systems with symbol names that clash
+ * one way or another
+ */
+# include <openssl/symhacks.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/opensslv.h>
+# endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSLeay OpenSSL_version_num
+# define SSLeay_version OpenSSL_version
+# define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
+# define SSLEAY_VERSION OPENSSL_VERSION
+# define SSLEAY_CFLAGS OPENSSL_CFLAGS
+# define SSLEAY_BUILT_ON OPENSSL_BUILT_ON
+# define SSLEAY_PLATFORM OPENSSL_PLATFORM
+# define SSLEAY_DIR OPENSSL_DIR
+
+/*
+ * Old type for allocating dynamic locks. No longer used. Use the new thread
+ * API instead.
+ */
+typedef struct {
+ int dummy;
+} CRYPTO_dynlock;
+
+# endif /* OPENSSL_NO_DEPRECATED_1_1_0 */
+
+typedef void CRYPTO_RWLOCK;
+
+CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void);
+__owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock);
+__owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock);
+int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock);
+void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock);
+
+int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock);
+int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret,
+ CRYPTO_RWLOCK *lock);
+int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock);
+
+/* No longer needed, so this is a no-op */
+#define OPENSSL_malloc_init() while(0) continue
+
+# define OPENSSL_malloc(num) \
+ CRYPTO_malloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_zalloc(num) \
+ CRYPTO_zalloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_realloc(addr, num) \
+ CRYPTO_realloc(addr, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_clear_realloc(addr, old_num, num) \
+ CRYPTO_clear_realloc(addr, old_num, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_clear_free(addr, num) \
+ CRYPTO_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_free(addr) \
+ CRYPTO_free(addr, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_memdup(str, s) \
+ CRYPTO_memdup((str), s, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_strdup(str) \
+ CRYPTO_strdup(str, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_strndup(str, n) \
+ CRYPTO_strndup(str, n, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_malloc(num) \
+ CRYPTO_secure_malloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_zalloc(num) \
+ CRYPTO_secure_zalloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_free(addr) \
+ CRYPTO_secure_free(addr, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_clear_free(addr, num) \
+ CRYPTO_secure_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_actual_size(ptr) \
+ CRYPTO_secure_actual_size(ptr)
+
+size_t OPENSSL_strlcpy(char *dst, const char *src, size_t siz);
+size_t OPENSSL_strlcat(char *dst, const char *src, size_t siz);
+size_t OPENSSL_strnlen(const char *str, size_t maxlen);
+int OPENSSL_buf2hexstr_ex(char *str, size_t str_n, size_t *strlen,
+ const unsigned char *buf, size_t buflen,
+ const char sep);
+char *OPENSSL_buf2hexstr(const unsigned char *buf, long buflen);
+int OPENSSL_hexstr2buf_ex(unsigned char *buf, size_t buf_n, size_t *buflen,
+ const char *str, const char sep);
+unsigned char *OPENSSL_hexstr2buf(const char *str, long *buflen);
+int OPENSSL_hexchar2int(unsigned char c);
+
+# define OPENSSL_MALLOC_MAX_NELEMS(type) (((1U<<(sizeof(int)*8-1))-1)/sizeof(type))
+
+/*
+ * These functions return the values of OPENSSL_VERSION_MAJOR,
+ * OPENSSL_VERSION_MINOR, OPENSSL_VERSION_PATCH, OPENSSL_VERSION_PRE_RELEASE
+ * and OPENSSL_VERSION_BUILD_METADATA, respectively.
+ */
+unsigned int OPENSSL_version_major(void);
+unsigned int OPENSSL_version_minor(void);
+unsigned int OPENSSL_version_patch(void);
+const char *OPENSSL_version_pre_release(void);
+const char *OPENSSL_version_build_metadata(void);
+
+unsigned long OpenSSL_version_num(void);
+const char *OpenSSL_version(int type);
+# define OPENSSL_VERSION 0
+# define OPENSSL_CFLAGS 1
+# define OPENSSL_BUILT_ON 2
+# define OPENSSL_PLATFORM 3
+# define OPENSSL_DIR 4
+# define OPENSSL_ENGINES_DIR 5
+# define OPENSSL_VERSION_STRING 6
+# define OPENSSL_FULL_VERSION_STRING 7
+# define OPENSSL_MODULES_DIR 8
+# define OPENSSL_CPU_INFO 9
+
+const char *OPENSSL_info(int type);
+/*
+ * The series starts at 1001 to avoid confusion with the OpenSSL_version
+ * types.
+ */
+# define OPENSSL_INFO_CONFIG_DIR 1001
+# define OPENSSL_INFO_ENGINES_DIR 1002
+# define OPENSSL_INFO_MODULES_DIR 1003
+# define OPENSSL_INFO_DSO_EXTENSION 1004
+# define OPENSSL_INFO_DIR_FILENAME_SEPARATOR 1005
+# define OPENSSL_INFO_LIST_SEPARATOR 1006
+# define OPENSSL_INFO_SEED_SOURCE 1007
+# define OPENSSL_INFO_CPU_SETTINGS 1008
+
+int OPENSSL_issetugid(void);
+
+struct crypto_ex_data_st {
+ OSSL_LIB_CTX *ctx;
+ STACK_OF(void) *sk;
+};
+
+SKM_DEFINE_STACK_OF_INTERNAL(void, void, void)
+#define sk_void_num(sk) OPENSSL_sk_num(ossl_check_const_void_sk_type(sk))
+#define sk_void_value(sk, idx) ((void *)OPENSSL_sk_value(ossl_check_const_void_sk_type(sk), (idx)))
+#define sk_void_new(cmp) ((STACK_OF(void) *)OPENSSL_sk_new(ossl_check_void_compfunc_type(cmp)))
+#define sk_void_new_null() ((STACK_OF(void) *)OPENSSL_sk_new_null())
+#define sk_void_new_reserve(cmp, n) ((STACK_OF(void) *)OPENSSL_sk_new_reserve(ossl_check_void_compfunc_type(cmp), (n)))
+#define sk_void_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_void_sk_type(sk), (n))
+#define sk_void_free(sk) OPENSSL_sk_free(ossl_check_void_sk_type(sk))
+#define sk_void_zero(sk) OPENSSL_sk_zero(ossl_check_void_sk_type(sk))
+#define sk_void_delete(sk, i) ((void *)OPENSSL_sk_delete(ossl_check_void_sk_type(sk), (i)))
+#define sk_void_delete_ptr(sk, ptr) ((void *)OPENSSL_sk_delete_ptr(ossl_check_void_sk_type(sk), ossl_check_void_type(ptr)))
+#define sk_void_push(sk, ptr) OPENSSL_sk_push(ossl_check_void_sk_type(sk), ossl_check_void_type(ptr))
+#define sk_void_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_void_sk_type(sk), ossl_check_void_type(ptr))
+#define sk_void_pop(sk) ((void *)OPENSSL_sk_pop(ossl_check_void_sk_type(sk)))
+#define sk_void_shift(sk) ((void *)OPENSSL_sk_shift(ossl_check_void_sk_type(sk)))
+#define sk_void_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_void_sk_type(sk),ossl_check_void_freefunc_type(freefunc))
+#define sk_void_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_void_sk_type(sk), ossl_check_void_type(ptr), (idx))
+#define sk_void_set(sk, idx, ptr) ((void *)OPENSSL_sk_set(ossl_check_void_sk_type(sk), (idx), ossl_check_void_type(ptr)))
+#define sk_void_find(sk, ptr) OPENSSL_sk_find(ossl_check_void_sk_type(sk), ossl_check_void_type(ptr))
+#define sk_void_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_void_sk_type(sk), ossl_check_void_type(ptr))
+#define sk_void_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_void_sk_type(sk), ossl_check_void_type(ptr), pnum)
+#define sk_void_sort(sk) OPENSSL_sk_sort(ossl_check_void_sk_type(sk))
+#define sk_void_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_void_sk_type(sk))
+#define sk_void_dup(sk) ((STACK_OF(void) *)OPENSSL_sk_dup(ossl_check_const_void_sk_type(sk)))
+#define sk_void_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(void) *)OPENSSL_sk_deep_copy(ossl_check_const_void_sk_type(sk), ossl_check_void_copyfunc_type(copyfunc), ossl_check_void_freefunc_type(freefunc)))
+#define sk_void_set_cmp_func(sk, cmp) ((sk_void_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_void_sk_type(sk), ossl_check_void_compfunc_type(cmp)))
+
+
+
+/*
+ * Per class, we have a STACK of function pointers.
+ */
+# define CRYPTO_EX_INDEX_SSL 0
+# define CRYPTO_EX_INDEX_SSL_CTX 1
+# define CRYPTO_EX_INDEX_SSL_SESSION 2
+# define CRYPTO_EX_INDEX_X509 3
+# define CRYPTO_EX_INDEX_X509_STORE 4
+# define CRYPTO_EX_INDEX_X509_STORE_CTX 5
+# define CRYPTO_EX_INDEX_DH 6
+# define CRYPTO_EX_INDEX_DSA 7
+# define CRYPTO_EX_INDEX_EC_KEY 8
+# define CRYPTO_EX_INDEX_RSA 9
+# define CRYPTO_EX_INDEX_ENGINE 10
+# define CRYPTO_EX_INDEX_UI 11
+# define CRYPTO_EX_INDEX_BIO 12
+# define CRYPTO_EX_INDEX_APP 13
+# define CRYPTO_EX_INDEX_UI_METHOD 14
+# define CRYPTO_EX_INDEX_RAND_DRBG 15
+# define CRYPTO_EX_INDEX_DRBG CRYPTO_EX_INDEX_RAND_DRBG
+# define CRYPTO_EX_INDEX_OSSL_LIB_CTX 16
+# define CRYPTO_EX_INDEX_EVP_PKEY 17
+# define CRYPTO_EX_INDEX__COUNT 18
+
+typedef void CRYPTO_EX_new (void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+ int idx, long argl, void *argp);
+typedef void CRYPTO_EX_free (void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+ int idx, long argl, void *argp);
+typedef int CRYPTO_EX_dup (CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
+ void **from_d, int idx, long argl, void *argp);
+__owur int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
+ CRYPTO_EX_new *new_func,
+ CRYPTO_EX_dup *dup_func,
+ CRYPTO_EX_free *free_func);
+/* No longer use an index. */
+int CRYPTO_free_ex_index(int class_index, int idx);
+
+/*
+ * Initialise/duplicate/free CRYPTO_EX_DATA variables corresponding to a
+ * given class (invokes whatever per-class callbacks are applicable)
+ */
+int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
+int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
+ const CRYPTO_EX_DATA *from);
+
+void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
+
+/* Allocate a single item in the CRYPTO_EX_DATA variable */
+int CRYPTO_alloc_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad,
+ int idx);
+
+/*
+ * Get/set data in a CRYPTO_EX_DATA variable corresponding to a particular
+ * index (relative to the class type involved)
+ */
+int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val);
+void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/*
+ * This function cleans up all "ex_data" state. It mustn't be called under
+ * potential race-conditions.
+ */
+# define CRYPTO_cleanup_all_ex_data() while(0) continue
+
+/*
+ * The old locking functions have been removed completely without compatibility
+ * macros. This is because the old functions either could not properly report
+ * errors, or the returned error values were not clearly documented.
+ * Replacing the locking functions with no-ops would cause race condition
+ * issues in the affected applications. It is far better for them to fail at
+ * compile time.
+ * On the other hand, the locking callbacks are no longer used. Consequently,
+ * the callback management functions can be safely replaced with no-op macros.
+ */
+# define CRYPTO_num_locks() (1)
+# define CRYPTO_set_locking_callback(func)
+# define CRYPTO_get_locking_callback() (NULL)
+# define CRYPTO_set_add_lock_callback(func)
+# define CRYPTO_get_add_lock_callback() (NULL)
+
+/*
+ * These defines where used in combination with the old locking callbacks,
+ * they are not called anymore, but old code that's not called might still
+ * use them.
+ */
+# define CRYPTO_LOCK 1
+# define CRYPTO_UNLOCK 2
+# define CRYPTO_READ 4
+# define CRYPTO_WRITE 8
+
+/* This structure is no longer used */
+typedef struct crypto_threadid_st {
+ int dummy;
+} CRYPTO_THREADID;
+/* Only use CRYPTO_THREADID_set_[numeric|pointer]() within callbacks */
+# define CRYPTO_THREADID_set_numeric(id, val)
+# define CRYPTO_THREADID_set_pointer(id, ptr)
+# define CRYPTO_THREADID_set_callback(threadid_func) (0)
+# define CRYPTO_THREADID_get_callback() (NULL)
+# define CRYPTO_THREADID_current(id)
+# define CRYPTO_THREADID_cmp(a, b) (-1)
+# define CRYPTO_THREADID_cpy(dest, src)
+# define CRYPTO_THREADID_hash(id) (0UL)
+
+# ifndef OPENSSL_NO_DEPRECATED_1_0_0
+# define CRYPTO_set_id_callback(func)
+# define CRYPTO_get_id_callback() (NULL)
+# define CRYPTO_thread_id() (0UL)
+# endif /* OPENSSL_NO_DEPRECATED_1_0_0 */
+
+# define CRYPTO_set_dynlock_create_callback(dyn_create_function)
+# define CRYPTO_set_dynlock_lock_callback(dyn_lock_function)
+# define CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function)
+# define CRYPTO_get_dynlock_create_callback() (NULL)
+# define CRYPTO_get_dynlock_lock_callback() (NULL)
+# define CRYPTO_get_dynlock_destroy_callback() (NULL)
+# endif /* OPENSSL_NO_DEPRECATED_1_1_0 */
+
+typedef void *(*CRYPTO_malloc_fn)(size_t num, const char *file, int line);
+typedef void *(*CRYPTO_realloc_fn)(void *addr, size_t num, const char *file,
+ int line);
+typedef void (*CRYPTO_free_fn)(void *addr, const char *file, int line);
+int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
+ CRYPTO_realloc_fn realloc_fn,
+ CRYPTO_free_fn free_fn);
+void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
+ CRYPTO_realloc_fn *realloc_fn,
+ CRYPTO_free_fn *free_fn);
+
+void *CRYPTO_malloc(size_t num, const char *file, int line);
+void *CRYPTO_zalloc(size_t num, const char *file, int line);
+void *CRYPTO_memdup(const void *str, size_t siz, const char *file, int line);
+char *CRYPTO_strdup(const char *str, const char *file, int line);
+char *CRYPTO_strndup(const char *str, size_t s, const char *file, int line);
+void CRYPTO_free(void *ptr, const char *file, int line);
+void CRYPTO_clear_free(void *ptr, size_t num, const char *file, int line);
+void *CRYPTO_realloc(void *addr, size_t num, const char *file, int line);
+void *CRYPTO_clear_realloc(void *addr, size_t old_num, size_t num,
+ const char *file, int line);
+
+int CRYPTO_secure_malloc_init(size_t sz, size_t minsize);
+int CRYPTO_secure_malloc_done(void);
+void *CRYPTO_secure_malloc(size_t num, const char *file, int line);
+void *CRYPTO_secure_zalloc(size_t num, const char *file, int line);
+void CRYPTO_secure_free(void *ptr, const char *file, int line);
+void CRYPTO_secure_clear_free(void *ptr, size_t num,
+ const char *file, int line);
+int CRYPTO_secure_allocated(const void *ptr);
+int CRYPTO_secure_malloc_initialized(void);
+size_t CRYPTO_secure_actual_size(void *ptr);
+size_t CRYPTO_secure_used(void);
+
+void OPENSSL_cleanse(void *ptr, size_t len);
+
+# ifndef OPENSSL_NO_CRYPTO_MDEBUG
+/*
+ * The following can be used to detect memory leaks in the library. If
+ * used, it turns on malloc checking
+ */
+# define CRYPTO_MEM_CHECK_OFF 0x0 /* Control only */
+# define CRYPTO_MEM_CHECK_ON 0x1 /* Control and mode bit */
+# define CRYPTO_MEM_CHECK_ENABLE 0x2 /* Control and mode bit */
+# define CRYPTO_MEM_CHECK_DISABLE 0x3 /* Control only */
+
+void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define OPENSSL_mem_debug_push(info) \
+ CRYPTO_mem_debug_push(info, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_mem_debug_pop() \
+ CRYPTO_mem_debug_pop()
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_set_mem_debug(int flag);
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_ctrl(int mode);
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_debug_push(const char *info,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_debug_pop(void);
+OSSL_DEPRECATEDIN_3_0 void CRYPTO_mem_debug_malloc(void *addr, size_t num,
+ int flag,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2,
+ size_t num, int flag,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0 void CRYPTO_mem_debug_free(void *addr, int flag,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0
+int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
+ void *u);
+# endif
+# ifndef OPENSSL_NO_STDIO
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_leaks_fp(FILE *);
+# endif
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_leaks(BIO *bio);
+# endif
+# endif /* OPENSSL_NO_CRYPTO_MDEBUG */
+
+/* die if we have to */
+ossl_noreturn void OPENSSL_die(const char *assertion, const char *file, int line);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OpenSSLDie(f,l,a) OPENSSL_die((a),(f),(l))
+# endif
+# define OPENSSL_assert(e) \
+ (void)((e) ? 0 : (OPENSSL_die("assertion failed: " #e, OPENSSL_FILE, OPENSSL_LINE), 1))
+
+int OPENSSL_isservice(void);
+
+void OPENSSL_init(void);
+# ifdef OPENSSL_SYS_UNIX
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void OPENSSL_fork_prepare(void);
+OSSL_DEPRECATEDIN_3_0 void OPENSSL_fork_parent(void);
+OSSL_DEPRECATEDIN_3_0 void OPENSSL_fork_child(void);
+# endif
+# endif
+
+struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result);
+int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, long offset_sec);
+int OPENSSL_gmtime_diff(int *pday, int *psec,
+ const struct tm *from, const struct tm *to);
+
+/*
+ * CRYPTO_memcmp returns zero iff the |len| bytes at |a| and |b| are equal.
+ * It takes an amount of time dependent on |len|, but independent of the
+ * contents of |a| and |b|. Unlike memcmp, it cannot be used to put elements
+ * into a defined order as the return value when a != b is undefined, other
+ * than to be non-zero.
+ */
+int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len);
+
+/* Standard initialisation options */
+# define OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS 0x00000001L
+# define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
+# define OPENSSL_INIT_ADD_ALL_CIPHERS 0x00000004L
+# define OPENSSL_INIT_ADD_ALL_DIGESTS 0x00000008L
+# define OPENSSL_INIT_NO_ADD_ALL_CIPHERS 0x00000010L
+# define OPENSSL_INIT_NO_ADD_ALL_DIGESTS 0x00000020L
+# define OPENSSL_INIT_LOAD_CONFIG 0x00000040L
+# define OPENSSL_INIT_NO_LOAD_CONFIG 0x00000080L
+# define OPENSSL_INIT_ASYNC 0x00000100L
+# define OPENSSL_INIT_ENGINE_RDRAND 0x00000200L
+# define OPENSSL_INIT_ENGINE_DYNAMIC 0x00000400L
+# define OPENSSL_INIT_ENGINE_OPENSSL 0x00000800L
+# define OPENSSL_INIT_ENGINE_CRYPTODEV 0x00001000L
+# define OPENSSL_INIT_ENGINE_CAPI 0x00002000L
+# define OPENSSL_INIT_ENGINE_PADLOCK 0x00004000L
+# define OPENSSL_INIT_ENGINE_AFALG 0x00008000L
+/* FREE: 0x00010000L */
+# define OPENSSL_INIT_ATFORK 0x00020000L
+/* OPENSSL_INIT_BASE_ONLY 0x00040000L */
+# define OPENSSL_INIT_NO_ATEXIT 0x00080000L
+/* OPENSSL_INIT flag range 0x03f00000 reserved for OPENSSL_init_ssl() */
+/* FREE: 0x04000000L */
+/* FREE: 0x08000000L */
+/* FREE: 0x10000000L */
+/* FREE: 0x20000000L */
+/* FREE: 0x40000000L */
+/* FREE: 0x80000000L */
+/* Max OPENSSL_INIT flag value is 0x80000000 */
+
+/* openssl and dasync not counted as builtin */
+# define OPENSSL_INIT_ENGINE_ALL_BUILTIN \
+ (OPENSSL_INIT_ENGINE_RDRAND | OPENSSL_INIT_ENGINE_DYNAMIC \
+ | OPENSSL_INIT_ENGINE_CRYPTODEV | OPENSSL_INIT_ENGINE_CAPI | \
+ OPENSSL_INIT_ENGINE_PADLOCK)
+
+/* Library initialisation functions */
+void OPENSSL_cleanup(void);
+int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings);
+int OPENSSL_atexit(void (*handler)(void));
+void OPENSSL_thread_stop(void);
+void OPENSSL_thread_stop_ex(OSSL_LIB_CTX *ctx);
+
+/* Low-level control of initialization */
+OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void);
+# ifndef OPENSSL_NO_STDIO
+int OPENSSL_INIT_set_config_filename(OPENSSL_INIT_SETTINGS *settings,
+ const char *config_filename);
+void OPENSSL_INIT_set_config_file_flags(OPENSSL_INIT_SETTINGS *settings,
+ unsigned long flags);
+int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *settings,
+ const char *config_appname);
+# endif
+void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *settings);
+
+# if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG)
+# if defined(_WIN32)
+# if defined(BASETYPES) || defined(_WINDEF_H)
+/* application has to include <windows.h> in order to use this */
+typedef DWORD CRYPTO_THREAD_LOCAL;
+typedef DWORD CRYPTO_THREAD_ID;
+
+typedef LONG CRYPTO_ONCE;
+# define CRYPTO_ONCE_STATIC_INIT 0
+# endif
+# else
+# if defined(__TANDEM) && defined(_SPT_MODEL_)
+# define SPT_THREAD_SIGNAL 1
+# define SPT_THREAD_AWARE 1
+# include <spthread.h>
+# else
+# include <pthread.h>
+# endif
+typedef pthread_once_t CRYPTO_ONCE;
+typedef pthread_key_t CRYPTO_THREAD_LOCAL;
+typedef pthread_t CRYPTO_THREAD_ID;
+
+# define CRYPTO_ONCE_STATIC_INIT PTHREAD_ONCE_INIT
+# endif
+# endif
+
+# if !defined(CRYPTO_ONCE_STATIC_INIT)
+typedef unsigned int CRYPTO_ONCE;
+typedef unsigned int CRYPTO_THREAD_LOCAL;
+typedef unsigned int CRYPTO_THREAD_ID;
+# define CRYPTO_ONCE_STATIC_INIT 0
+# endif
+
+int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void));
+
+int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *));
+void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key);
+int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val);
+int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key);
+
+CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void);
+int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b);
+
+OSSL_LIB_CTX *OSSL_LIB_CTX_new(void);
+OSSL_LIB_CTX *OSSL_LIB_CTX_new_from_dispatch(const OSSL_CORE_HANDLE *handle,
+ const OSSL_DISPATCH *in);
+OSSL_LIB_CTX *OSSL_LIB_CTX_new_child(const OSSL_CORE_HANDLE *handle,
+ const OSSL_DISPATCH *in);
+int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file);
+void OSSL_LIB_CTX_free(OSSL_LIB_CTX *);
+OSSL_LIB_CTX *OSSL_LIB_CTX_get0_global_default(void);
+OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *libctx);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/crypto.h.in b/include/openssl/crypto.h.in
new file mode 100644
index 00000000..724e2ca5
--- /dev/null
+++ b/include/openssl/crypto.h.in
@@ -0,0 +1,533 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_CRYPTO_H
+# define OPENSSL_CRYPTO_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CRYPTO_H
+# endif
+
+# include <stdlib.h>
+# include <time.h>
+
+# include <openssl/e_os2.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+
+# include <openssl/safestack.h>
+# include <openssl/opensslv.h>
+# include <openssl/types.h>
+# include <openssl/opensslconf.h>
+# include <openssl/cryptoerr.h>
+# include <openssl/core.h>
+
+# ifdef CHARSET_EBCDIC
+# include <openssl/ebcdic.h>
+# endif
+
+/*
+ * Resolve problems on some operating systems with symbol names that clash
+ * one way or another
+ */
+# include <openssl/symhacks.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/opensslv.h>
+# endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSLeay OpenSSL_version_num
+# define SSLeay_version OpenSSL_version
+# define SSLEAY_VERSION_NUMBER OPENSSL_VERSION_NUMBER
+# define SSLEAY_VERSION OPENSSL_VERSION
+# define SSLEAY_CFLAGS OPENSSL_CFLAGS
+# define SSLEAY_BUILT_ON OPENSSL_BUILT_ON
+# define SSLEAY_PLATFORM OPENSSL_PLATFORM
+# define SSLEAY_DIR OPENSSL_DIR
+
+/*
+ * Old type for allocating dynamic locks. No longer used. Use the new thread
+ * API instead.
+ */
+typedef struct {
+ int dummy;
+} CRYPTO_dynlock;
+
+# endif /* OPENSSL_NO_DEPRECATED_1_1_0 */
+
+typedef void CRYPTO_RWLOCK;
+
+CRYPTO_RWLOCK *CRYPTO_THREAD_lock_new(void);
+__owur int CRYPTO_THREAD_read_lock(CRYPTO_RWLOCK *lock);
+__owur int CRYPTO_THREAD_write_lock(CRYPTO_RWLOCK *lock);
+int CRYPTO_THREAD_unlock(CRYPTO_RWLOCK *lock);
+void CRYPTO_THREAD_lock_free(CRYPTO_RWLOCK *lock);
+
+int CRYPTO_atomic_add(int *val, int amount, int *ret, CRYPTO_RWLOCK *lock);
+int CRYPTO_atomic_or(uint64_t *val, uint64_t op, uint64_t *ret,
+ CRYPTO_RWLOCK *lock);
+int CRYPTO_atomic_load(uint64_t *val, uint64_t *ret, CRYPTO_RWLOCK *lock);
+
+/* No longer needed, so this is a no-op */
+#define OPENSSL_malloc_init() while(0) continue
+
+# define OPENSSL_malloc(num) \
+ CRYPTO_malloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_zalloc(num) \
+ CRYPTO_zalloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_realloc(addr, num) \
+ CRYPTO_realloc(addr, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_clear_realloc(addr, old_num, num) \
+ CRYPTO_clear_realloc(addr, old_num, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_clear_free(addr, num) \
+ CRYPTO_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_free(addr) \
+ CRYPTO_free(addr, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_memdup(str, s) \
+ CRYPTO_memdup((str), s, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_strdup(str) \
+ CRYPTO_strdup(str, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_strndup(str, n) \
+ CRYPTO_strndup(str, n, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_malloc(num) \
+ CRYPTO_secure_malloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_zalloc(num) \
+ CRYPTO_secure_zalloc(num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_free(addr) \
+ CRYPTO_secure_free(addr, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_clear_free(addr, num) \
+ CRYPTO_secure_clear_free(addr, num, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_secure_actual_size(ptr) \
+ CRYPTO_secure_actual_size(ptr)
+
+size_t OPENSSL_strlcpy(char *dst, const char *src, size_t siz);
+size_t OPENSSL_strlcat(char *dst, const char *src, size_t siz);
+size_t OPENSSL_strnlen(const char *str, size_t maxlen);
+int OPENSSL_buf2hexstr_ex(char *str, size_t str_n, size_t *strlen,
+ const unsigned char *buf, size_t buflen,
+ const char sep);
+char *OPENSSL_buf2hexstr(const unsigned char *buf, long buflen);
+int OPENSSL_hexstr2buf_ex(unsigned char *buf, size_t buf_n, size_t *buflen,
+ const char *str, const char sep);
+unsigned char *OPENSSL_hexstr2buf(const char *str, long *buflen);
+int OPENSSL_hexchar2int(unsigned char c);
+
+# define OPENSSL_MALLOC_MAX_NELEMS(type) (((1U<<(sizeof(int)*8-1))-1)/sizeof(type))
+
+/*
+ * These functions return the values of OPENSSL_VERSION_MAJOR,
+ * OPENSSL_VERSION_MINOR, OPENSSL_VERSION_PATCH, OPENSSL_VERSION_PRE_RELEASE
+ * and OPENSSL_VERSION_BUILD_METADATA, respectively.
+ */
+unsigned int OPENSSL_version_major(void);
+unsigned int OPENSSL_version_minor(void);
+unsigned int OPENSSL_version_patch(void);
+const char *OPENSSL_version_pre_release(void);
+const char *OPENSSL_version_build_metadata(void);
+
+unsigned long OpenSSL_version_num(void);
+const char *OpenSSL_version(int type);
+# define OPENSSL_VERSION 0
+# define OPENSSL_CFLAGS 1
+# define OPENSSL_BUILT_ON 2
+# define OPENSSL_PLATFORM 3
+# define OPENSSL_DIR 4
+# define OPENSSL_ENGINES_DIR 5
+# define OPENSSL_VERSION_STRING 6
+# define OPENSSL_FULL_VERSION_STRING 7
+# define OPENSSL_MODULES_DIR 8
+# define OPENSSL_CPU_INFO 9
+
+const char *OPENSSL_info(int type);
+/*
+ * The series starts at 1001 to avoid confusion with the OpenSSL_version
+ * types.
+ */
+# define OPENSSL_INFO_CONFIG_DIR 1001
+# define OPENSSL_INFO_ENGINES_DIR 1002
+# define OPENSSL_INFO_MODULES_DIR 1003
+# define OPENSSL_INFO_DSO_EXTENSION 1004
+# define OPENSSL_INFO_DIR_FILENAME_SEPARATOR 1005
+# define OPENSSL_INFO_LIST_SEPARATOR 1006
+# define OPENSSL_INFO_SEED_SOURCE 1007
+# define OPENSSL_INFO_CPU_SETTINGS 1008
+
+int OPENSSL_issetugid(void);
+
+struct crypto_ex_data_st {
+ OSSL_LIB_CTX *ctx;
+ STACK_OF(void) *sk;
+};
+
+{-
+ generate_stack_macros("void");
+-}
+
+
+/*
+ * Per class, we have a STACK of function pointers.
+ */
+# define CRYPTO_EX_INDEX_SSL 0
+# define CRYPTO_EX_INDEX_SSL_CTX 1
+# define CRYPTO_EX_INDEX_SSL_SESSION 2
+# define CRYPTO_EX_INDEX_X509 3
+# define CRYPTO_EX_INDEX_X509_STORE 4
+# define CRYPTO_EX_INDEX_X509_STORE_CTX 5
+# define CRYPTO_EX_INDEX_DH 6
+# define CRYPTO_EX_INDEX_DSA 7
+# define CRYPTO_EX_INDEX_EC_KEY 8
+# define CRYPTO_EX_INDEX_RSA 9
+# define CRYPTO_EX_INDEX_ENGINE 10
+# define CRYPTO_EX_INDEX_UI 11
+# define CRYPTO_EX_INDEX_BIO 12
+# define CRYPTO_EX_INDEX_APP 13
+# define CRYPTO_EX_INDEX_UI_METHOD 14
+# define CRYPTO_EX_INDEX_RAND_DRBG 15
+# define CRYPTO_EX_INDEX_DRBG CRYPTO_EX_INDEX_RAND_DRBG
+# define CRYPTO_EX_INDEX_OSSL_LIB_CTX 16
+# define CRYPTO_EX_INDEX_EVP_PKEY 17
+# define CRYPTO_EX_INDEX__COUNT 18
+
+typedef void CRYPTO_EX_new (void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+ int idx, long argl, void *argp);
+typedef void CRYPTO_EX_free (void *parent, void *ptr, CRYPTO_EX_DATA *ad,
+ int idx, long argl, void *argp);
+typedef int CRYPTO_EX_dup (CRYPTO_EX_DATA *to, const CRYPTO_EX_DATA *from,
+ void **from_d, int idx, long argl, void *argp);
+__owur int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
+ CRYPTO_EX_new *new_func,
+ CRYPTO_EX_dup *dup_func,
+ CRYPTO_EX_free *free_func);
+/* No longer use an index. */
+int CRYPTO_free_ex_index(int class_index, int idx);
+
+/*
+ * Initialise/duplicate/free CRYPTO_EX_DATA variables corresponding to a
+ * given class (invokes whatever per-class callbacks are applicable)
+ */
+int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
+int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
+ const CRYPTO_EX_DATA *from);
+
+void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad);
+
+/* Allocate a single item in the CRYPTO_EX_DATA variable */
+int CRYPTO_alloc_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad,
+ int idx);
+
+/*
+ * Get/set data in a CRYPTO_EX_DATA variable corresponding to a particular
+ * index (relative to the class type involved)
+ */
+int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val);
+void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/*
+ * This function cleans up all "ex_data" state. It mustn't be called under
+ * potential race-conditions.
+ */
+# define CRYPTO_cleanup_all_ex_data() while(0) continue
+
+/*
+ * The old locking functions have been removed completely without compatibility
+ * macros. This is because the old functions either could not properly report
+ * errors, or the returned error values were not clearly documented.
+ * Replacing the locking functions with no-ops would cause race condition
+ * issues in the affected applications. It is far better for them to fail at
+ * compile time.
+ * On the other hand, the locking callbacks are no longer used. Consequently,
+ * the callback management functions can be safely replaced with no-op macros.
+ */
+# define CRYPTO_num_locks() (1)
+# define CRYPTO_set_locking_callback(func)
+# define CRYPTO_get_locking_callback() (NULL)
+# define CRYPTO_set_add_lock_callback(func)
+# define CRYPTO_get_add_lock_callback() (NULL)
+
+/*
+ * These defines where used in combination with the old locking callbacks,
+ * they are not called anymore, but old code that's not called might still
+ * use them.
+ */
+# define CRYPTO_LOCK 1
+# define CRYPTO_UNLOCK 2
+# define CRYPTO_READ 4
+# define CRYPTO_WRITE 8
+
+/* This structure is no longer used */
+typedef struct crypto_threadid_st {
+ int dummy;
+} CRYPTO_THREADID;
+/* Only use CRYPTO_THREADID_set_[numeric|pointer]() within callbacks */
+# define CRYPTO_THREADID_set_numeric(id, val)
+# define CRYPTO_THREADID_set_pointer(id, ptr)
+# define CRYPTO_THREADID_set_callback(threadid_func) (0)
+# define CRYPTO_THREADID_get_callback() (NULL)
+# define CRYPTO_THREADID_current(id)
+# define CRYPTO_THREADID_cmp(a, b) (-1)
+# define CRYPTO_THREADID_cpy(dest, src)
+# define CRYPTO_THREADID_hash(id) (0UL)
+
+# ifndef OPENSSL_NO_DEPRECATED_1_0_0
+# define CRYPTO_set_id_callback(func)
+# define CRYPTO_get_id_callback() (NULL)
+# define CRYPTO_thread_id() (0UL)
+# endif /* OPENSSL_NO_DEPRECATED_1_0_0 */
+
+# define CRYPTO_set_dynlock_create_callback(dyn_create_function)
+# define CRYPTO_set_dynlock_lock_callback(dyn_lock_function)
+# define CRYPTO_set_dynlock_destroy_callback(dyn_destroy_function)
+# define CRYPTO_get_dynlock_create_callback() (NULL)
+# define CRYPTO_get_dynlock_lock_callback() (NULL)
+# define CRYPTO_get_dynlock_destroy_callback() (NULL)
+# endif /* OPENSSL_NO_DEPRECATED_1_1_0 */
+
+typedef void *(*CRYPTO_malloc_fn)(size_t num, const char *file, int line);
+typedef void *(*CRYPTO_realloc_fn)(void *addr, size_t num, const char *file,
+ int line);
+typedef void (*CRYPTO_free_fn)(void *addr, const char *file, int line);
+int CRYPTO_set_mem_functions(CRYPTO_malloc_fn malloc_fn,
+ CRYPTO_realloc_fn realloc_fn,
+ CRYPTO_free_fn free_fn);
+void CRYPTO_get_mem_functions(CRYPTO_malloc_fn *malloc_fn,
+ CRYPTO_realloc_fn *realloc_fn,
+ CRYPTO_free_fn *free_fn);
+
+void *CRYPTO_malloc(size_t num, const char *file, int line);
+void *CRYPTO_zalloc(size_t num, const char *file, int line);
+void *CRYPTO_memdup(const void *str, size_t siz, const char *file, int line);
+char *CRYPTO_strdup(const char *str, const char *file, int line);
+char *CRYPTO_strndup(const char *str, size_t s, const char *file, int line);
+void CRYPTO_free(void *ptr, const char *file, int line);
+void CRYPTO_clear_free(void *ptr, size_t num, const char *file, int line);
+void *CRYPTO_realloc(void *addr, size_t num, const char *file, int line);
+void *CRYPTO_clear_realloc(void *addr, size_t old_num, size_t num,
+ const char *file, int line);
+
+int CRYPTO_secure_malloc_init(size_t sz, size_t minsize);
+int CRYPTO_secure_malloc_done(void);
+void *CRYPTO_secure_malloc(size_t num, const char *file, int line);
+void *CRYPTO_secure_zalloc(size_t num, const char *file, int line);
+void CRYPTO_secure_free(void *ptr, const char *file, int line);
+void CRYPTO_secure_clear_free(void *ptr, size_t num,
+ const char *file, int line);
+int CRYPTO_secure_allocated(const void *ptr);
+int CRYPTO_secure_malloc_initialized(void);
+size_t CRYPTO_secure_actual_size(void *ptr);
+size_t CRYPTO_secure_used(void);
+
+void OPENSSL_cleanse(void *ptr, size_t len);
+
+# ifndef OPENSSL_NO_CRYPTO_MDEBUG
+/*
+ * The following can be used to detect memory leaks in the library. If
+ * used, it turns on malloc checking
+ */
+# define CRYPTO_MEM_CHECK_OFF 0x0 /* Control only */
+# define CRYPTO_MEM_CHECK_ON 0x1 /* Control and mode bit */
+# define CRYPTO_MEM_CHECK_ENABLE 0x2 /* Control and mode bit */
+# define CRYPTO_MEM_CHECK_DISABLE 0x3 /* Control only */
+
+void CRYPTO_get_alloc_counts(int *mcount, int *rcount, int *fcount);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define OPENSSL_mem_debug_push(info) \
+ CRYPTO_mem_debug_push(info, OPENSSL_FILE, OPENSSL_LINE)
+# define OPENSSL_mem_debug_pop() \
+ CRYPTO_mem_debug_pop()
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_set_mem_debug(int flag);
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_ctrl(int mode);
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_debug_push(const char *info,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_debug_pop(void);
+OSSL_DEPRECATEDIN_3_0 void CRYPTO_mem_debug_malloc(void *addr, size_t num,
+ int flag,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0 void CRYPTO_mem_debug_realloc(void *addr1, void *addr2,
+ size_t num, int flag,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0 void CRYPTO_mem_debug_free(void *addr, int flag,
+ const char *file, int line);
+OSSL_DEPRECATEDIN_3_0
+int CRYPTO_mem_leaks_cb(int (*cb)(const char *str, size_t len, void *u),
+ void *u);
+# endif
+# ifndef OPENSSL_NO_STDIO
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_leaks_fp(FILE *);
+# endif
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int CRYPTO_mem_leaks(BIO *bio);
+# endif
+# endif /* OPENSSL_NO_CRYPTO_MDEBUG */
+
+/* die if we have to */
+ossl_noreturn void OPENSSL_die(const char *assertion, const char *file, int line);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OpenSSLDie(f,l,a) OPENSSL_die((a),(f),(l))
+# endif
+# define OPENSSL_assert(e) \
+ (void)((e) ? 0 : (OPENSSL_die("assertion failed: " #e, OPENSSL_FILE, OPENSSL_LINE), 1))
+
+int OPENSSL_isservice(void);
+
+void OPENSSL_init(void);
+# ifdef OPENSSL_SYS_UNIX
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void OPENSSL_fork_prepare(void);
+OSSL_DEPRECATEDIN_3_0 void OPENSSL_fork_parent(void);
+OSSL_DEPRECATEDIN_3_0 void OPENSSL_fork_child(void);
+# endif
+# endif
+
+struct tm *OPENSSL_gmtime(const time_t *timer, struct tm *result);
+int OPENSSL_gmtime_adj(struct tm *tm, int offset_day, long offset_sec);
+int OPENSSL_gmtime_diff(int *pday, int *psec,
+ const struct tm *from, const struct tm *to);
+
+/*
+ * CRYPTO_memcmp returns zero iff the |len| bytes at |a| and |b| are equal.
+ * It takes an amount of time dependent on |len|, but independent of the
+ * contents of |a| and |b|. Unlike memcmp, it cannot be used to put elements
+ * into a defined order as the return value when a != b is undefined, other
+ * than to be non-zero.
+ */
+int CRYPTO_memcmp(const void * in_a, const void * in_b, size_t len);
+
+/* Standard initialisation options */
+# define OPENSSL_INIT_NO_LOAD_CRYPTO_STRINGS 0x00000001L
+# define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L
+# define OPENSSL_INIT_ADD_ALL_CIPHERS 0x00000004L
+# define OPENSSL_INIT_ADD_ALL_DIGESTS 0x00000008L
+# define OPENSSL_INIT_NO_ADD_ALL_CIPHERS 0x00000010L
+# define OPENSSL_INIT_NO_ADD_ALL_DIGESTS 0x00000020L
+# define OPENSSL_INIT_LOAD_CONFIG 0x00000040L
+# define OPENSSL_INIT_NO_LOAD_CONFIG 0x00000080L
+# define OPENSSL_INIT_ASYNC 0x00000100L
+# define OPENSSL_INIT_ENGINE_RDRAND 0x00000200L
+# define OPENSSL_INIT_ENGINE_DYNAMIC 0x00000400L
+# define OPENSSL_INIT_ENGINE_OPENSSL 0x00000800L
+# define OPENSSL_INIT_ENGINE_CRYPTODEV 0x00001000L
+# define OPENSSL_INIT_ENGINE_CAPI 0x00002000L
+# define OPENSSL_INIT_ENGINE_PADLOCK 0x00004000L
+# define OPENSSL_INIT_ENGINE_AFALG 0x00008000L
+/* FREE: 0x00010000L */
+# define OPENSSL_INIT_ATFORK 0x00020000L
+/* OPENSSL_INIT_BASE_ONLY 0x00040000L */
+# define OPENSSL_INIT_NO_ATEXIT 0x00080000L
+/* OPENSSL_INIT flag range 0x03f00000 reserved for OPENSSL_init_ssl() */
+/* FREE: 0x04000000L */
+/* FREE: 0x08000000L */
+/* FREE: 0x10000000L */
+/* FREE: 0x20000000L */
+/* FREE: 0x40000000L */
+/* FREE: 0x80000000L */
+/* Max OPENSSL_INIT flag value is 0x80000000 */
+
+/* openssl and dasync not counted as builtin */
+# define OPENSSL_INIT_ENGINE_ALL_BUILTIN \
+ (OPENSSL_INIT_ENGINE_RDRAND | OPENSSL_INIT_ENGINE_DYNAMIC \
+ | OPENSSL_INIT_ENGINE_CRYPTODEV | OPENSSL_INIT_ENGINE_CAPI | \
+ OPENSSL_INIT_ENGINE_PADLOCK)
+
+/* Library initialisation functions */
+void OPENSSL_cleanup(void);
+int OPENSSL_init_crypto(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings);
+int OPENSSL_atexit(void (*handler)(void));
+void OPENSSL_thread_stop(void);
+void OPENSSL_thread_stop_ex(OSSL_LIB_CTX *ctx);
+
+/* Low-level control of initialization */
+OPENSSL_INIT_SETTINGS *OPENSSL_INIT_new(void);
+# ifndef OPENSSL_NO_STDIO
+int OPENSSL_INIT_set_config_filename(OPENSSL_INIT_SETTINGS *settings,
+ const char *config_filename);
+void OPENSSL_INIT_set_config_file_flags(OPENSSL_INIT_SETTINGS *settings,
+ unsigned long flags);
+int OPENSSL_INIT_set_config_appname(OPENSSL_INIT_SETTINGS *settings,
+ const char *config_appname);
+# endif
+void OPENSSL_INIT_free(OPENSSL_INIT_SETTINGS *settings);
+
+# if defined(OPENSSL_THREADS) && !defined(CRYPTO_TDEBUG)
+# if defined(_WIN32)
+# if defined(BASETYPES) || defined(_WINDEF_H)
+/* application has to include <windows.h> in order to use this */
+typedef DWORD CRYPTO_THREAD_LOCAL;
+typedef DWORD CRYPTO_THREAD_ID;
+
+typedef LONG CRYPTO_ONCE;
+# define CRYPTO_ONCE_STATIC_INIT 0
+# endif
+# else
+# if defined(__TANDEM) && defined(_SPT_MODEL_)
+# define SPT_THREAD_SIGNAL 1
+# define SPT_THREAD_AWARE 1
+# include <spthread.h>
+# else
+# include <pthread.h>
+# endif
+typedef pthread_once_t CRYPTO_ONCE;
+typedef pthread_key_t CRYPTO_THREAD_LOCAL;
+typedef pthread_t CRYPTO_THREAD_ID;
+
+# define CRYPTO_ONCE_STATIC_INIT PTHREAD_ONCE_INIT
+# endif
+# endif
+
+# if !defined(CRYPTO_ONCE_STATIC_INIT)
+typedef unsigned int CRYPTO_ONCE;
+typedef unsigned int CRYPTO_THREAD_LOCAL;
+typedef unsigned int CRYPTO_THREAD_ID;
+# define CRYPTO_ONCE_STATIC_INIT 0
+# endif
+
+int CRYPTO_THREAD_run_once(CRYPTO_ONCE *once, void (*init)(void));
+
+int CRYPTO_THREAD_init_local(CRYPTO_THREAD_LOCAL *key, void (*cleanup)(void *));
+void *CRYPTO_THREAD_get_local(CRYPTO_THREAD_LOCAL *key);
+int CRYPTO_THREAD_set_local(CRYPTO_THREAD_LOCAL *key, void *val);
+int CRYPTO_THREAD_cleanup_local(CRYPTO_THREAD_LOCAL *key);
+
+CRYPTO_THREAD_ID CRYPTO_THREAD_get_current_id(void);
+int CRYPTO_THREAD_compare_id(CRYPTO_THREAD_ID a, CRYPTO_THREAD_ID b);
+
+OSSL_LIB_CTX *OSSL_LIB_CTX_new(void);
+OSSL_LIB_CTX *OSSL_LIB_CTX_new_from_dispatch(const OSSL_CORE_HANDLE *handle,
+ const OSSL_DISPATCH *in);
+OSSL_LIB_CTX *OSSL_LIB_CTX_new_child(const OSSL_CORE_HANDLE *handle,
+ const OSSL_DISPATCH *in);
+int OSSL_LIB_CTX_load_config(OSSL_LIB_CTX *ctx, const char *config_file);
+void OSSL_LIB_CTX_free(OSSL_LIB_CTX *);
+OSSL_LIB_CTX *OSSL_LIB_CTX_get0_global_default(void);
+OSSL_LIB_CTX *OSSL_LIB_CTX_set0_default(OSSL_LIB_CTX *libctx);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/cryptoerr.h b/include/openssl/cryptoerr.h
new file mode 100644
index 00000000..c6a04d9b
--- /dev/null
+++ b/include/openssl/cryptoerr.h
@@ -0,0 +1,46 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CRYPTOERR_H
+# define OPENSSL_CRYPTOERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * CRYPTO reason codes.
+ */
+# define CRYPTO_R_BAD_ALGORITHM_NAME 117
+# define CRYPTO_R_CONFLICTING_NAMES 118
+# define CRYPTO_R_HEX_STRING_TOO_SHORT 121
+# define CRYPTO_R_ILLEGAL_HEX_DIGIT 102
+# define CRYPTO_R_INSUFFICIENT_DATA_SPACE 106
+# define CRYPTO_R_INSUFFICIENT_PARAM_SIZE 107
+# define CRYPTO_R_INSUFFICIENT_SECURE_DATA_SPACE 108
+# define CRYPTO_R_INVALID_NEGATIVE_VALUE 122
+# define CRYPTO_R_INVALID_NULL_ARGUMENT 109
+# define CRYPTO_R_INVALID_OSSL_PARAM_TYPE 110
+# define CRYPTO_R_ODD_NUMBER_OF_DIGITS 103
+# define CRYPTO_R_PROVIDER_ALREADY_EXISTS 104
+# define CRYPTO_R_PROVIDER_SECTION_ERROR 105
+# define CRYPTO_R_RANDOM_SECTION_ERROR 119
+# define CRYPTO_R_SECURE_MALLOC_FAILURE 111
+# define CRYPTO_R_STRING_TOO_LONG 112
+# define CRYPTO_R_TOO_MANY_BYTES 113
+# define CRYPTO_R_TOO_MANY_RECORDS 114
+# define CRYPTO_R_TOO_SMALL_BUFFER 116
+# define CRYPTO_R_UNKNOWN_NAME_IN_RANDOM_SECTION 120
+# define CRYPTO_R_ZERO_LENGTH_NUMBER 115
+
+#endif
diff --git a/include/openssl/cryptoerr_legacy.h b/include/openssl/cryptoerr_legacy.h
new file mode 100644
index 00000000..ccab33a5
--- /dev/null
+++ b/include/openssl/cryptoerr_legacy.h
@@ -0,0 +1,1466 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This header file preserves symbols from pre-3.0 OpenSSL.
+ * It should never be included directly, as it's already included
+ * by the public {lib}err.h headers, and since it will go away some
+ * time in the future.
+ */
+
+#ifndef OPENSSL_CRYPTOERR_LEGACY_H
+# define OPENSSL_CRYPTOERR_LEGACY_H
+# pragma once
+
+# include <openssl/macros.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ERR_load_ASN1_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_ASYNC_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_BIO_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_BN_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_BUF_strings(void);
+# ifndef OPENSSL_NO_CMS
+OSSL_DEPRECATEDIN_3_0 int ERR_load_CMS_strings(void);
+# endif
+# ifndef OPENSSL_NO_COMP
+OSSL_DEPRECATEDIN_3_0 int ERR_load_COMP_strings(void);
+# endif
+OSSL_DEPRECATEDIN_3_0 int ERR_load_CONF_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_CRYPTO_strings(void);
+# ifndef OPENSSL_NO_CT
+OSSL_DEPRECATEDIN_3_0 int ERR_load_CT_strings(void);
+# endif
+# ifndef OPENSSL_NO_DH
+OSSL_DEPRECATEDIN_3_0 int ERR_load_DH_strings(void);
+# endif
+# ifndef OPENSSL_NO_DSA
+OSSL_DEPRECATEDIN_3_0 int ERR_load_DSA_strings(void);
+# endif
+# ifndef OPENSSL_NO_EC
+OSSL_DEPRECATEDIN_3_0 int ERR_load_EC_strings(void);
+# endif
+# ifndef OPENSSL_NO_ENGINE
+OSSL_DEPRECATEDIN_3_0 int ERR_load_ENGINE_strings(void);
+# endif
+OSSL_DEPRECATEDIN_3_0 int ERR_load_ERR_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_EVP_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_KDF_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_OBJ_strings(void);
+# ifndef OPENSSL_NO_OCSP
+OSSL_DEPRECATEDIN_3_0 int ERR_load_OCSP_strings(void);
+# endif
+OSSL_DEPRECATEDIN_3_0 int ERR_load_PEM_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_PKCS12_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_PKCS7_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_RAND_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_RSA_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_OSSL_STORE_strings(void);
+# ifndef OPENSSL_NO_TS
+OSSL_DEPRECATEDIN_3_0 int ERR_load_TS_strings(void);
+# endif
+OSSL_DEPRECATEDIN_3_0 int ERR_load_UI_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_X509_strings(void);
+OSSL_DEPRECATEDIN_3_0 int ERR_load_X509V3_strings(void);
+
+/* Collected _F_ macros from OpenSSL 1.1.1 */
+
+/*
+ * ASN1 function codes.
+ */
+# define ASN1_F_A2D_ASN1_OBJECT 0
+# define ASN1_F_A2I_ASN1_INTEGER 0
+# define ASN1_F_A2I_ASN1_STRING 0
+# define ASN1_F_APPEND_EXP 0
+# define ASN1_F_ASN1_BIO_INIT 0
+# define ASN1_F_ASN1_BIT_STRING_SET_BIT 0
+# define ASN1_F_ASN1_CB 0
+# define ASN1_F_ASN1_CHECK_TLEN 0
+# define ASN1_F_ASN1_COLLECT 0
+# define ASN1_F_ASN1_D2I_EX_PRIMITIVE 0
+# define ASN1_F_ASN1_D2I_FP 0
+# define ASN1_F_ASN1_D2I_READ_BIO 0
+# define ASN1_F_ASN1_DIGEST 0
+# define ASN1_F_ASN1_DO_ADB 0
+# define ASN1_F_ASN1_DO_LOCK 0
+# define ASN1_F_ASN1_DUP 0
+# define ASN1_F_ASN1_ENC_SAVE 0
+# define ASN1_F_ASN1_EX_C2I 0
+# define ASN1_F_ASN1_FIND_END 0
+# define ASN1_F_ASN1_GENERALIZEDTIME_ADJ 0
+# define ASN1_F_ASN1_GENERATE_V3 0
+# define ASN1_F_ASN1_GET_INT64 0
+# define ASN1_F_ASN1_GET_OBJECT 0
+# define ASN1_F_ASN1_GET_UINT64 0
+# define ASN1_F_ASN1_I2D_BIO 0
+# define ASN1_F_ASN1_I2D_FP 0
+# define ASN1_F_ASN1_ITEM_D2I_FP 0
+# define ASN1_F_ASN1_ITEM_DUP 0
+# define ASN1_F_ASN1_ITEM_EMBED_D2I 0
+# define ASN1_F_ASN1_ITEM_EMBED_NEW 0
+# define ASN1_F_ASN1_ITEM_FLAGS_I2D 0
+# define ASN1_F_ASN1_ITEM_I2D_BIO 0
+# define ASN1_F_ASN1_ITEM_I2D_FP 0
+# define ASN1_F_ASN1_ITEM_PACK 0
+# define ASN1_F_ASN1_ITEM_SIGN 0
+# define ASN1_F_ASN1_ITEM_SIGN_CTX 0
+# define ASN1_F_ASN1_ITEM_UNPACK 0
+# define ASN1_F_ASN1_ITEM_VERIFY 0
+# define ASN1_F_ASN1_MBSTRING_NCOPY 0
+# define ASN1_F_ASN1_OBJECT_NEW 0
+# define ASN1_F_ASN1_OUTPUT_DATA 0
+# define ASN1_F_ASN1_PCTX_NEW 0
+# define ASN1_F_ASN1_PRIMITIVE_NEW 0
+# define ASN1_F_ASN1_SCTX_NEW 0
+# define ASN1_F_ASN1_SIGN 0
+# define ASN1_F_ASN1_STR2TYPE 0
+# define ASN1_F_ASN1_STRING_GET_INT64 0
+# define ASN1_F_ASN1_STRING_GET_UINT64 0
+# define ASN1_F_ASN1_STRING_SET 0
+# define ASN1_F_ASN1_STRING_TABLE_ADD 0
+# define ASN1_F_ASN1_STRING_TO_BN 0
+# define ASN1_F_ASN1_STRING_TYPE_NEW 0
+# define ASN1_F_ASN1_TEMPLATE_EX_D2I 0
+# define ASN1_F_ASN1_TEMPLATE_NEW 0
+# define ASN1_F_ASN1_TEMPLATE_NOEXP_D2I 0
+# define ASN1_F_ASN1_TIME_ADJ 0
+# define ASN1_F_ASN1_TYPE_GET_INT_OCTETSTRING 0
+# define ASN1_F_ASN1_TYPE_GET_OCTETSTRING 0
+# define ASN1_F_ASN1_UTCTIME_ADJ 0
+# define ASN1_F_ASN1_VERIFY 0
+# define ASN1_F_B64_READ_ASN1 0
+# define ASN1_F_B64_WRITE_ASN1 0
+# define ASN1_F_BIO_NEW_NDEF 0
+# define ASN1_F_BITSTR_CB 0
+# define ASN1_F_BN_TO_ASN1_STRING 0
+# define ASN1_F_C2I_ASN1_BIT_STRING 0
+# define ASN1_F_C2I_ASN1_INTEGER 0
+# define ASN1_F_C2I_ASN1_OBJECT 0
+# define ASN1_F_C2I_IBUF 0
+# define ASN1_F_C2I_UINT64_INT 0
+# define ASN1_F_COLLECT_DATA 0
+# define ASN1_F_D2I_ASN1_OBJECT 0
+# define ASN1_F_D2I_ASN1_UINTEGER 0
+# define ASN1_F_D2I_AUTOPRIVATEKEY 0
+# define ASN1_F_D2I_PRIVATEKEY 0
+# define ASN1_F_D2I_PUBLICKEY 0
+# define ASN1_F_DO_BUF 0
+# define ASN1_F_DO_CREATE 0
+# define ASN1_F_DO_DUMP 0
+# define ASN1_F_DO_TCREATE 0
+# define ASN1_F_I2A_ASN1_OBJECT 0
+# define ASN1_F_I2D_ASN1_BIO_STREAM 0
+# define ASN1_F_I2D_ASN1_OBJECT 0
+# define ASN1_F_I2D_DSA_PUBKEY 0
+# define ASN1_F_I2D_EC_PUBKEY 0
+# define ASN1_F_I2D_PRIVATEKEY 0
+# define ASN1_F_I2D_PUBLICKEY 0
+# define ASN1_F_I2D_RSA_PUBKEY 0
+# define ASN1_F_LONG_C2I 0
+# define ASN1_F_NDEF_PREFIX 0
+# define ASN1_F_NDEF_SUFFIX 0
+# define ASN1_F_OID_MODULE_INIT 0
+# define ASN1_F_PARSE_TAGGING 0
+# define ASN1_F_PKCS5_PBE2_SET_IV 0
+# define ASN1_F_PKCS5_PBE2_SET_SCRYPT 0
+# define ASN1_F_PKCS5_PBE_SET 0
+# define ASN1_F_PKCS5_PBE_SET0_ALGOR 0
+# define ASN1_F_PKCS5_PBKDF2_SET 0
+# define ASN1_F_PKCS5_SCRYPT_SET 0
+# define ASN1_F_SMIME_READ_ASN1 0
+# define ASN1_F_SMIME_TEXT 0
+# define ASN1_F_STABLE_GET 0
+# define ASN1_F_STBL_MODULE_INIT 0
+# define ASN1_F_UINT32_C2I 0
+# define ASN1_F_UINT32_NEW 0
+# define ASN1_F_UINT64_C2I 0
+# define ASN1_F_UINT64_NEW 0
+# define ASN1_F_X509_CRL_ADD0_REVOKED 0
+# define ASN1_F_X509_INFO_NEW 0
+# define ASN1_F_X509_NAME_ENCODE 0
+# define ASN1_F_X509_NAME_EX_D2I 0
+# define ASN1_F_X509_NAME_EX_NEW 0
+# define ASN1_F_X509_PKEY_NEW 0
+
+/*
+ * ASYNC function codes.
+ */
+# define ASYNC_F_ASYNC_CTX_NEW 0
+# define ASYNC_F_ASYNC_INIT_THREAD 0
+# define ASYNC_F_ASYNC_JOB_NEW 0
+# define ASYNC_F_ASYNC_PAUSE_JOB 0
+# define ASYNC_F_ASYNC_START_FUNC 0
+# define ASYNC_F_ASYNC_START_JOB 0
+# define ASYNC_F_ASYNC_WAIT_CTX_SET_WAIT_FD 0
+
+/*
+ * BIO function codes.
+ */
+# define BIO_F_ACPT_STATE 0
+# define BIO_F_ADDRINFO_WRAP 0
+# define BIO_F_ADDR_STRINGS 0
+# define BIO_F_BIO_ACCEPT 0
+# define BIO_F_BIO_ACCEPT_EX 0
+# define BIO_F_BIO_ACCEPT_NEW 0
+# define BIO_F_BIO_ADDR_NEW 0
+# define BIO_F_BIO_BIND 0
+# define BIO_F_BIO_CALLBACK_CTRL 0
+# define BIO_F_BIO_CONNECT 0
+# define BIO_F_BIO_CONNECT_NEW 0
+# define BIO_F_BIO_CTRL 0
+# define BIO_F_BIO_GETS 0
+# define BIO_F_BIO_GET_HOST_IP 0
+# define BIO_F_BIO_GET_NEW_INDEX 0
+# define BIO_F_BIO_GET_PORT 0
+# define BIO_F_BIO_LISTEN 0
+# define BIO_F_BIO_LOOKUP 0
+# define BIO_F_BIO_LOOKUP_EX 0
+# define BIO_F_BIO_MAKE_PAIR 0
+# define BIO_F_BIO_METH_NEW 0
+# define BIO_F_BIO_NEW 0
+# define BIO_F_BIO_NEW_DGRAM_SCTP 0
+# define BIO_F_BIO_NEW_FILE 0
+# define BIO_F_BIO_NEW_MEM_BUF 0
+# define BIO_F_BIO_NREAD 0
+# define BIO_F_BIO_NREAD0 0
+# define BIO_F_BIO_NWRITE 0
+# define BIO_F_BIO_NWRITE0 0
+# define BIO_F_BIO_PARSE_HOSTSERV 0
+# define BIO_F_BIO_PUTS 0
+# define BIO_F_BIO_READ 0
+# define BIO_F_BIO_READ_EX 0
+# define BIO_F_BIO_READ_INTERN 0
+# define BIO_F_BIO_SOCKET 0
+# define BIO_F_BIO_SOCKET_NBIO 0
+# define BIO_F_BIO_SOCK_INFO 0
+# define BIO_F_BIO_SOCK_INIT 0
+# define BIO_F_BIO_WRITE 0
+# define BIO_F_BIO_WRITE_EX 0
+# define BIO_F_BIO_WRITE_INTERN 0
+# define BIO_F_BUFFER_CTRL 0
+# define BIO_F_CONN_CTRL 0
+# define BIO_F_CONN_STATE 0
+# define BIO_F_DGRAM_SCTP_NEW 0
+# define BIO_F_DGRAM_SCTP_READ 0
+# define BIO_F_DGRAM_SCTP_WRITE 0
+# define BIO_F_DOAPR_OUTCH 0
+# define BIO_F_FILE_CTRL 0
+# define BIO_F_FILE_READ 0
+# define BIO_F_LINEBUFFER_CTRL 0
+# define BIO_F_LINEBUFFER_NEW 0
+# define BIO_F_MEM_WRITE 0
+# define BIO_F_NBIOF_NEW 0
+# define BIO_F_SLG_WRITE 0
+# define BIO_F_SSL_NEW 0
+
+/*
+ * BN function codes.
+ */
+# define BN_F_BNRAND 0
+# define BN_F_BNRAND_RANGE 0
+# define BN_F_BN_BLINDING_CONVERT_EX 0
+# define BN_F_BN_BLINDING_CREATE_PARAM 0
+# define BN_F_BN_BLINDING_INVERT_EX 0
+# define BN_F_BN_BLINDING_NEW 0
+# define BN_F_BN_BLINDING_UPDATE 0
+# define BN_F_BN_BN2DEC 0
+# define BN_F_BN_BN2HEX 0
+# define BN_F_BN_COMPUTE_WNAF 0
+# define BN_F_BN_CTX_GET 0
+# define BN_F_BN_CTX_NEW 0
+# define BN_F_BN_CTX_START 0
+# define BN_F_BN_DIV 0
+# define BN_F_BN_DIV_RECP 0
+# define BN_F_BN_EXP 0
+# define BN_F_BN_EXPAND_INTERNAL 0
+# define BN_F_BN_GENCB_NEW 0
+# define BN_F_BN_GENERATE_DSA_NONCE 0
+# define BN_F_BN_GENERATE_PRIME_EX 0
+# define BN_F_BN_GF2M_MOD 0
+# define BN_F_BN_GF2M_MOD_EXP 0
+# define BN_F_BN_GF2M_MOD_MUL 0
+# define BN_F_BN_GF2M_MOD_SOLVE_QUAD 0
+# define BN_F_BN_GF2M_MOD_SOLVE_QUAD_ARR 0
+# define BN_F_BN_GF2M_MOD_SQR 0
+# define BN_F_BN_GF2M_MOD_SQRT 0
+# define BN_F_BN_LSHIFT 0
+# define BN_F_BN_MOD_EXP2_MONT 0
+# define BN_F_BN_MOD_EXP_MONT 0
+# define BN_F_BN_MOD_EXP_MONT_CONSTTIME 0
+# define BN_F_BN_MOD_EXP_MONT_WORD 0
+# define BN_F_BN_MOD_EXP_RECP 0
+# define BN_F_BN_MOD_EXP_SIMPLE 0
+# define BN_F_BN_MOD_INVERSE 0
+# define BN_F_BN_MOD_INVERSE_NO_BRANCH 0
+# define BN_F_BN_MOD_LSHIFT_QUICK 0
+# define BN_F_BN_MOD_SQRT 0
+# define BN_F_BN_MONT_CTX_NEW 0
+# define BN_F_BN_MPI2BN 0
+# define BN_F_BN_NEW 0
+# define BN_F_BN_POOL_GET 0
+# define BN_F_BN_RAND 0
+# define BN_F_BN_RAND_RANGE 0
+# define BN_F_BN_RECP_CTX_NEW 0
+# define BN_F_BN_RSHIFT 0
+# define BN_F_BN_SET_WORDS 0
+# define BN_F_BN_STACK_PUSH 0
+# define BN_F_BN_USUB 0
+
+/*
+ * BUF function codes.
+ */
+# define BUF_F_BUF_MEM_GROW 0
+# define BUF_F_BUF_MEM_GROW_CLEAN 0
+# define BUF_F_BUF_MEM_NEW 0
+
+# ifndef OPENSSL_NO_CMS
+/*
+ * CMS function codes.
+ */
+# define CMS_F_CHECK_CONTENT 0
+# define CMS_F_CMS_ADD0_CERT 0
+# define CMS_F_CMS_ADD0_RECIPIENT_KEY 0
+# define CMS_F_CMS_ADD0_RECIPIENT_PASSWORD 0
+# define CMS_F_CMS_ADD1_RECEIPTREQUEST 0
+# define CMS_F_CMS_ADD1_RECIPIENT_CERT 0
+# define CMS_F_CMS_ADD1_SIGNER 0
+# define CMS_F_CMS_ADD1_SIGNINGTIME 0
+# define CMS_F_CMS_COMPRESS 0
+# define CMS_F_CMS_COMPRESSEDDATA_CREATE 0
+# define CMS_F_CMS_COMPRESSEDDATA_INIT_BIO 0
+# define CMS_F_CMS_COPY_CONTENT 0
+# define CMS_F_CMS_COPY_MESSAGEDIGEST 0
+# define CMS_F_CMS_DATA 0
+# define CMS_F_CMS_DATAFINAL 0
+# define CMS_F_CMS_DATAINIT 0
+# define CMS_F_CMS_DECRYPT 0
+# define CMS_F_CMS_DECRYPT_SET1_KEY 0
+# define CMS_F_CMS_DECRYPT_SET1_PASSWORD 0
+# define CMS_F_CMS_DECRYPT_SET1_PKEY 0
+# define CMS_F_CMS_DIGESTALGORITHM_FIND_CTX 0
+# define CMS_F_CMS_DIGESTALGORITHM_INIT_BIO 0
+# define CMS_F_CMS_DIGESTEDDATA_DO_FINAL 0
+# define CMS_F_CMS_DIGEST_VERIFY 0
+# define CMS_F_CMS_ENCODE_RECEIPT 0
+# define CMS_F_CMS_ENCRYPT 0
+# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT 0
+# define CMS_F_CMS_ENCRYPTEDCONTENT_INIT_BIO 0
+# define CMS_F_CMS_ENCRYPTEDDATA_DECRYPT 0
+# define CMS_F_CMS_ENCRYPTEDDATA_ENCRYPT 0
+# define CMS_F_CMS_ENCRYPTEDDATA_SET1_KEY 0
+# define CMS_F_CMS_ENVELOPEDDATA_CREATE 0
+# define CMS_F_CMS_ENVELOPEDDATA_INIT_BIO 0
+# define CMS_F_CMS_ENVELOPED_DATA_INIT 0
+# define CMS_F_CMS_ENV_ASN1_CTRL 0
+# define CMS_F_CMS_FINAL 0
+# define CMS_F_CMS_GET0_CERTIFICATE_CHOICES 0
+# define CMS_F_CMS_GET0_CONTENT 0
+# define CMS_F_CMS_GET0_ECONTENT_TYPE 0
+# define CMS_F_CMS_GET0_ENVELOPED 0
+# define CMS_F_CMS_GET0_REVOCATION_CHOICES 0
+# define CMS_F_CMS_GET0_SIGNED 0
+# define CMS_F_CMS_MSGSIGDIGEST_ADD1 0
+# define CMS_F_CMS_RECEIPTREQUEST_CREATE0 0
+# define CMS_F_CMS_RECEIPT_VERIFY 0
+# define CMS_F_CMS_RECIPIENTINFO_DECRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_ENCRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_KARI_ENCRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ALG 0
+# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_ORIG_ID 0
+# define CMS_F_CMS_RECIPIENTINFO_KARI_GET0_REKS 0
+# define CMS_F_CMS_RECIPIENTINFO_KARI_ORIG_ID_CMP 0
+# define CMS_F_CMS_RECIPIENTINFO_KEKRI_DECRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ENCRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_KEKRI_GET0_ID 0
+# define CMS_F_CMS_RECIPIENTINFO_KEKRI_ID_CMP 0
+# define CMS_F_CMS_RECIPIENTINFO_KTRI_CERT_CMP 0
+# define CMS_F_CMS_RECIPIENTINFO_KTRI_DECRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_KTRI_ENCRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_ALGS 0
+# define CMS_F_CMS_RECIPIENTINFO_KTRI_GET0_SIGNER_ID 0
+# define CMS_F_CMS_RECIPIENTINFO_PWRI_CRYPT 0
+# define CMS_F_CMS_RECIPIENTINFO_SET0_KEY 0
+# define CMS_F_CMS_RECIPIENTINFO_SET0_PASSWORD 0
+# define CMS_F_CMS_RECIPIENTINFO_SET0_PKEY 0
+# define CMS_F_CMS_SD_ASN1_CTRL 0
+# define CMS_F_CMS_SET1_IAS 0
+# define CMS_F_CMS_SET1_KEYID 0
+# define CMS_F_CMS_SET1_SIGNERIDENTIFIER 0
+# define CMS_F_CMS_SET_DETACHED 0
+# define CMS_F_CMS_SIGN 0
+# define CMS_F_CMS_SIGNED_DATA_INIT 0
+# define CMS_F_CMS_SIGNERINFO_CONTENT_SIGN 0
+# define CMS_F_CMS_SIGNERINFO_SIGN 0
+# define CMS_F_CMS_SIGNERINFO_VERIFY 0
+# define CMS_F_CMS_SIGNERINFO_VERIFY_CERT 0
+# define CMS_F_CMS_SIGNERINFO_VERIFY_CONTENT 0
+# define CMS_F_CMS_SIGN_RECEIPT 0
+# define CMS_F_CMS_SI_CHECK_ATTRIBUTES 0
+# define CMS_F_CMS_STREAM 0
+# define CMS_F_CMS_UNCOMPRESS 0
+# define CMS_F_CMS_VERIFY 0
+# define CMS_F_KEK_UNWRAP_KEY 0
+# endif
+
+# ifndef OPENSSL_NO_COMP
+/*
+ * COMP function codes.
+ */
+# define COMP_F_BIO_ZLIB_FLUSH 0
+# define COMP_F_BIO_ZLIB_NEW 0
+# define COMP_F_BIO_ZLIB_READ 0
+# define COMP_F_BIO_ZLIB_WRITE 0
+# define COMP_F_COMP_CTX_NEW 0
+# endif
+
+/*
+ * CONF function codes.
+ */
+# define CONF_F_CONF_DUMP_FP 0
+# define CONF_F_CONF_LOAD 0
+# define CONF_F_CONF_LOAD_FP 0
+# define CONF_F_CONF_PARSE_LIST 0
+# define CONF_F_DEF_LOAD 0
+# define CONF_F_DEF_LOAD_BIO 0
+# define CONF_F_GET_NEXT_FILE 0
+# define CONF_F_MODULE_ADD 0
+# define CONF_F_MODULE_INIT 0
+# define CONF_F_MODULE_LOAD_DSO 0
+# define CONF_F_MODULE_RUN 0
+# define CONF_F_NCONF_DUMP_BIO 0
+# define CONF_F_NCONF_DUMP_FP 0
+# define CONF_F_NCONF_GET_NUMBER_E 0
+# define CONF_F_NCONF_GET_SECTION 0
+# define CONF_F_NCONF_GET_STRING 0
+# define CONF_F_NCONF_LOAD 0
+# define CONF_F_NCONF_LOAD_BIO 0
+# define CONF_F_NCONF_LOAD_FP 0
+# define CONF_F_NCONF_NEW 0
+# define CONF_F_PROCESS_INCLUDE 0
+# define CONF_F_SSL_MODULE_INIT 0
+# define CONF_F_STR_COPY 0
+
+/*
+ * CRYPTO function codes.
+ */
+# define CRYPTO_F_CMAC_CTX_NEW 0
+# define CRYPTO_F_CRYPTO_DUP_EX_DATA 0
+# define CRYPTO_F_CRYPTO_FREE_EX_DATA 0
+# define CRYPTO_F_CRYPTO_GET_EX_NEW_INDEX 0
+# define CRYPTO_F_CRYPTO_MEMDUP 0
+# define CRYPTO_F_CRYPTO_NEW_EX_DATA 0
+# define CRYPTO_F_CRYPTO_OCB128_COPY_CTX 0
+# define CRYPTO_F_CRYPTO_OCB128_INIT 0
+# define CRYPTO_F_CRYPTO_SET_EX_DATA 0
+# define CRYPTO_F_GET_AND_LOCK 0
+# define CRYPTO_F_OPENSSL_ATEXIT 0
+# define CRYPTO_F_OPENSSL_BUF2HEXSTR 0
+# define CRYPTO_F_OPENSSL_FOPEN 0
+# define CRYPTO_F_OPENSSL_HEXSTR2BUF 0
+# define CRYPTO_F_OPENSSL_INIT_CRYPTO 0
+# define CRYPTO_F_OPENSSL_LH_NEW 0
+# define CRYPTO_F_OPENSSL_SK_DEEP_COPY 0
+# define CRYPTO_F_OPENSSL_SK_DUP 0
+# define CRYPTO_F_PKEY_HMAC_INIT 0
+# define CRYPTO_F_PKEY_POLY1305_INIT 0
+# define CRYPTO_F_PKEY_SIPHASH_INIT 0
+# define CRYPTO_F_SK_RESERVE 0
+
+# ifndef OPENSSL_NO_CT
+/*
+ * CT function codes.
+ */
+# define CT_F_CTLOG_NEW 0
+# define CT_F_CTLOG_NEW_FROM_BASE64 0
+# define CT_F_CTLOG_NEW_FROM_CONF 0
+# define CT_F_CTLOG_STORE_LOAD_CTX_NEW 0
+# define CT_F_CTLOG_STORE_LOAD_FILE 0
+# define CT_F_CTLOG_STORE_LOAD_LOG 0
+# define CT_F_CTLOG_STORE_NEW 0
+# define CT_F_CT_BASE64_DECODE 0
+# define CT_F_CT_POLICY_EVAL_CTX_NEW 0
+# define CT_F_CT_V1_LOG_ID_FROM_PKEY 0
+# define CT_F_I2O_SCT 0
+# define CT_F_I2O_SCT_LIST 0
+# define CT_F_I2O_SCT_SIGNATURE 0
+# define CT_F_O2I_SCT 0
+# define CT_F_O2I_SCT_LIST 0
+# define CT_F_O2I_SCT_SIGNATURE 0
+# define CT_F_SCT_CTX_NEW 0
+# define CT_F_SCT_CTX_VERIFY 0
+# define CT_F_SCT_NEW 0
+# define CT_F_SCT_NEW_FROM_BASE64 0
+# define CT_F_SCT_SET0_LOG_ID 0
+# define CT_F_SCT_SET1_EXTENSIONS 0
+# define CT_F_SCT_SET1_LOG_ID 0
+# define CT_F_SCT_SET1_SIGNATURE 0
+# define CT_F_SCT_SET_LOG_ENTRY_TYPE 0
+# define CT_F_SCT_SET_SIGNATURE_NID 0
+# define CT_F_SCT_SET_VERSION 0
+# endif
+
+# ifndef OPENSSL_NO_DH
+/*
+ * DH function codes.
+ */
+# define DH_F_COMPUTE_KEY 0
+# define DH_F_DHPARAMS_PRINT_FP 0
+# define DH_F_DH_BUILTIN_GENPARAMS 0
+# define DH_F_DH_CHECK_EX 0
+# define DH_F_DH_CHECK_PARAMS_EX 0
+# define DH_F_DH_CHECK_PUB_KEY_EX 0
+# define DH_F_DH_CMS_DECRYPT 0
+# define DH_F_DH_CMS_SET_PEERKEY 0
+# define DH_F_DH_CMS_SET_SHARED_INFO 0
+# define DH_F_DH_METH_DUP 0
+# define DH_F_DH_METH_NEW 0
+# define DH_F_DH_METH_SET1_NAME 0
+# define DH_F_DH_NEW_BY_NID 0
+# define DH_F_DH_NEW_METHOD 0
+# define DH_F_DH_PARAM_DECODE 0
+# define DH_F_DH_PKEY_PUBLIC_CHECK 0
+# define DH_F_DH_PRIV_DECODE 0
+# define DH_F_DH_PRIV_ENCODE 0
+# define DH_F_DH_PUB_DECODE 0
+# define DH_F_DH_PUB_ENCODE 0
+# define DH_F_DO_DH_PRINT 0
+# define DH_F_GENERATE_KEY 0
+# define DH_F_PKEY_DH_CTRL_STR 0
+# define DH_F_PKEY_DH_DERIVE 0
+# define DH_F_PKEY_DH_INIT 0
+# define DH_F_PKEY_DH_KEYGEN 0
+# endif
+
+# ifndef OPENSSL_NO_DSA
+/*
+ * DSA function codes.
+ */
+# define DSA_F_DSAPARAMS_PRINT 0
+# define DSA_F_DSAPARAMS_PRINT_FP 0
+# define DSA_F_DSA_BUILTIN_PARAMGEN 0
+# define DSA_F_DSA_BUILTIN_PARAMGEN2 0
+# define DSA_F_DSA_DO_SIGN 0
+# define DSA_F_DSA_DO_VERIFY 0
+# define DSA_F_DSA_METH_DUP 0
+# define DSA_F_DSA_METH_NEW 0
+# define DSA_F_DSA_METH_SET1_NAME 0
+# define DSA_F_DSA_NEW_METHOD 0
+# define DSA_F_DSA_PARAM_DECODE 0
+# define DSA_F_DSA_PRINT_FP 0
+# define DSA_F_DSA_PRIV_DECODE 0
+# define DSA_F_DSA_PRIV_ENCODE 0
+# define DSA_F_DSA_PUB_DECODE 0
+# define DSA_F_DSA_PUB_ENCODE 0
+# define DSA_F_DSA_SIGN 0
+# define DSA_F_DSA_SIGN_SETUP 0
+# define DSA_F_DSA_SIG_NEW 0
+# define DSA_F_OLD_DSA_PRIV_DECODE 0
+# define DSA_F_PKEY_DSA_CTRL 0
+# define DSA_F_PKEY_DSA_CTRL_STR 0
+# define DSA_F_PKEY_DSA_KEYGEN 0
+# endif
+
+# ifndef OPENSSL_NO_EC
+/*
+ * EC function codes.
+ */
+# define EC_F_BN_TO_FELEM 0
+# define EC_F_D2I_ECPARAMETERS 0
+# define EC_F_D2I_ECPKPARAMETERS 0
+# define EC_F_D2I_ECPRIVATEKEY 0
+# define EC_F_DO_EC_KEY_PRINT 0
+# define EC_F_ECDH_CMS_DECRYPT 0
+# define EC_F_ECDH_CMS_SET_SHARED_INFO 0
+# define EC_F_ECDH_COMPUTE_KEY 0
+# define EC_F_ECDH_SIMPLE_COMPUTE_KEY 0
+# define EC_F_ECDSA_DO_SIGN_EX 0
+# define EC_F_ECDSA_DO_VERIFY 0
+# define EC_F_ECDSA_SIGN_EX 0
+# define EC_F_ECDSA_SIGN_SETUP 0
+# define EC_F_ECDSA_SIG_NEW 0
+# define EC_F_ECDSA_VERIFY 0
+# define EC_F_ECD_ITEM_VERIFY 0
+# define EC_F_ECKEY_PARAM2TYPE 0
+# define EC_F_ECKEY_PARAM_DECODE 0
+# define EC_F_ECKEY_PRIV_DECODE 0
+# define EC_F_ECKEY_PRIV_ENCODE 0
+# define EC_F_ECKEY_PUB_DECODE 0
+# define EC_F_ECKEY_PUB_ENCODE 0
+# define EC_F_ECKEY_TYPE2PARAM 0
+# define EC_F_ECPARAMETERS_PRINT 0
+# define EC_F_ECPARAMETERS_PRINT_FP 0
+# define EC_F_ECPKPARAMETERS_PRINT 0
+# define EC_F_ECPKPARAMETERS_PRINT_FP 0
+# define EC_F_ECP_NISTZ256_GET_AFFINE 0
+# define EC_F_ECP_NISTZ256_INV_MOD_ORD 0
+# define EC_F_ECP_NISTZ256_MULT_PRECOMPUTE 0
+# define EC_F_ECP_NISTZ256_POINTS_MUL 0
+# define EC_F_ECP_NISTZ256_PRE_COMP_NEW 0
+# define EC_F_ECP_NISTZ256_WINDOWED_MUL 0
+# define EC_F_ECX_KEY_OP 0
+# define EC_F_ECX_PRIV_ENCODE 0
+# define EC_F_ECX_PUB_ENCODE 0
+# define EC_F_EC_ASN1_GROUP2CURVE 0
+# define EC_F_EC_ASN1_GROUP2FIELDID 0
+# define EC_F_EC_GF2M_MONTGOMERY_POINT_MULTIPLY 0
+# define EC_F_EC_GF2M_SIMPLE_FIELD_INV 0
+# define EC_F_EC_GF2M_SIMPLE_GROUP_CHECK_DISCRIMINANT 0
+# define EC_F_EC_GF2M_SIMPLE_GROUP_SET_CURVE 0
+# define EC_F_EC_GF2M_SIMPLE_LADDER_POST 0
+# define EC_F_EC_GF2M_SIMPLE_LADDER_PRE 0
+# define EC_F_EC_GF2M_SIMPLE_OCT2POINT 0
+# define EC_F_EC_GF2M_SIMPLE_POINT2OCT 0
+# define EC_F_EC_GF2M_SIMPLE_POINTS_MUL 0
+# define EC_F_EC_GF2M_SIMPLE_POINT_GET_AFFINE_COORDINATES 0
+# define EC_F_EC_GF2M_SIMPLE_POINT_SET_AFFINE_COORDINATES 0
+# define EC_F_EC_GF2M_SIMPLE_SET_COMPRESSED_COORDINATES 0
+# define EC_F_EC_GFP_MONT_FIELD_DECODE 0
+# define EC_F_EC_GFP_MONT_FIELD_ENCODE 0
+# define EC_F_EC_GFP_MONT_FIELD_INV 0
+# define EC_F_EC_GFP_MONT_FIELD_MUL 0
+# define EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE 0
+# define EC_F_EC_GFP_MONT_FIELD_SQR 0
+# define EC_F_EC_GFP_MONT_GROUP_SET_CURVE 0
+# define EC_F_EC_GFP_NISTP224_GROUP_SET_CURVE 0
+# define EC_F_EC_GFP_NISTP224_POINTS_MUL 0
+# define EC_F_EC_GFP_NISTP224_POINT_GET_AFFINE_COORDINATES 0
+# define EC_F_EC_GFP_NISTP256_GROUP_SET_CURVE 0
+# define EC_F_EC_GFP_NISTP256_POINTS_MUL 0
+# define EC_F_EC_GFP_NISTP256_POINT_GET_AFFINE_COORDINATES 0
+# define EC_F_EC_GFP_NISTP521_GROUP_SET_CURVE 0
+# define EC_F_EC_GFP_NISTP521_POINTS_MUL 0
+# define EC_F_EC_GFP_NISTP521_POINT_GET_AFFINE_COORDINATES 0
+# define EC_F_EC_GFP_NIST_FIELD_MUL 0
+# define EC_F_EC_GFP_NIST_FIELD_SQR 0
+# define EC_F_EC_GFP_NIST_GROUP_SET_CURVE 0
+# define EC_F_EC_GFP_SIMPLE_BLIND_COORDINATES 0
+# define EC_F_EC_GFP_SIMPLE_FIELD_INV 0
+# define EC_F_EC_GFP_SIMPLE_GROUP_CHECK_DISCRIMINANT 0
+# define EC_F_EC_GFP_SIMPLE_GROUP_SET_CURVE 0
+# define EC_F_EC_GFP_SIMPLE_MAKE_AFFINE 0
+# define EC_F_EC_GFP_SIMPLE_OCT2POINT 0
+# define EC_F_EC_GFP_SIMPLE_POINT2OCT 0
+# define EC_F_EC_GFP_SIMPLE_POINTS_MAKE_AFFINE 0
+# define EC_F_EC_GFP_SIMPLE_POINT_GET_AFFINE_COORDINATES 0
+# define EC_F_EC_GFP_SIMPLE_POINT_SET_AFFINE_COORDINATES 0
+# define EC_F_EC_GFP_SIMPLE_SET_COMPRESSED_COORDINATES 0
+# define EC_F_EC_GROUP_CHECK 0
+# define EC_F_EC_GROUP_CHECK_DISCRIMINANT 0
+# define EC_F_EC_GROUP_COPY 0
+# define EC_F_EC_GROUP_GET_CURVE 0
+# define EC_F_EC_GROUP_GET_CURVE_GF2M 0
+# define EC_F_EC_GROUP_GET_CURVE_GFP 0
+# define EC_F_EC_GROUP_GET_DEGREE 0
+# define EC_F_EC_GROUP_GET_ECPARAMETERS 0
+# define EC_F_EC_GROUP_GET_ECPKPARAMETERS 0
+# define EC_F_EC_GROUP_GET_PENTANOMIAL_BASIS 0
+# define EC_F_EC_GROUP_GET_TRINOMIAL_BASIS 0
+# define EC_F_EC_GROUP_NEW 0
+# define EC_F_EC_GROUP_NEW_BY_CURVE_NAME 0
+# define EC_F_EC_GROUP_NEW_FROM_DATA 0
+# define EC_F_EC_GROUP_NEW_FROM_ECPARAMETERS 0
+# define EC_F_EC_GROUP_NEW_FROM_ECPKPARAMETERS 0
+# define EC_F_EC_GROUP_SET_CURVE 0
+# define EC_F_EC_GROUP_SET_CURVE_GF2M 0
+# define EC_F_EC_GROUP_SET_CURVE_GFP 0
+# define EC_F_EC_GROUP_SET_GENERATOR 0
+# define EC_F_EC_GROUP_SET_SEED 0
+# define EC_F_EC_KEY_CHECK_KEY 0
+# define EC_F_EC_KEY_COPY 0
+# define EC_F_EC_KEY_GENERATE_KEY 0
+# define EC_F_EC_KEY_NEW 0
+# define EC_F_EC_KEY_NEW_METHOD 0
+# define EC_F_EC_KEY_OCT2PRIV 0
+# define EC_F_EC_KEY_PRINT 0
+# define EC_F_EC_KEY_PRINT_FP 0
+# define EC_F_EC_KEY_PRIV2BUF 0
+# define EC_F_EC_KEY_PRIV2OCT 0
+# define EC_F_EC_KEY_SET_PUBLIC_KEY_AFFINE_COORDINATES 0
+# define EC_F_EC_KEY_SIMPLE_CHECK_KEY 0
+# define EC_F_EC_KEY_SIMPLE_OCT2PRIV 0
+# define EC_F_EC_KEY_SIMPLE_PRIV2OCT 0
+# define EC_F_EC_PKEY_CHECK 0
+# define EC_F_EC_PKEY_PARAM_CHECK 0
+# define EC_F_EC_POINTS_MAKE_AFFINE 0
+# define EC_F_EC_POINTS_MUL 0
+# define EC_F_EC_POINT_ADD 0
+# define EC_F_EC_POINT_BN2POINT 0
+# define EC_F_EC_POINT_CMP 0
+# define EC_F_EC_POINT_COPY 0
+# define EC_F_EC_POINT_DBL 0
+# define EC_F_EC_POINT_GET_AFFINE_COORDINATES 0
+# define EC_F_EC_POINT_GET_AFFINE_COORDINATES_GF2M 0
+# define EC_F_EC_POINT_GET_AFFINE_COORDINATES_GFP 0
+# define EC_F_EC_POINT_GET_JPROJECTIVE_COORDINATES_GFP 0
+# define EC_F_EC_POINT_INVERT 0
+# define EC_F_EC_POINT_IS_AT_INFINITY 0
+# define EC_F_EC_POINT_IS_ON_CURVE 0
+# define EC_F_EC_POINT_MAKE_AFFINE 0
+# define EC_F_EC_POINT_NEW 0
+# define EC_F_EC_POINT_OCT2POINT 0
+# define EC_F_EC_POINT_POINT2BUF 0
+# define EC_F_EC_POINT_POINT2OCT 0
+# define EC_F_EC_POINT_SET_AFFINE_COORDINATES 0
+# define EC_F_EC_POINT_SET_AFFINE_COORDINATES_GF2M 0
+# define EC_F_EC_POINT_SET_AFFINE_COORDINATES_GFP 0
+# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES 0
+# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GF2M 0
+# define EC_F_EC_POINT_SET_COMPRESSED_COORDINATES_GFP 0
+# define EC_F_EC_POINT_SET_JPROJECTIVE_COORDINATES_GFP 0
+# define EC_F_EC_POINT_SET_TO_INFINITY 0
+# define EC_F_EC_PRE_COMP_NEW 0
+# define EC_F_EC_SCALAR_MUL_LADDER 0
+# define EC_F_EC_WNAF_MUL 0
+# define EC_F_EC_WNAF_PRECOMPUTE_MULT 0
+# define EC_F_I2D_ECPARAMETERS 0
+# define EC_F_I2D_ECPKPARAMETERS 0
+# define EC_F_I2D_ECPRIVATEKEY 0
+# define EC_F_I2O_ECPUBLICKEY 0
+# define EC_F_NISTP224_PRE_COMP_NEW 0
+# define EC_F_NISTP256_PRE_COMP_NEW 0
+# define EC_F_NISTP521_PRE_COMP_NEW 0
+# define EC_F_O2I_ECPUBLICKEY 0
+# define EC_F_OLD_EC_PRIV_DECODE 0
+# define EC_F_OSSL_ECDH_COMPUTE_KEY 0
+# define EC_F_OSSL_ECDSA_SIGN_SIG 0
+# define EC_F_OSSL_ECDSA_VERIFY_SIG 0
+# define EC_F_PKEY_ECD_CTRL 0
+# define EC_F_PKEY_ECD_DIGESTSIGN 0
+# define EC_F_PKEY_ECD_DIGESTSIGN25519 0
+# define EC_F_PKEY_ECD_DIGESTSIGN448 0
+# define EC_F_PKEY_ECX_DERIVE 0
+# define EC_F_PKEY_EC_CTRL 0
+# define EC_F_PKEY_EC_CTRL_STR 0
+# define EC_F_PKEY_EC_DERIVE 0
+# define EC_F_PKEY_EC_INIT 0
+# define EC_F_PKEY_EC_KDF_DERIVE 0
+# define EC_F_PKEY_EC_KEYGEN 0
+# define EC_F_PKEY_EC_PARAMGEN 0
+# define EC_F_PKEY_EC_SIGN 0
+# define EC_F_VALIDATE_ECX_DERIVE 0
+# endif
+
+# ifndef OPENSSL_NO_ENGINE
+/*
+ * ENGINE function codes.
+ */
+# define ENGINE_F_DIGEST_UPDATE 0
+# define ENGINE_F_DYNAMIC_CTRL 0
+# define ENGINE_F_DYNAMIC_GET_DATA_CTX 0
+# define ENGINE_F_DYNAMIC_LOAD 0
+# define ENGINE_F_DYNAMIC_SET_DATA_CTX 0
+# define ENGINE_F_ENGINE_ADD 0
+# define ENGINE_F_ENGINE_BY_ID 0
+# define ENGINE_F_ENGINE_CMD_IS_EXECUTABLE 0
+# define ENGINE_F_ENGINE_CTRL 0
+# define ENGINE_F_ENGINE_CTRL_CMD 0
+# define ENGINE_F_ENGINE_CTRL_CMD_STRING 0
+# define ENGINE_F_ENGINE_FINISH 0
+# define ENGINE_F_ENGINE_GET_CIPHER 0
+# define ENGINE_F_ENGINE_GET_DIGEST 0
+# define ENGINE_F_ENGINE_GET_FIRST 0
+# define ENGINE_F_ENGINE_GET_LAST 0
+# define ENGINE_F_ENGINE_GET_NEXT 0
+# define ENGINE_F_ENGINE_GET_PKEY_ASN1_METH 0
+# define ENGINE_F_ENGINE_GET_PKEY_METH 0
+# define ENGINE_F_ENGINE_GET_PREV 0
+# define ENGINE_F_ENGINE_INIT 0
+# define ENGINE_F_ENGINE_LIST_ADD 0
+# define ENGINE_F_ENGINE_LIST_REMOVE 0
+# define ENGINE_F_ENGINE_LOAD_PRIVATE_KEY 0
+# define ENGINE_F_ENGINE_LOAD_PUBLIC_KEY 0
+# define ENGINE_F_ENGINE_LOAD_SSL_CLIENT_CERT 0
+# define ENGINE_F_ENGINE_NEW 0
+# define ENGINE_F_ENGINE_PKEY_ASN1_FIND_STR 0
+# define ENGINE_F_ENGINE_REMOVE 0
+# define ENGINE_F_ENGINE_SET_DEFAULT_STRING 0
+# define ENGINE_F_ENGINE_SET_ID 0
+# define ENGINE_F_ENGINE_SET_NAME 0
+# define ENGINE_F_ENGINE_TABLE_REGISTER 0
+# define ENGINE_F_ENGINE_UNLOCKED_FINISH 0
+# define ENGINE_F_ENGINE_UP_REF 0
+# define ENGINE_F_INT_CLEANUP_ITEM 0
+# define ENGINE_F_INT_CTRL_HELPER 0
+# define ENGINE_F_INT_ENGINE_CONFIGURE 0
+# define ENGINE_F_INT_ENGINE_MODULE_INIT 0
+# define ENGINE_F_OSSL_HMAC_INIT 0
+# endif
+
+/*
+ * EVP function codes.
+ */
+# define EVP_F_AESNI_INIT_KEY 0
+# define EVP_F_AESNI_XTS_INIT_KEY 0
+# define EVP_F_AES_GCM_CTRL 0
+# define EVP_F_AES_INIT_KEY 0
+# define EVP_F_AES_OCB_CIPHER 0
+# define EVP_F_AES_T4_INIT_KEY 0
+# define EVP_F_AES_T4_XTS_INIT_KEY 0
+# define EVP_F_AES_WRAP_CIPHER 0
+# define EVP_F_AES_XTS_INIT_KEY 0
+# define EVP_F_ALG_MODULE_INIT 0
+# define EVP_F_ARIA_CCM_INIT_KEY 0
+# define EVP_F_ARIA_GCM_CTRL 0
+# define EVP_F_ARIA_GCM_INIT_KEY 0
+# define EVP_F_ARIA_INIT_KEY 0
+# define EVP_F_B64_NEW 0
+# define EVP_F_CAMELLIA_INIT_KEY 0
+# define EVP_F_CHACHA20_POLY1305_CTRL 0
+# define EVP_F_CMLL_T4_INIT_KEY 0
+# define EVP_F_DES_EDE3_WRAP_CIPHER 0
+# define EVP_F_DO_SIGVER_INIT 0
+# define EVP_F_ENC_NEW 0
+# define EVP_F_EVP_CIPHERINIT_EX 0
+# define EVP_F_EVP_CIPHER_ASN1_TO_PARAM 0
+# define EVP_F_EVP_CIPHER_CTX_COPY 0
+# define EVP_F_EVP_CIPHER_CTX_CTRL 0
+# define EVP_F_EVP_CIPHER_CTX_SET_KEY_LENGTH 0
+# define EVP_F_EVP_CIPHER_PARAM_TO_ASN1 0
+# define EVP_F_EVP_DECRYPTFINAL_EX 0
+# define EVP_F_EVP_DECRYPTUPDATE 0
+# define EVP_F_EVP_DIGESTFINALXOF 0
+# define EVP_F_EVP_DIGESTINIT_EX 0
+# define EVP_F_EVP_ENCRYPTDECRYPTUPDATE 0
+# define EVP_F_EVP_ENCRYPTFINAL_EX 0
+# define EVP_F_EVP_ENCRYPTUPDATE 0
+# define EVP_F_EVP_MD_CTX_COPY_EX 0
+# define EVP_F_EVP_MD_SIZE 0
+# define EVP_F_EVP_OPENINIT 0
+# define EVP_F_EVP_PBE_ALG_ADD 0
+# define EVP_F_EVP_PBE_ALG_ADD_TYPE 0
+# define EVP_F_EVP_PBE_CIPHERINIT 0
+# define EVP_F_EVP_PBE_SCRYPT 0
+# define EVP_F_EVP_PKCS82PKEY 0
+# define EVP_F_EVP_PKEY2PKCS8 0
+# define EVP_F_EVP_PKEY_ASN1_ADD0 0
+# define EVP_F_EVP_PKEY_CHECK 0
+# define EVP_F_EVP_PKEY_COPY_PARAMETERS 0
+# define EVP_F_EVP_PKEY_CTX_CTRL 0
+# define EVP_F_EVP_PKEY_CTX_CTRL_STR 0
+# define EVP_F_EVP_PKEY_CTX_DUP 0
+# define EVP_F_EVP_PKEY_CTX_MD 0
+# define EVP_F_EVP_PKEY_DECRYPT 0
+# define EVP_F_EVP_PKEY_DECRYPT_INIT 0
+# define EVP_F_EVP_PKEY_DECRYPT_OLD 0
+# define EVP_F_EVP_PKEY_DERIVE 0
+# define EVP_F_EVP_PKEY_DERIVE_INIT 0
+# define EVP_F_EVP_PKEY_DERIVE_SET_PEER 0
+# define EVP_F_EVP_PKEY_ENCRYPT 0
+# define EVP_F_EVP_PKEY_ENCRYPT_INIT 0
+# define EVP_F_EVP_PKEY_ENCRYPT_OLD 0
+# define EVP_F_EVP_PKEY_GET0_DH 0
+# define EVP_F_EVP_PKEY_GET0_DSA 0
+# define EVP_F_EVP_PKEY_GET0_EC_KEY 0
+# define EVP_F_EVP_PKEY_GET0_HMAC 0
+# define EVP_F_EVP_PKEY_GET0_POLY1305 0
+# define EVP_F_EVP_PKEY_GET0_RSA 0
+# define EVP_F_EVP_PKEY_GET0_SIPHASH 0
+# define EVP_F_EVP_PKEY_GET_RAW_PRIVATE_KEY 0
+# define EVP_F_EVP_PKEY_GET_RAW_PUBLIC_KEY 0
+# define EVP_F_EVP_PKEY_KEYGEN 0
+# define EVP_F_EVP_PKEY_KEYGEN_INIT 0
+# define EVP_F_EVP_PKEY_METH_ADD0 0
+# define EVP_F_EVP_PKEY_METH_NEW 0
+# define EVP_F_EVP_PKEY_NEW 0
+# define EVP_F_EVP_PKEY_NEW_CMAC_KEY 0
+# define EVP_F_EVP_PKEY_NEW_RAW_PRIVATE_KEY 0
+# define EVP_F_EVP_PKEY_NEW_RAW_PUBLIC_KEY 0
+# define EVP_F_EVP_PKEY_PARAMGEN 0
+# define EVP_F_EVP_PKEY_PARAMGEN_INIT 0
+# define EVP_F_EVP_PKEY_PARAM_CHECK 0
+# define EVP_F_EVP_PKEY_PUBLIC_CHECK 0
+# define EVP_F_EVP_PKEY_SET1_ENGINE 0
+# define EVP_F_EVP_PKEY_SET_ALIAS_TYPE 0
+# define EVP_F_EVP_PKEY_SIGN 0
+# define EVP_F_EVP_PKEY_SIGN_INIT 0
+# define EVP_F_EVP_PKEY_VERIFY 0
+# define EVP_F_EVP_PKEY_VERIFY_INIT 0
+# define EVP_F_EVP_PKEY_VERIFY_RECOVER 0
+# define EVP_F_EVP_PKEY_VERIFY_RECOVER_INIT 0
+# define EVP_F_EVP_SIGNFINAL 0
+# define EVP_F_EVP_VERIFYFINAL 0
+# define EVP_F_INT_CTX_NEW 0
+# define EVP_F_OK_NEW 0
+# define EVP_F_PKCS5_PBE_KEYIVGEN 0
+# define EVP_F_PKCS5_V2_PBE_KEYIVGEN 0
+# define EVP_F_PKCS5_V2_PBKDF2_KEYIVGEN 0
+# define EVP_F_PKCS5_V2_SCRYPT_KEYIVGEN 0
+# define EVP_F_PKEY_SET_TYPE 0
+# define EVP_F_RC2_MAGIC_TO_METH 0
+# define EVP_F_RC5_CTRL 0
+# define EVP_F_R_32_12_16_INIT_KEY 0
+# define EVP_F_S390X_AES_GCM_CTRL 0
+# define EVP_F_UPDATE 0
+
+/*
+ * KDF function codes.
+ */
+# define KDF_F_PKEY_HKDF_CTRL_STR 0
+# define KDF_F_PKEY_HKDF_DERIVE 0
+# define KDF_F_PKEY_HKDF_INIT 0
+# define KDF_F_PKEY_SCRYPT_CTRL_STR 0
+# define KDF_F_PKEY_SCRYPT_CTRL_UINT64 0
+# define KDF_F_PKEY_SCRYPT_DERIVE 0
+# define KDF_F_PKEY_SCRYPT_INIT 0
+# define KDF_F_PKEY_SCRYPT_SET_MEMBUF 0
+# define KDF_F_PKEY_TLS1_PRF_CTRL_STR 0
+# define KDF_F_PKEY_TLS1_PRF_DERIVE 0
+# define KDF_F_PKEY_TLS1_PRF_INIT 0
+# define KDF_F_TLS1_PRF_ALG 0
+
+/*
+ * KDF reason codes.
+ */
+# define KDF_R_INVALID_DIGEST 0
+# define KDF_R_MISSING_ITERATION_COUNT 0
+# define KDF_R_MISSING_KEY 0
+# define KDF_R_MISSING_MESSAGE_DIGEST 0
+# define KDF_R_MISSING_PARAMETER 0
+# define KDF_R_MISSING_PASS 0
+# define KDF_R_MISSING_SALT 0
+# define KDF_R_MISSING_SECRET 0
+# define KDF_R_MISSING_SEED 0
+# define KDF_R_UNKNOWN_PARAMETER_TYPE 0
+# define KDF_R_VALUE_ERROR 0
+# define KDF_R_VALUE_MISSING 0
+
+/*
+ * OBJ function codes.
+ */
+# define OBJ_F_OBJ_ADD_OBJECT 0
+# define OBJ_F_OBJ_ADD_SIGID 0
+# define OBJ_F_OBJ_CREATE 0
+# define OBJ_F_OBJ_DUP 0
+# define OBJ_F_OBJ_NAME_NEW_INDEX 0
+# define OBJ_F_OBJ_NID2LN 0
+# define OBJ_F_OBJ_NID2OBJ 0
+# define OBJ_F_OBJ_NID2SN 0
+# define OBJ_F_OBJ_TXT2OBJ 0
+
+# ifndef OPENSSL_NO_OCSP
+/*
+ * OCSP function codes.
+ */
+# define OCSP_F_D2I_OCSP_NONCE 0
+# define OCSP_F_OCSP_BASIC_ADD1_STATUS 0
+# define OCSP_F_OCSP_BASIC_SIGN 0
+# define OCSP_F_OCSP_BASIC_SIGN_CTX 0
+# define OCSP_F_OCSP_BASIC_VERIFY 0
+# define OCSP_F_OCSP_CERT_ID_NEW 0
+# define OCSP_F_OCSP_CHECK_DELEGATED 0
+# define OCSP_F_OCSP_CHECK_IDS 0
+# define OCSP_F_OCSP_CHECK_ISSUER 0
+# define OCSP_F_OCSP_CHECK_VALIDITY 0
+# define OCSP_F_OCSP_MATCH_ISSUERID 0
+# define OCSP_F_OCSP_PARSE_URL 0
+# define OCSP_F_OCSP_REQUEST_SIGN 0
+# define OCSP_F_OCSP_REQUEST_VERIFY 0
+# define OCSP_F_OCSP_RESPONSE_GET1_BASIC 0
+# define OCSP_F_PARSE_HTTP_LINE1 0
+# endif
+
+/*
+ * PEM function codes.
+ */
+# define PEM_F_B2I_DSS 0
+# define PEM_F_B2I_PVK_BIO 0
+# define PEM_F_B2I_RSA 0
+# define PEM_F_CHECK_BITLEN_DSA 0
+# define PEM_F_CHECK_BITLEN_RSA 0
+# define PEM_F_D2I_PKCS8PRIVATEKEY_BIO 0
+# define PEM_F_D2I_PKCS8PRIVATEKEY_FP 0
+# define PEM_F_DO_B2I 0
+# define PEM_F_DO_B2I_BIO 0
+# define PEM_F_DO_BLOB_HEADER 0
+# define PEM_F_DO_I2B 0
+# define PEM_F_DO_PK8PKEY 0
+# define PEM_F_DO_PK8PKEY_FP 0
+# define PEM_F_DO_PVK_BODY 0
+# define PEM_F_DO_PVK_HEADER 0
+# define PEM_F_GET_HEADER_AND_DATA 0
+# define PEM_F_GET_NAME 0
+# define PEM_F_I2B_PVK 0
+# define PEM_F_I2B_PVK_BIO 0
+# define PEM_F_LOAD_IV 0
+# define PEM_F_PEM_ASN1_READ 0
+# define PEM_F_PEM_ASN1_READ_BIO 0
+# define PEM_F_PEM_ASN1_WRITE 0
+# define PEM_F_PEM_ASN1_WRITE_BIO 0
+# define PEM_F_PEM_DEF_CALLBACK 0
+# define PEM_F_PEM_DO_HEADER 0
+# define PEM_F_PEM_GET_EVP_CIPHER_INFO 0
+# define PEM_F_PEM_READ 0
+# define PEM_F_PEM_READ_BIO 0
+# define PEM_F_PEM_READ_BIO_DHPARAMS 0
+# define PEM_F_PEM_READ_BIO_EX 0
+# define PEM_F_PEM_READ_BIO_PARAMETERS 0
+# define PEM_F_PEM_READ_BIO_PRIVATEKEY 0
+# define PEM_F_PEM_READ_DHPARAMS 0
+# define PEM_F_PEM_READ_PRIVATEKEY 0
+# define PEM_F_PEM_SIGNFINAL 0
+# define PEM_F_PEM_WRITE 0
+# define PEM_F_PEM_WRITE_BIO 0
+# define PEM_F_PEM_WRITE_BIO_PRIVATEKEY_TRADITIONAL 0
+# define PEM_F_PEM_WRITE_PRIVATEKEY 0
+# define PEM_F_PEM_X509_INFO_READ 0
+# define PEM_F_PEM_X509_INFO_READ_BIO 0
+# define PEM_F_PEM_X509_INFO_WRITE_BIO 0
+
+/*
+ * PKCS12 function codes.
+ */
+# define PKCS12_F_OPENSSL_ASC2UNI 0
+# define PKCS12_F_OPENSSL_UNI2ASC 0
+# define PKCS12_F_OPENSSL_UNI2UTF8 0
+# define PKCS12_F_OPENSSL_UTF82UNI 0
+# define PKCS12_F_PKCS12_CREATE 0
+# define PKCS12_F_PKCS12_GEN_MAC 0
+# define PKCS12_F_PKCS12_INIT 0
+# define PKCS12_F_PKCS12_ITEM_DECRYPT_D2I 0
+# define PKCS12_F_PKCS12_ITEM_I2D_ENCRYPT 0
+# define PKCS12_F_PKCS12_ITEM_PACK_SAFEBAG 0
+# define PKCS12_F_PKCS12_KEY_GEN_ASC 0
+# define PKCS12_F_PKCS12_KEY_GEN_UNI 0
+# define PKCS12_F_PKCS12_KEY_GEN_UTF8 0
+# define PKCS12_F_PKCS12_NEWPASS 0
+# define PKCS12_F_PKCS12_PACK_P7DATA 0
+# define PKCS12_F_PKCS12_PACK_P7ENCDATA 0
+# define PKCS12_F_PKCS12_PARSE 0
+# define PKCS12_F_PKCS12_PBE_CRYPT 0
+# define PKCS12_F_PKCS12_PBE_KEYIVGEN 0
+# define PKCS12_F_PKCS12_SAFEBAG_CREATE0_P8INF 0
+# define PKCS12_F_PKCS12_SAFEBAG_CREATE0_PKCS8 0
+# define PKCS12_F_PKCS12_SAFEBAG_CREATE_PKCS8_ENCRYPT 0
+# define PKCS12_F_PKCS12_SETUP_MAC 0
+# define PKCS12_F_PKCS12_SET_MAC 0
+# define PKCS12_F_PKCS12_UNPACK_AUTHSAFES 0
+# define PKCS12_F_PKCS12_UNPACK_P7DATA 0
+# define PKCS12_F_PKCS12_VERIFY_MAC 0
+# define PKCS12_F_PKCS8_ENCRYPT 0
+# define PKCS12_F_PKCS8_SET0_PBE 0
+
+/*
+ * PKCS7 function codes.
+ */
+# define PKCS7_F_DO_PKCS7_SIGNED_ATTRIB 0
+# define PKCS7_F_PKCS7_ADD0_ATTRIB_SIGNING_TIME 0
+# define PKCS7_F_PKCS7_ADD_ATTRIB_SMIMECAP 0
+# define PKCS7_F_PKCS7_ADD_CERTIFICATE 0
+# define PKCS7_F_PKCS7_ADD_CRL 0
+# define PKCS7_F_PKCS7_ADD_RECIPIENT_INFO 0
+# define PKCS7_F_PKCS7_ADD_SIGNATURE 0
+# define PKCS7_F_PKCS7_ADD_SIGNER 0
+# define PKCS7_F_PKCS7_BIO_ADD_DIGEST 0
+# define PKCS7_F_PKCS7_COPY_EXISTING_DIGEST 0
+# define PKCS7_F_PKCS7_CTRL 0
+# define PKCS7_F_PKCS7_DATADECODE 0
+# define PKCS7_F_PKCS7_DATAFINAL 0
+# define PKCS7_F_PKCS7_DATAINIT 0
+# define PKCS7_F_PKCS7_DATAVERIFY 0
+# define PKCS7_F_PKCS7_DECRYPT 0
+# define PKCS7_F_PKCS7_DECRYPT_RINFO 0
+# define PKCS7_F_PKCS7_ENCODE_RINFO 0
+# define PKCS7_F_PKCS7_ENCRYPT 0
+# define PKCS7_F_PKCS7_FINAL 0
+# define PKCS7_F_PKCS7_FIND_DIGEST 0
+# define PKCS7_F_PKCS7_GET0_SIGNERS 0
+# define PKCS7_F_PKCS7_RECIP_INFO_SET 0
+# define PKCS7_F_PKCS7_SET_CIPHER 0
+# define PKCS7_F_PKCS7_SET_CONTENT 0
+# define PKCS7_F_PKCS7_SET_DIGEST 0
+# define PKCS7_F_PKCS7_SET_TYPE 0
+# define PKCS7_F_PKCS7_SIGN 0
+# define PKCS7_F_PKCS7_SIGNATUREVERIFY 0
+# define PKCS7_F_PKCS7_SIGNER_INFO_SET 0
+# define PKCS7_F_PKCS7_SIGNER_INFO_SIGN 0
+# define PKCS7_F_PKCS7_SIGN_ADD_SIGNER 0
+# define PKCS7_F_PKCS7_SIMPLE_SMIMECAP 0
+# define PKCS7_F_PKCS7_VERIFY 0
+
+/*
+ * RAND function codes.
+ */
+# define RAND_F_DATA_COLLECT_METHOD 0
+# define RAND_F_DRBG_BYTES 0
+# define RAND_F_DRBG_GET_ENTROPY 0
+# define RAND_F_DRBG_SETUP 0
+# define RAND_F_GET_ENTROPY 0
+# define RAND_F_RAND_BYTES 0
+# define RAND_F_RAND_DRBG_ENABLE_LOCKING 0
+# define RAND_F_RAND_DRBG_GENERATE 0
+# define RAND_F_RAND_DRBG_GET_ENTROPY 0
+# define RAND_F_RAND_DRBG_GET_NONCE 0
+# define RAND_F_RAND_DRBG_INSTANTIATE 0
+# define RAND_F_RAND_DRBG_NEW 0
+# define RAND_F_RAND_DRBG_RESEED 0
+# define RAND_F_RAND_DRBG_RESTART 0
+# define RAND_F_RAND_DRBG_SET 0
+# define RAND_F_RAND_DRBG_SET_DEFAULTS 0
+# define RAND_F_RAND_DRBG_UNINSTANTIATE 0
+# define RAND_F_RAND_LOAD_FILE 0
+# define RAND_F_RAND_POOL_ACQUIRE_ENTROPY 0
+# define RAND_F_RAND_POOL_ADD 0
+# define RAND_F_RAND_POOL_ADD_BEGIN 0
+# define RAND_F_RAND_POOL_ADD_END 0
+# define RAND_F_RAND_POOL_ATTACH 0
+# define RAND_F_RAND_POOL_BYTES_NEEDED 0
+# define RAND_F_RAND_POOL_GROW 0
+# define RAND_F_RAND_POOL_NEW 0
+# define RAND_F_RAND_PSEUDO_BYTES 0
+# define RAND_F_RAND_WRITE_FILE 0
+
+/*
+ * RSA function codes.
+ */
+# define RSA_F_CHECK_PADDING_MD 0
+# define RSA_F_ENCODE_PKCS1 0
+# define RSA_F_INT_RSA_VERIFY 0
+# define RSA_F_OLD_RSA_PRIV_DECODE 0
+# define RSA_F_PKEY_PSS_INIT 0
+# define RSA_F_PKEY_RSA_CTRL 0
+# define RSA_F_PKEY_RSA_CTRL_STR 0
+# define RSA_F_PKEY_RSA_SIGN 0
+# define RSA_F_PKEY_RSA_VERIFY 0
+# define RSA_F_PKEY_RSA_VERIFYRECOVER 0
+# define RSA_F_RSA_ALGOR_TO_MD 0
+# define RSA_F_RSA_BUILTIN_KEYGEN 0
+# define RSA_F_RSA_CHECK_KEY 0
+# define RSA_F_RSA_CHECK_KEY_EX 0
+# define RSA_F_RSA_CMS_DECRYPT 0
+# define RSA_F_RSA_CMS_VERIFY 0
+# define RSA_F_RSA_ITEM_VERIFY 0
+# define RSA_F_RSA_METH_DUP 0
+# define RSA_F_RSA_METH_NEW 0
+# define RSA_F_RSA_METH_SET1_NAME 0
+# define RSA_F_RSA_MGF1_TO_MD 0
+# define RSA_F_RSA_MULTIP_INFO_NEW 0
+# define RSA_F_RSA_NEW_METHOD 0
+# define RSA_F_RSA_NULL 0
+# define RSA_F_RSA_NULL_PRIVATE_DECRYPT 0
+# define RSA_F_RSA_NULL_PRIVATE_ENCRYPT 0
+# define RSA_F_RSA_NULL_PUBLIC_DECRYPT 0
+# define RSA_F_RSA_NULL_PUBLIC_ENCRYPT 0
+# define RSA_F_RSA_OSSL_PRIVATE_DECRYPT 0
+# define RSA_F_RSA_OSSL_PRIVATE_ENCRYPT 0
+# define RSA_F_RSA_OSSL_PUBLIC_DECRYPT 0
+# define RSA_F_RSA_OSSL_PUBLIC_ENCRYPT 0
+# define RSA_F_RSA_PADDING_ADD_NONE 0
+# define RSA_F_RSA_PADDING_ADD_PKCS1_OAEP 0
+# define RSA_F_RSA_PADDING_ADD_PKCS1_OAEP_MGF1 0
+# define RSA_F_RSA_PADDING_ADD_PKCS1_PSS 0
+# define RSA_F_RSA_PADDING_ADD_PKCS1_PSS_MGF1 0
+# define RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_1 0
+# define RSA_F_RSA_PADDING_ADD_PKCS1_TYPE_2 0
+# define RSA_F_RSA_PADDING_ADD_SSLV23 0
+# define RSA_F_RSA_PADDING_ADD_X931 0
+# define RSA_F_RSA_PADDING_CHECK_NONE 0
+# define RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP 0
+# define RSA_F_RSA_PADDING_CHECK_PKCS1_OAEP_MGF1 0
+# define RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_1 0
+# define RSA_F_RSA_PADDING_CHECK_PKCS1_TYPE_2 0
+# define RSA_F_RSA_PADDING_CHECK_SSLV23 0
+# define RSA_F_RSA_PADDING_CHECK_X931 0
+# define RSA_F_RSA_PARAM_DECODE 0
+# define RSA_F_RSA_PRINT 0
+# define RSA_F_RSA_PRINT_FP 0
+# define RSA_F_RSA_PRIV_DECODE 0
+# define RSA_F_RSA_PRIV_ENCODE 0
+# define RSA_F_RSA_PSS_GET_PARAM 0
+# define RSA_F_RSA_PSS_TO_CTX 0
+# define RSA_F_RSA_PUB_DECODE 0
+# define RSA_F_RSA_SETUP_BLINDING 0
+# define RSA_F_RSA_SIGN 0
+# define RSA_F_RSA_SIGN_ASN1_OCTET_STRING 0
+# define RSA_F_RSA_VERIFY 0
+# define RSA_F_RSA_VERIFY_ASN1_OCTET_STRING 0
+# define RSA_F_RSA_VERIFY_PKCS1_PSS_MGF1 0
+# define RSA_F_SETUP_TBUF 0
+
+/*
+ * OSSL_STORE function codes.
+ */
+# define OSSL_STORE_F_FILE_CTRL 0
+# define OSSL_STORE_F_FILE_FIND 0
+# define OSSL_STORE_F_FILE_GET_PASS 0
+# define OSSL_STORE_F_FILE_LOAD 0
+# define OSSL_STORE_F_FILE_LOAD_TRY_DECODE 0
+# define OSSL_STORE_F_FILE_NAME_TO_URI 0
+# define OSSL_STORE_F_FILE_OPEN 0
+# define OSSL_STORE_F_OSSL_STORE_ATTACH_PEM_BIO 0
+# define OSSL_STORE_F_OSSL_STORE_EXPECT 0
+# define OSSL_STORE_F_OSSL_STORE_FILE_ATTACH_PEM_BIO_INT 0
+# define OSSL_STORE_F_OSSL_STORE_FIND 0
+# define OSSL_STORE_F_OSSL_STORE_GET0_LOADER_INT 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_CERT 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_CRL 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_NAME_DESCRIPTION 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_PARAMS 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_GET1_PKEY 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_CERT 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_CRL 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_EMBEDDED 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_NAME 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_PARAMS 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_NEW_PKEY 0
+# define OSSL_STORE_F_OSSL_STORE_INFO_SET0_NAME_DESCRIPTION 0
+# define OSSL_STORE_F_OSSL_STORE_INIT_ONCE 0
+# define OSSL_STORE_F_OSSL_STORE_LOADER_NEW 0
+# define OSSL_STORE_F_OSSL_STORE_OPEN 0
+# define OSSL_STORE_F_OSSL_STORE_OPEN_INT 0
+# define OSSL_STORE_F_OSSL_STORE_REGISTER_LOADER_INT 0
+# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ALIAS 0
+# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_ISSUER_SERIAL 0
+# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT 0
+# define OSSL_STORE_F_OSSL_STORE_SEARCH_BY_NAME 0
+# define OSSL_STORE_F_OSSL_STORE_UNREGISTER_LOADER_INT 0
+# define OSSL_STORE_F_TRY_DECODE_PARAMS 0
+# define OSSL_STORE_F_TRY_DECODE_PKCS12 0
+# define OSSL_STORE_F_TRY_DECODE_PKCS8ENCRYPTED 0
+
+# ifndef OPENSSL_NO_TS
+/*
+ * TS function codes.
+ */
+# define TS_F_DEF_SERIAL_CB 0
+# define TS_F_DEF_TIME_CB 0
+# define TS_F_ESS_ADD_SIGNING_CERT 0
+# define TS_F_ESS_ADD_SIGNING_CERT_V2 0
+# define TS_F_ESS_CERT_ID_NEW_INIT 0
+# define TS_F_ESS_CERT_ID_V2_NEW_INIT 0
+# define TS_F_ESS_SIGNING_CERT_NEW_INIT 0
+# define TS_F_ESS_SIGNING_CERT_V2_NEW_INIT 0
+# define TS_F_INT_TS_RESP_VERIFY_TOKEN 0
+# define TS_F_PKCS7_TO_TS_TST_INFO 0
+# define TS_F_TS_ACCURACY_SET_MICROS 0
+# define TS_F_TS_ACCURACY_SET_MILLIS 0
+# define TS_F_TS_ACCURACY_SET_SECONDS 0
+# define TS_F_TS_CHECK_IMPRINTS 0
+# define TS_F_TS_CHECK_NONCES 0
+# define TS_F_TS_CHECK_POLICY 0
+# define TS_F_TS_CHECK_SIGNING_CERTS 0
+# define TS_F_TS_CHECK_STATUS_INFO 0
+# define TS_F_TS_COMPUTE_IMPRINT 0
+# define TS_F_TS_CONF_INVALID 0
+# define TS_F_TS_CONF_LOAD_CERT 0
+# define TS_F_TS_CONF_LOAD_CERTS 0
+# define TS_F_TS_CONF_LOAD_KEY 0
+# define TS_F_TS_CONF_LOOKUP_FAIL 0
+# define TS_F_TS_CONF_SET_DEFAULT_ENGINE 0
+# define TS_F_TS_GET_STATUS_TEXT 0
+# define TS_F_TS_MSG_IMPRINT_SET_ALGO 0
+# define TS_F_TS_REQ_SET_MSG_IMPRINT 0
+# define TS_F_TS_REQ_SET_NONCE 0
+# define TS_F_TS_REQ_SET_POLICY_ID 0
+# define TS_F_TS_RESP_CREATE_RESPONSE 0
+# define TS_F_TS_RESP_CREATE_TST_INFO 0
+# define TS_F_TS_RESP_CTX_ADD_FAILURE_INFO 0
+# define TS_F_TS_RESP_CTX_ADD_MD 0
+# define TS_F_TS_RESP_CTX_ADD_POLICY 0
+# define TS_F_TS_RESP_CTX_NEW 0
+# define TS_F_TS_RESP_CTX_SET_ACCURACY 0
+# define TS_F_TS_RESP_CTX_SET_CERTS 0
+# define TS_F_TS_RESP_CTX_SET_DEF_POLICY 0
+# define TS_F_TS_RESP_CTX_SET_SIGNER_CERT 0
+# define TS_F_TS_RESP_CTX_SET_STATUS_INFO 0
+# define TS_F_TS_RESP_GET_POLICY 0
+# define TS_F_TS_RESP_SET_GENTIME_WITH_PRECISION 0
+# define TS_F_TS_RESP_SET_STATUS_INFO 0
+# define TS_F_TS_RESP_SET_TST_INFO 0
+# define TS_F_TS_RESP_SIGN 0
+# define TS_F_TS_RESP_VERIFY_SIGNATURE 0
+# define TS_F_TS_TST_INFO_SET_ACCURACY 0
+# define TS_F_TS_TST_INFO_SET_MSG_IMPRINT 0
+# define TS_F_TS_TST_INFO_SET_NONCE 0
+# define TS_F_TS_TST_INFO_SET_POLICY_ID 0
+# define TS_F_TS_TST_INFO_SET_SERIAL 0
+# define TS_F_TS_TST_INFO_SET_TIME 0
+# define TS_F_TS_TST_INFO_SET_TSA 0
+# define TS_F_TS_VERIFY 0
+# define TS_F_TS_VERIFY_CERT 0
+# define TS_F_TS_VERIFY_CTX_NEW 0
+# endif
+
+/*
+ * UI function codes.
+ */
+# define UI_F_CLOSE_CONSOLE 0
+# define UI_F_ECHO_CONSOLE 0
+# define UI_F_GENERAL_ALLOCATE_BOOLEAN 0
+# define UI_F_GENERAL_ALLOCATE_PROMPT 0
+# define UI_F_NOECHO_CONSOLE 0
+# define UI_F_OPEN_CONSOLE 0
+# define UI_F_UI_CONSTRUCT_PROMPT 0
+# define UI_F_UI_CREATE_METHOD 0
+# define UI_F_UI_CTRL 0
+# define UI_F_UI_DUP_ERROR_STRING 0
+# define UI_F_UI_DUP_INFO_STRING 0
+# define UI_F_UI_DUP_INPUT_BOOLEAN 0
+# define UI_F_UI_DUP_INPUT_STRING 0
+# define UI_F_UI_DUP_USER_DATA 0
+# define UI_F_UI_DUP_VERIFY_STRING 0
+# define UI_F_UI_GET0_RESULT 0
+# define UI_F_UI_GET_RESULT_LENGTH 0
+# define UI_F_UI_NEW_METHOD 0
+# define UI_F_UI_PROCESS 0
+# define UI_F_UI_SET_RESULT 0
+# define UI_F_UI_SET_RESULT_EX 0
+
+/*
+ * X509 function codes.
+ */
+# define X509_F_ADD_CERT_DIR 0
+# define X509_F_BUILD_CHAIN 0
+# define X509_F_BY_FILE_CTRL 0
+# define X509_F_CHECK_NAME_CONSTRAINTS 0
+# define X509_F_CHECK_POLICY 0
+# define X509_F_DANE_I2D 0
+# define X509_F_DIR_CTRL 0
+# define X509_F_GET_CERT_BY_SUBJECT 0
+# define X509_F_I2D_X509_AUX 0
+# define X509_F_LOOKUP_CERTS_SK 0
+# define X509_F_NETSCAPE_SPKI_B64_DECODE 0
+# define X509_F_NETSCAPE_SPKI_B64_ENCODE 0
+# define X509_F_NEW_DIR 0
+# define X509_F_X509AT_ADD1_ATTR 0
+# define X509_F_X509V3_ADD_EXT 0
+# define X509_F_X509_ATTRIBUTE_CREATE_BY_NID 0
+# define X509_F_X509_ATTRIBUTE_CREATE_BY_OBJ 0
+# define X509_F_X509_ATTRIBUTE_CREATE_BY_TXT 0
+# define X509_F_X509_ATTRIBUTE_GET0_DATA 0
+# define X509_F_X509_ATTRIBUTE_SET1_DATA 0
+# define X509_F_X509_CHECK_PRIVATE_KEY 0
+# define X509_F_X509_CRL_DIFF 0
+# define X509_F_X509_CRL_METHOD_NEW 0
+# define X509_F_X509_CRL_PRINT_FP 0
+# define X509_F_X509_EXTENSION_CREATE_BY_NID 0
+# define X509_F_X509_EXTENSION_CREATE_BY_OBJ 0
+# define X509_F_X509_GET_PUBKEY_PARAMETERS 0
+# define X509_F_X509_LOAD_CERT_CRL_FILE 0
+# define X509_F_X509_LOAD_CERT_FILE 0
+# define X509_F_X509_LOAD_CRL_FILE 0
+# define X509_F_X509_LOOKUP_METH_NEW 0
+# define X509_F_X509_LOOKUP_NEW 0
+# define X509_F_X509_NAME_ADD_ENTRY 0
+# define X509_F_X509_NAME_CANON 0
+# define X509_F_X509_NAME_ENTRY_CREATE_BY_NID 0
+# define X509_F_X509_NAME_ENTRY_CREATE_BY_TXT 0
+# define X509_F_X509_NAME_ENTRY_SET_OBJECT 0
+# define X509_F_X509_NAME_ONELINE 0
+# define X509_F_X509_NAME_PRINT 0
+# define X509_F_X509_OBJECT_NEW 0
+# define X509_F_X509_PRINT_EX_FP 0
+# define X509_F_X509_PUBKEY_DECODE 0
+# define X509_F_X509_PUBKEY_GET 0
+# define X509_F_X509_PUBKEY_GET0 0
+# define X509_F_X509_PUBKEY_SET 0
+# define X509_F_X509_REQ_CHECK_PRIVATE_KEY 0
+# define X509_F_X509_REQ_PRINT_EX 0
+# define X509_F_X509_REQ_PRINT_FP 0
+# define X509_F_X509_REQ_TO_X509 0
+# define X509_F_X509_STORE_ADD_CERT 0
+# define X509_F_X509_STORE_ADD_CRL 0
+# define X509_F_X509_STORE_ADD_LOOKUP 0
+# define X509_F_X509_STORE_CTX_GET1_ISSUER 0
+# define X509_F_X509_STORE_CTX_INIT 0
+# define X509_F_X509_STORE_CTX_NEW 0
+# define X509_F_X509_STORE_CTX_PURPOSE_INHERIT 0
+# define X509_F_X509_STORE_NEW 0
+# define X509_F_X509_TO_X509_REQ 0
+# define X509_F_X509_TRUST_ADD 0
+# define X509_F_X509_TRUST_SET 0
+# define X509_F_X509_VERIFY_CERT 0
+# define X509_F_X509_VERIFY_PARAM_NEW 0
+
+/*
+ * X509V3 function codes.
+ */
+# define X509V3_F_A2I_GENERAL_NAME 0
+# define X509V3_F_ADDR_VALIDATE_PATH_INTERNAL 0
+# define X509V3_F_ASIDENTIFIERCHOICE_CANONIZE 0
+# define X509V3_F_ASIDENTIFIERCHOICE_IS_CANONICAL 0
+# define X509V3_F_BIGNUM_TO_STRING 0
+# define X509V3_F_COPY_EMAIL 0
+# define X509V3_F_COPY_ISSUER 0
+# define X509V3_F_DO_DIRNAME 0
+# define X509V3_F_DO_EXT_I2D 0
+# define X509V3_F_DO_EXT_NCONF 0
+# define X509V3_F_GNAMES_FROM_SECTNAME 0
+# define X509V3_F_I2S_ASN1_ENUMERATED 0
+# define X509V3_F_I2S_ASN1_IA5STRING 0
+# define X509V3_F_I2S_ASN1_INTEGER 0
+# define X509V3_F_I2V_AUTHORITY_INFO_ACCESS 0
+# define X509V3_F_LEVEL_ADD_NODE 0
+# define X509V3_F_NOTICE_SECTION 0
+# define X509V3_F_NREF_NOS 0
+# define X509V3_F_POLICY_CACHE_CREATE 0
+# define X509V3_F_POLICY_CACHE_NEW 0
+# define X509V3_F_POLICY_DATA_NEW 0
+# define X509V3_F_POLICY_SECTION 0
+# define X509V3_F_PROCESS_PCI_VALUE 0
+# define X509V3_F_R2I_CERTPOL 0
+# define X509V3_F_R2I_PCI 0
+# define X509V3_F_S2I_ASN1_IA5STRING 0
+# define X509V3_F_S2I_ASN1_INTEGER 0
+# define X509V3_F_S2I_ASN1_OCTET_STRING 0
+# define X509V3_F_S2I_SKEY_ID 0
+# define X509V3_F_SET_DIST_POINT_NAME 0
+# define X509V3_F_SXNET_ADD_ID_ASC 0
+# define X509V3_F_SXNET_ADD_ID_INTEGER 0
+# define X509V3_F_SXNET_ADD_ID_ULONG 0
+# define X509V3_F_SXNET_GET_ID_ASC 0
+# define X509V3_F_SXNET_GET_ID_ULONG 0
+# define X509V3_F_TREE_INIT 0
+# define X509V3_F_V2I_ASIDENTIFIERS 0
+# define X509V3_F_V2I_ASN1_BIT_STRING 0
+# define X509V3_F_V2I_AUTHORITY_INFO_ACCESS 0
+# define X509V3_F_V2I_AUTHORITY_KEYID 0
+# define X509V3_F_V2I_BASIC_CONSTRAINTS 0
+# define X509V3_F_V2I_CRLD 0
+# define X509V3_F_V2I_EXTENDED_KEY_USAGE 0
+# define X509V3_F_V2I_GENERAL_NAMES 0
+# define X509V3_F_V2I_GENERAL_NAME_EX 0
+# define X509V3_F_V2I_IDP 0
+# define X509V3_F_V2I_IPADDRBLOCKS 0
+# define X509V3_F_V2I_ISSUER_ALT 0
+# define X509V3_F_V2I_NAME_CONSTRAINTS 0
+# define X509V3_F_V2I_POLICY_CONSTRAINTS 0
+# define X509V3_F_V2I_POLICY_MAPPINGS 0
+# define X509V3_F_V2I_SUBJECT_ALT 0
+# define X509V3_F_V2I_TLS_FEATURE 0
+# define X509V3_F_V3_GENERIC_EXTENSION 0
+# define X509V3_F_X509V3_ADD1_I2D 0
+# define X509V3_F_X509V3_ADD_VALUE 0
+# define X509V3_F_X509V3_EXT_ADD 0
+# define X509V3_F_X509V3_EXT_ADD_ALIAS 0
+# define X509V3_F_X509V3_EXT_I2D 0
+# define X509V3_F_X509V3_EXT_NCONF 0
+# define X509V3_F_X509V3_GET_SECTION 0
+# define X509V3_F_X509V3_GET_STRING 0
+# define X509V3_F_X509V3_GET_VALUE_BOOL 0
+# define X509V3_F_X509V3_PARSE_LIST 0
+# define X509V3_F_X509_PURPOSE_ADD 0
+# define X509V3_F_X509_PURPOSE_SET 0
+
+/*
+ * Compatibility defines.
+ */
+# define EVP_R_OPERATON_NOT_INITIALIZED EVP_R_OPERATION_NOT_INITIALIZED
+
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/ct.h b/include/openssl/ct.h
new file mode 100644
index 00000000..06c41b70
--- /dev/null
+++ b/include/openssl/ct.h
@@ -0,0 +1,573 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\ct.h.in
+ *
+ * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_CT_H
+# define OPENSSL_CT_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CT_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CT
+# include <openssl/types.h>
+# include <openssl/safestack.h>
+# include <openssl/x509.h>
+# include <openssl/cterr.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+
+/* Minimum RSA key size, from RFC6962 */
+# define SCT_MIN_RSA_BITS 2048
+
+/* All hashes are SHA256 in v1 of Certificate Transparency */
+# define CT_V1_HASHLEN SHA256_DIGEST_LENGTH
+
+SKM_DEFINE_STACK_OF_INTERNAL(SCT, SCT, SCT)
+#define sk_SCT_num(sk) OPENSSL_sk_num(ossl_check_const_SCT_sk_type(sk))
+#define sk_SCT_value(sk, idx) ((SCT *)OPENSSL_sk_value(ossl_check_const_SCT_sk_type(sk), (idx)))
+#define sk_SCT_new(cmp) ((STACK_OF(SCT) *)OPENSSL_sk_new(ossl_check_SCT_compfunc_type(cmp)))
+#define sk_SCT_new_null() ((STACK_OF(SCT) *)OPENSSL_sk_new_null())
+#define sk_SCT_new_reserve(cmp, n) ((STACK_OF(SCT) *)OPENSSL_sk_new_reserve(ossl_check_SCT_compfunc_type(cmp), (n)))
+#define sk_SCT_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SCT_sk_type(sk), (n))
+#define sk_SCT_free(sk) OPENSSL_sk_free(ossl_check_SCT_sk_type(sk))
+#define sk_SCT_zero(sk) OPENSSL_sk_zero(ossl_check_SCT_sk_type(sk))
+#define sk_SCT_delete(sk, i) ((SCT *)OPENSSL_sk_delete(ossl_check_SCT_sk_type(sk), (i)))
+#define sk_SCT_delete_ptr(sk, ptr) ((SCT *)OPENSSL_sk_delete_ptr(ossl_check_SCT_sk_type(sk), ossl_check_SCT_type(ptr)))
+#define sk_SCT_push(sk, ptr) OPENSSL_sk_push(ossl_check_SCT_sk_type(sk), ossl_check_SCT_type(ptr))
+#define sk_SCT_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SCT_sk_type(sk), ossl_check_SCT_type(ptr))
+#define sk_SCT_pop(sk) ((SCT *)OPENSSL_sk_pop(ossl_check_SCT_sk_type(sk)))
+#define sk_SCT_shift(sk) ((SCT *)OPENSSL_sk_shift(ossl_check_SCT_sk_type(sk)))
+#define sk_SCT_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SCT_sk_type(sk),ossl_check_SCT_freefunc_type(freefunc))
+#define sk_SCT_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SCT_sk_type(sk), ossl_check_SCT_type(ptr), (idx))
+#define sk_SCT_set(sk, idx, ptr) ((SCT *)OPENSSL_sk_set(ossl_check_SCT_sk_type(sk), (idx), ossl_check_SCT_type(ptr)))
+#define sk_SCT_find(sk, ptr) OPENSSL_sk_find(ossl_check_SCT_sk_type(sk), ossl_check_SCT_type(ptr))
+#define sk_SCT_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SCT_sk_type(sk), ossl_check_SCT_type(ptr))
+#define sk_SCT_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SCT_sk_type(sk), ossl_check_SCT_type(ptr), pnum)
+#define sk_SCT_sort(sk) OPENSSL_sk_sort(ossl_check_SCT_sk_type(sk))
+#define sk_SCT_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SCT_sk_type(sk))
+#define sk_SCT_dup(sk) ((STACK_OF(SCT) *)OPENSSL_sk_dup(ossl_check_const_SCT_sk_type(sk)))
+#define sk_SCT_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SCT) *)OPENSSL_sk_deep_copy(ossl_check_const_SCT_sk_type(sk), ossl_check_SCT_copyfunc_type(copyfunc), ossl_check_SCT_freefunc_type(freefunc)))
+#define sk_SCT_set_cmp_func(sk, cmp) ((sk_SCT_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SCT_sk_type(sk), ossl_check_SCT_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(CTLOG, CTLOG, CTLOG)
+#define sk_CTLOG_num(sk) OPENSSL_sk_num(ossl_check_const_CTLOG_sk_type(sk))
+#define sk_CTLOG_value(sk, idx) ((CTLOG *)OPENSSL_sk_value(ossl_check_const_CTLOG_sk_type(sk), (idx)))
+#define sk_CTLOG_new(cmp) ((STACK_OF(CTLOG) *)OPENSSL_sk_new(ossl_check_CTLOG_compfunc_type(cmp)))
+#define sk_CTLOG_new_null() ((STACK_OF(CTLOG) *)OPENSSL_sk_new_null())
+#define sk_CTLOG_new_reserve(cmp, n) ((STACK_OF(CTLOG) *)OPENSSL_sk_new_reserve(ossl_check_CTLOG_compfunc_type(cmp), (n)))
+#define sk_CTLOG_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_CTLOG_sk_type(sk), (n))
+#define sk_CTLOG_free(sk) OPENSSL_sk_free(ossl_check_CTLOG_sk_type(sk))
+#define sk_CTLOG_zero(sk) OPENSSL_sk_zero(ossl_check_CTLOG_sk_type(sk))
+#define sk_CTLOG_delete(sk, i) ((CTLOG *)OPENSSL_sk_delete(ossl_check_CTLOG_sk_type(sk), (i)))
+#define sk_CTLOG_delete_ptr(sk, ptr) ((CTLOG *)OPENSSL_sk_delete_ptr(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_type(ptr)))
+#define sk_CTLOG_push(sk, ptr) OPENSSL_sk_push(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_type(ptr))
+#define sk_CTLOG_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_type(ptr))
+#define sk_CTLOG_pop(sk) ((CTLOG *)OPENSSL_sk_pop(ossl_check_CTLOG_sk_type(sk)))
+#define sk_CTLOG_shift(sk) ((CTLOG *)OPENSSL_sk_shift(ossl_check_CTLOG_sk_type(sk)))
+#define sk_CTLOG_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_CTLOG_sk_type(sk),ossl_check_CTLOG_freefunc_type(freefunc))
+#define sk_CTLOG_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_type(ptr), (idx))
+#define sk_CTLOG_set(sk, idx, ptr) ((CTLOG *)OPENSSL_sk_set(ossl_check_CTLOG_sk_type(sk), (idx), ossl_check_CTLOG_type(ptr)))
+#define sk_CTLOG_find(sk, ptr) OPENSSL_sk_find(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_type(ptr))
+#define sk_CTLOG_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_type(ptr))
+#define sk_CTLOG_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_type(ptr), pnum)
+#define sk_CTLOG_sort(sk) OPENSSL_sk_sort(ossl_check_CTLOG_sk_type(sk))
+#define sk_CTLOG_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_CTLOG_sk_type(sk))
+#define sk_CTLOG_dup(sk) ((STACK_OF(CTLOG) *)OPENSSL_sk_dup(ossl_check_const_CTLOG_sk_type(sk)))
+#define sk_CTLOG_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(CTLOG) *)OPENSSL_sk_deep_copy(ossl_check_const_CTLOG_sk_type(sk), ossl_check_CTLOG_copyfunc_type(copyfunc), ossl_check_CTLOG_freefunc_type(freefunc)))
+#define sk_CTLOG_set_cmp_func(sk, cmp) ((sk_CTLOG_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_CTLOG_sk_type(sk), ossl_check_CTLOG_compfunc_type(cmp)))
+
+
+
+typedef enum {
+ CT_LOG_ENTRY_TYPE_NOT_SET = -1,
+ CT_LOG_ENTRY_TYPE_X509 = 0,
+ CT_LOG_ENTRY_TYPE_PRECERT = 1
+} ct_log_entry_type_t;
+
+typedef enum {
+ SCT_VERSION_NOT_SET = -1,
+ SCT_VERSION_V1 = 0
+} sct_version_t;
+
+typedef enum {
+ SCT_SOURCE_UNKNOWN,
+ SCT_SOURCE_TLS_EXTENSION,
+ SCT_SOURCE_X509V3_EXTENSION,
+ SCT_SOURCE_OCSP_STAPLED_RESPONSE
+} sct_source_t;
+
+typedef enum {
+ SCT_VALIDATION_STATUS_NOT_SET,
+ SCT_VALIDATION_STATUS_UNKNOWN_LOG,
+ SCT_VALIDATION_STATUS_VALID,
+ SCT_VALIDATION_STATUS_INVALID,
+ SCT_VALIDATION_STATUS_UNVERIFIED,
+ SCT_VALIDATION_STATUS_UNKNOWN_VERSION
+} sct_validation_status_t;
+
+/******************************************
+ * CT policy evaluation context functions *
+ ******************************************/
+
+/*
+ * Creates a new, empty policy evaluation context associated with the given
+ * library context and property query string.
+ * The caller is responsible for calling CT_POLICY_EVAL_CTX_free when finished
+ * with the CT_POLICY_EVAL_CTX.
+ */
+CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new_ex(OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+/*
+ * The same as CT_POLICY_EVAL_CTX_new_ex() but the default library
+ * context and property query string is used.
+ */
+CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new(void);
+
+/* Deletes a policy evaluation context and anything it owns. */
+void CT_POLICY_EVAL_CTX_free(CT_POLICY_EVAL_CTX *ctx);
+
+/* Gets the peer certificate that the SCTs are for */
+X509* CT_POLICY_EVAL_CTX_get0_cert(const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Sets the certificate associated with the received SCTs.
+ * Increments the reference count of cert.
+ * Returns 1 on success, 0 otherwise.
+ */
+int CT_POLICY_EVAL_CTX_set1_cert(CT_POLICY_EVAL_CTX *ctx, X509 *cert);
+
+/* Gets the issuer of the aforementioned certificate */
+X509* CT_POLICY_EVAL_CTX_get0_issuer(const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Sets the issuer of the certificate associated with the received SCTs.
+ * Increments the reference count of issuer.
+ * Returns 1 on success, 0 otherwise.
+ */
+int CT_POLICY_EVAL_CTX_set1_issuer(CT_POLICY_EVAL_CTX *ctx, X509 *issuer);
+
+/* Gets the CT logs that are trusted sources of SCTs */
+const CTLOG_STORE *CT_POLICY_EVAL_CTX_get0_log_store(const CT_POLICY_EVAL_CTX *ctx);
+
+/* Sets the log store that is in use. It must outlive the CT_POLICY_EVAL_CTX. */
+void CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(CT_POLICY_EVAL_CTX *ctx,
+ CTLOG_STORE *log_store);
+
+/*
+ * Gets the time, in milliseconds since the Unix epoch, that will be used as the
+ * current time when checking whether an SCT was issued in the future.
+ * Such SCTs will fail validation, as required by RFC6962.
+ */
+uint64_t CT_POLICY_EVAL_CTX_get_time(const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Sets the time to evaluate SCTs against, in milliseconds since the Unix epoch.
+ * If an SCT's timestamp is after this time, it will be interpreted as having
+ * been issued in the future. RFC6962 states that "TLS clients MUST reject SCTs
+ * whose timestamp is in the future", so an SCT will not validate in this case.
+ */
+void CT_POLICY_EVAL_CTX_set_time(CT_POLICY_EVAL_CTX *ctx, uint64_t time_in_ms);
+
+/*****************
+ * SCT functions *
+ *****************/
+
+/*
+ * Creates a new, blank SCT.
+ * The caller is responsible for calling SCT_free when finished with the SCT.
+ */
+SCT *SCT_new(void);
+
+/*
+ * Creates a new SCT from some base64-encoded strings.
+ * The caller is responsible for calling SCT_free when finished with the SCT.
+ */
+SCT *SCT_new_from_base64(unsigned char version,
+ const char *logid_base64,
+ ct_log_entry_type_t entry_type,
+ uint64_t timestamp,
+ const char *extensions_base64,
+ const char *signature_base64);
+
+/*
+ * Frees the SCT and the underlying data structures.
+ */
+void SCT_free(SCT *sct);
+
+/*
+ * Free a stack of SCTs, and the underlying SCTs themselves.
+ * Intended to be compatible with X509V3_EXT_FREE.
+ */
+void SCT_LIST_free(STACK_OF(SCT) *a);
+
+/*
+ * Returns the version of the SCT.
+ */
+sct_version_t SCT_get_version(const SCT *sct);
+
+/*
+ * Set the version of an SCT.
+ * Returns 1 on success, 0 if the version is unrecognized.
+ */
+__owur int SCT_set_version(SCT *sct, sct_version_t version);
+
+/*
+ * Returns the log entry type of the SCT.
+ */
+ct_log_entry_type_t SCT_get_log_entry_type(const SCT *sct);
+
+/*
+ * Set the log entry type of an SCT.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type);
+
+/*
+ * Gets the ID of the log that an SCT came from.
+ * Ownership of the log ID remains with the SCT.
+ * Returns the length of the log ID.
+ */
+size_t SCT_get0_log_id(const SCT *sct, unsigned char **log_id);
+
+/*
+ * Set the log ID of an SCT to point directly to the *log_id specified.
+ * The SCT takes ownership of the specified pointer.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len);
+
+/*
+ * Set the log ID of an SCT.
+ * This makes a copy of the log_id.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set1_log_id(SCT *sct, const unsigned char *log_id,
+ size_t log_id_len);
+
+/*
+ * Returns the timestamp for the SCT (epoch time in milliseconds).
+ */
+uint64_t SCT_get_timestamp(const SCT *sct);
+
+/*
+ * Set the timestamp of an SCT (epoch time in milliseconds).
+ */
+void SCT_set_timestamp(SCT *sct, uint64_t timestamp);
+
+/*
+ * Return the NID for the signature used by the SCT.
+ * For CT v1, this will be either NID_sha256WithRSAEncryption or
+ * NID_ecdsa_with_SHA256 (or NID_undef if incorrect/unset).
+ */
+int SCT_get_signature_nid(const SCT *sct);
+
+/*
+ * Set the signature type of an SCT
+ * For CT v1, this should be either NID_sha256WithRSAEncryption or
+ * NID_ecdsa_with_SHA256.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set_signature_nid(SCT *sct, int nid);
+
+/*
+ * Set *ext to point to the extension data for the SCT. ext must not be NULL.
+ * The SCT retains ownership of this pointer.
+ * Returns length of the data pointed to.
+ */
+size_t SCT_get0_extensions(const SCT *sct, unsigned char **ext);
+
+/*
+ * Set the extensions of an SCT to point directly to the *ext specified.
+ * The SCT takes ownership of the specified pointer.
+ */
+void SCT_set0_extensions(SCT *sct, unsigned char *ext, size_t ext_len);
+
+/*
+ * Set the extensions of an SCT.
+ * This takes a copy of the ext.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set1_extensions(SCT *sct, const unsigned char *ext,
+ size_t ext_len);
+
+/*
+ * Set *sig to point to the signature for the SCT. sig must not be NULL.
+ * The SCT retains ownership of this pointer.
+ * Returns length of the data pointed to.
+ */
+size_t SCT_get0_signature(const SCT *sct, unsigned char **sig);
+
+/*
+ * Set the signature of an SCT to point directly to the *sig specified.
+ * The SCT takes ownership of the specified pointer.
+ */
+void SCT_set0_signature(SCT *sct, unsigned char *sig, size_t sig_len);
+
+/*
+ * Set the signature of an SCT to be a copy of the *sig specified.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set1_signature(SCT *sct, const unsigned char *sig,
+ size_t sig_len);
+
+/*
+ * The origin of this SCT, e.g. TLS extension, OCSP response, etc.
+ */
+sct_source_t SCT_get_source(const SCT *sct);
+
+/*
+ * Set the origin of this SCT, e.g. TLS extension, OCSP response, etc.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set_source(SCT *sct, sct_source_t source);
+
+/*
+ * Returns a text string describing the validation status of |sct|.
+ */
+const char *SCT_validation_status_string(const SCT *sct);
+
+/*
+ * Pretty-prints an |sct| to |out|.
+ * It will be indented by the number of spaces specified by |indent|.
+ * If |logs| is not NULL, it will be used to lookup the CT log that the SCT came
+ * from, so that the log name can be printed.
+ */
+void SCT_print(const SCT *sct, BIO *out, int indent, const CTLOG_STORE *logs);
+
+/*
+ * Pretty-prints an |sct_list| to |out|.
+ * It will be indented by the number of spaces specified by |indent|.
+ * SCTs will be delimited by |separator|.
+ * If |logs| is not NULL, it will be used to lookup the CT log that each SCT
+ * came from, so that the log names can be printed.
+ */
+void SCT_LIST_print(const STACK_OF(SCT) *sct_list, BIO *out, int indent,
+ const char *separator, const CTLOG_STORE *logs);
+
+/*
+ * Gets the last result of validating this SCT.
+ * If it has not been validated yet, returns SCT_VALIDATION_STATUS_NOT_SET.
+ */
+sct_validation_status_t SCT_get_validation_status(const SCT *sct);
+
+/*
+ * Validates the given SCT with the provided context.
+ * Sets the "validation_status" field of the SCT.
+ * Returns 1 if the SCT is valid and the signature verifies.
+ * Returns 0 if the SCT is invalid or could not be verified.
+ * Returns -1 if an error occurs.
+ */
+__owur int SCT_validate(SCT *sct, const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Validates the given list of SCTs with the provided context.
+ * Sets the "validation_status" field of each SCT.
+ * Returns 1 if there are no invalid SCTs and all signatures verify.
+ * Returns 0 if at least one SCT is invalid or could not be verified.
+ * Returns a negative integer if an error occurs.
+ */
+__owur int SCT_LIST_validate(const STACK_OF(SCT) *scts,
+ CT_POLICY_EVAL_CTX *ctx);
+
+
+/*********************************
+ * SCT parsing and serialization *
+ *********************************/
+
+/*
+ * Serialize (to TLS format) a stack of SCTs and return the length.
+ * "a" must not be NULL.
+ * If "pp" is NULL, just return the length of what would have been serialized.
+ * If "pp" is not NULL and "*pp" is null, function will allocate a new pointer
+ * for data that caller is responsible for freeing (only if function returns
+ * successfully).
+ * If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring
+ * that "*pp" is large enough to accept all of the serialized data.
+ * Returns < 0 on error, >= 0 indicating bytes written (or would have been)
+ * on success.
+ */
+__owur int i2o_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp);
+
+/*
+ * Convert TLS format SCT list to a stack of SCTs.
+ * If "a" or "*a" is NULL, a new stack will be created that the caller is
+ * responsible for freeing (by calling SCT_LIST_free).
+ * "**pp" and "*pp" must not be NULL.
+ * Upon success, "*pp" will point to after the last bytes read, and a stack
+ * will be returned.
+ * Upon failure, a NULL pointer will be returned, and the position of "*pp" is
+ * not defined.
+ */
+STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
+ size_t len);
+
+/*
+ * Serialize (to DER format) a stack of SCTs and return the length.
+ * "a" must not be NULL.
+ * If "pp" is NULL, just returns the length of what would have been serialized.
+ * If "pp" is not NULL and "*pp" is null, function will allocate a new pointer
+ * for data that caller is responsible for freeing (only if function returns
+ * successfully).
+ * If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring
+ * that "*pp" is large enough to accept all of the serialized data.
+ * Returns < 0 on error, >= 0 indicating bytes written (or would have been)
+ * on success.
+ */
+__owur int i2d_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp);
+
+/*
+ * Parses an SCT list in DER format and returns it.
+ * If "a" or "*a" is NULL, a new stack will be created that the caller is
+ * responsible for freeing (by calling SCT_LIST_free).
+ * "**pp" and "*pp" must not be NULL.
+ * Upon success, "*pp" will point to after the last bytes read, and a stack
+ * will be returned.
+ * Upon failure, a NULL pointer will be returned, and the position of "*pp" is
+ * not defined.
+ */
+STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
+ long len);
+
+/*
+ * Serialize (to TLS format) an |sct| and write it to |out|.
+ * If |out| is null, no SCT will be output but the length will still be returned.
+ * If |out| points to a null pointer, a string will be allocated to hold the
+ * TLS-format SCT. It is the responsibility of the caller to free it.
+ * If |out| points to an allocated string, the TLS-format SCT will be written
+ * to it.
+ * The length of the SCT in TLS format will be returned.
+ */
+__owur int i2o_SCT(const SCT *sct, unsigned char **out);
+
+/*
+ * Parses an SCT in TLS format and returns it.
+ * If |psct| is not null, it will end up pointing to the parsed SCT. If it
+ * already points to a non-null pointer, the pointer will be free'd.
+ * |in| should be a pointer to a string containing the TLS-format SCT.
+ * |in| will be advanced to the end of the SCT if parsing succeeds.
+ * |len| should be the length of the SCT in |in|.
+ * Returns NULL if an error occurs.
+ * If the SCT is an unsupported version, only the SCT's 'sct' and 'sct_len'
+ * fields will be populated (with |in| and |len| respectively).
+ */
+SCT *o2i_SCT(SCT **psct, const unsigned char **in, size_t len);
+
+/********************
+ * CT log functions *
+ ********************/
+
+/*
+ * Creates a new CT log instance with the given |public_key| and |name| and
+ * associates it with the give library context |libctx| and property query
+ * string |propq|.
+ * Takes ownership of |public_key| but copies |name|.
+ * Returns NULL if malloc fails or if |public_key| cannot be converted to DER.
+ * Should be deleted by the caller using CTLOG_free when no longer needed.
+ */
+CTLOG *CTLOG_new_ex(EVP_PKEY *public_key, const char *name, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+/*
+ * The same as CTLOG_new_ex except that the default library context and
+ * property query string are used.
+ */
+CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name);
+
+/*
+ * Creates a new CTLOG instance with the base64-encoded SubjectPublicKeyInfo DER
+ * in |pkey_base64| and associated with the given library context |libctx| and
+ * property query string |propq|. The |name| is a string to help users identify
+ * this log.
+ * Returns 1 on success, 0 on failure.
+ * Should be deleted by the caller using CTLOG_free when no longer needed.
+ */
+int CTLOG_new_from_base64_ex(CTLOG **ct_log, const char *pkey_base64,
+ const char *name, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+/*
+ * The same as CTLOG_new_from_base64_ex() except that the default
+ * library context and property query string are used.
+ * Returns 1 on success, 0 on failure.
+ */
+int CTLOG_new_from_base64(CTLOG ** ct_log,
+ const char *pkey_base64, const char *name);
+
+/*
+ * Deletes a CT log instance and its fields.
+ */
+void CTLOG_free(CTLOG *log);
+
+/* Gets the name of the CT log */
+const char *CTLOG_get0_name(const CTLOG *log);
+/* Gets the ID of the CT log */
+void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id,
+ size_t *log_id_len);
+/* Gets the public key of the CT log */
+EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log);
+
+/**************************
+ * CT log store functions *
+ **************************/
+
+/*
+ * Creates a new CT log store and associates it with the given libctx and
+ * property query string.
+ * Should be deleted by the caller using CTLOG_STORE_free when no longer needed.
+ */
+CTLOG_STORE *CTLOG_STORE_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+/*
+ * Same as CTLOG_STORE_new_ex except that the default libctx and
+ * property query string are used.
+ * Should be deleted by the caller using CTLOG_STORE_free when no longer needed.
+ */
+CTLOG_STORE *CTLOG_STORE_new(void);
+
+/*
+ * Deletes a CT log store and all of the CT log instances held within.
+ */
+void CTLOG_STORE_free(CTLOG_STORE *store);
+
+/*
+ * Finds a CT log in the store based on its log ID.
+ * Returns the CT log, or NULL if no match is found.
+ */
+const CTLOG *CTLOG_STORE_get0_log_by_id(const CTLOG_STORE *store,
+ const uint8_t *log_id,
+ size_t log_id_len);
+
+/*
+ * Loads a CT log list into a |store| from a |file|.
+ * Returns 1 if loading is successful, or 0 otherwise.
+ */
+__owur int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file);
+
+/*
+ * Loads the default CT log list into a |store|.
+ * Returns 1 if loading is successful, or 0 otherwise.
+ */
+__owur int CTLOG_STORE_load_default_file(CTLOG_STORE *store);
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/ct.h.in b/include/openssl/ct.h.in
new file mode 100644
index 00000000..16086b33
--- /dev/null
+++ b/include/openssl/ct.h.in
@@ -0,0 +1,525 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_CT_H
+# define OPENSSL_CT_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_CT_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_CT
+# include <openssl/types.h>
+# include <openssl/safestack.h>
+# include <openssl/x509.h>
+# include <openssl/cterr.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+
+/* Minimum RSA key size, from RFC6962 */
+# define SCT_MIN_RSA_BITS 2048
+
+/* All hashes are SHA256 in v1 of Certificate Transparency */
+# define CT_V1_HASHLEN SHA256_DIGEST_LENGTH
+
+{-
+ generate_stack_macros("SCT")
+ .generate_stack_macros("CTLOG");
+-}
+
+
+typedef enum {
+ CT_LOG_ENTRY_TYPE_NOT_SET = -1,
+ CT_LOG_ENTRY_TYPE_X509 = 0,
+ CT_LOG_ENTRY_TYPE_PRECERT = 1
+} ct_log_entry_type_t;
+
+typedef enum {
+ SCT_VERSION_NOT_SET = -1,
+ SCT_VERSION_V1 = 0
+} sct_version_t;
+
+typedef enum {
+ SCT_SOURCE_UNKNOWN,
+ SCT_SOURCE_TLS_EXTENSION,
+ SCT_SOURCE_X509V3_EXTENSION,
+ SCT_SOURCE_OCSP_STAPLED_RESPONSE
+} sct_source_t;
+
+typedef enum {
+ SCT_VALIDATION_STATUS_NOT_SET,
+ SCT_VALIDATION_STATUS_UNKNOWN_LOG,
+ SCT_VALIDATION_STATUS_VALID,
+ SCT_VALIDATION_STATUS_INVALID,
+ SCT_VALIDATION_STATUS_UNVERIFIED,
+ SCT_VALIDATION_STATUS_UNKNOWN_VERSION
+} sct_validation_status_t;
+
+/******************************************
+ * CT policy evaluation context functions *
+ ******************************************/
+
+/*
+ * Creates a new, empty policy evaluation context associated with the given
+ * library context and property query string.
+ * The caller is responsible for calling CT_POLICY_EVAL_CTX_free when finished
+ * with the CT_POLICY_EVAL_CTX.
+ */
+CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new_ex(OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+/*
+ * The same as CT_POLICY_EVAL_CTX_new_ex() but the default library
+ * context and property query string is used.
+ */
+CT_POLICY_EVAL_CTX *CT_POLICY_EVAL_CTX_new(void);
+
+/* Deletes a policy evaluation context and anything it owns. */
+void CT_POLICY_EVAL_CTX_free(CT_POLICY_EVAL_CTX *ctx);
+
+/* Gets the peer certificate that the SCTs are for */
+X509* CT_POLICY_EVAL_CTX_get0_cert(const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Sets the certificate associated with the received SCTs.
+ * Increments the reference count of cert.
+ * Returns 1 on success, 0 otherwise.
+ */
+int CT_POLICY_EVAL_CTX_set1_cert(CT_POLICY_EVAL_CTX *ctx, X509 *cert);
+
+/* Gets the issuer of the aforementioned certificate */
+X509* CT_POLICY_EVAL_CTX_get0_issuer(const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Sets the issuer of the certificate associated with the received SCTs.
+ * Increments the reference count of issuer.
+ * Returns 1 on success, 0 otherwise.
+ */
+int CT_POLICY_EVAL_CTX_set1_issuer(CT_POLICY_EVAL_CTX *ctx, X509 *issuer);
+
+/* Gets the CT logs that are trusted sources of SCTs */
+const CTLOG_STORE *CT_POLICY_EVAL_CTX_get0_log_store(const CT_POLICY_EVAL_CTX *ctx);
+
+/* Sets the log store that is in use. It must outlive the CT_POLICY_EVAL_CTX. */
+void CT_POLICY_EVAL_CTX_set_shared_CTLOG_STORE(CT_POLICY_EVAL_CTX *ctx,
+ CTLOG_STORE *log_store);
+
+/*
+ * Gets the time, in milliseconds since the Unix epoch, that will be used as the
+ * current time when checking whether an SCT was issued in the future.
+ * Such SCTs will fail validation, as required by RFC6962.
+ */
+uint64_t CT_POLICY_EVAL_CTX_get_time(const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Sets the time to evaluate SCTs against, in milliseconds since the Unix epoch.
+ * If an SCT's timestamp is after this time, it will be interpreted as having
+ * been issued in the future. RFC6962 states that "TLS clients MUST reject SCTs
+ * whose timestamp is in the future", so an SCT will not validate in this case.
+ */
+void CT_POLICY_EVAL_CTX_set_time(CT_POLICY_EVAL_CTX *ctx, uint64_t time_in_ms);
+
+/*****************
+ * SCT functions *
+ *****************/
+
+/*
+ * Creates a new, blank SCT.
+ * The caller is responsible for calling SCT_free when finished with the SCT.
+ */
+SCT *SCT_new(void);
+
+/*
+ * Creates a new SCT from some base64-encoded strings.
+ * The caller is responsible for calling SCT_free when finished with the SCT.
+ */
+SCT *SCT_new_from_base64(unsigned char version,
+ const char *logid_base64,
+ ct_log_entry_type_t entry_type,
+ uint64_t timestamp,
+ const char *extensions_base64,
+ const char *signature_base64);
+
+/*
+ * Frees the SCT and the underlying data structures.
+ */
+void SCT_free(SCT *sct);
+
+/*
+ * Free a stack of SCTs, and the underlying SCTs themselves.
+ * Intended to be compatible with X509V3_EXT_FREE.
+ */
+void SCT_LIST_free(STACK_OF(SCT) *a);
+
+/*
+ * Returns the version of the SCT.
+ */
+sct_version_t SCT_get_version(const SCT *sct);
+
+/*
+ * Set the version of an SCT.
+ * Returns 1 on success, 0 if the version is unrecognized.
+ */
+__owur int SCT_set_version(SCT *sct, sct_version_t version);
+
+/*
+ * Returns the log entry type of the SCT.
+ */
+ct_log_entry_type_t SCT_get_log_entry_type(const SCT *sct);
+
+/*
+ * Set the log entry type of an SCT.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set_log_entry_type(SCT *sct, ct_log_entry_type_t entry_type);
+
+/*
+ * Gets the ID of the log that an SCT came from.
+ * Ownership of the log ID remains with the SCT.
+ * Returns the length of the log ID.
+ */
+size_t SCT_get0_log_id(const SCT *sct, unsigned char **log_id);
+
+/*
+ * Set the log ID of an SCT to point directly to the *log_id specified.
+ * The SCT takes ownership of the specified pointer.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set0_log_id(SCT *sct, unsigned char *log_id, size_t log_id_len);
+
+/*
+ * Set the log ID of an SCT.
+ * This makes a copy of the log_id.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set1_log_id(SCT *sct, const unsigned char *log_id,
+ size_t log_id_len);
+
+/*
+ * Returns the timestamp for the SCT (epoch time in milliseconds).
+ */
+uint64_t SCT_get_timestamp(const SCT *sct);
+
+/*
+ * Set the timestamp of an SCT (epoch time in milliseconds).
+ */
+void SCT_set_timestamp(SCT *sct, uint64_t timestamp);
+
+/*
+ * Return the NID for the signature used by the SCT.
+ * For CT v1, this will be either NID_sha256WithRSAEncryption or
+ * NID_ecdsa_with_SHA256 (or NID_undef if incorrect/unset).
+ */
+int SCT_get_signature_nid(const SCT *sct);
+
+/*
+ * Set the signature type of an SCT
+ * For CT v1, this should be either NID_sha256WithRSAEncryption or
+ * NID_ecdsa_with_SHA256.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set_signature_nid(SCT *sct, int nid);
+
+/*
+ * Set *ext to point to the extension data for the SCT. ext must not be NULL.
+ * The SCT retains ownership of this pointer.
+ * Returns length of the data pointed to.
+ */
+size_t SCT_get0_extensions(const SCT *sct, unsigned char **ext);
+
+/*
+ * Set the extensions of an SCT to point directly to the *ext specified.
+ * The SCT takes ownership of the specified pointer.
+ */
+void SCT_set0_extensions(SCT *sct, unsigned char *ext, size_t ext_len);
+
+/*
+ * Set the extensions of an SCT.
+ * This takes a copy of the ext.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set1_extensions(SCT *sct, const unsigned char *ext,
+ size_t ext_len);
+
+/*
+ * Set *sig to point to the signature for the SCT. sig must not be NULL.
+ * The SCT retains ownership of this pointer.
+ * Returns length of the data pointed to.
+ */
+size_t SCT_get0_signature(const SCT *sct, unsigned char **sig);
+
+/*
+ * Set the signature of an SCT to point directly to the *sig specified.
+ * The SCT takes ownership of the specified pointer.
+ */
+void SCT_set0_signature(SCT *sct, unsigned char *sig, size_t sig_len);
+
+/*
+ * Set the signature of an SCT to be a copy of the *sig specified.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set1_signature(SCT *sct, const unsigned char *sig,
+ size_t sig_len);
+
+/*
+ * The origin of this SCT, e.g. TLS extension, OCSP response, etc.
+ */
+sct_source_t SCT_get_source(const SCT *sct);
+
+/*
+ * Set the origin of this SCT, e.g. TLS extension, OCSP response, etc.
+ * Returns 1 on success, 0 otherwise.
+ */
+__owur int SCT_set_source(SCT *sct, sct_source_t source);
+
+/*
+ * Returns a text string describing the validation status of |sct|.
+ */
+const char *SCT_validation_status_string(const SCT *sct);
+
+/*
+ * Pretty-prints an |sct| to |out|.
+ * It will be indented by the number of spaces specified by |indent|.
+ * If |logs| is not NULL, it will be used to lookup the CT log that the SCT came
+ * from, so that the log name can be printed.
+ */
+void SCT_print(const SCT *sct, BIO *out, int indent, const CTLOG_STORE *logs);
+
+/*
+ * Pretty-prints an |sct_list| to |out|.
+ * It will be indented by the number of spaces specified by |indent|.
+ * SCTs will be delimited by |separator|.
+ * If |logs| is not NULL, it will be used to lookup the CT log that each SCT
+ * came from, so that the log names can be printed.
+ */
+void SCT_LIST_print(const STACK_OF(SCT) *sct_list, BIO *out, int indent,
+ const char *separator, const CTLOG_STORE *logs);
+
+/*
+ * Gets the last result of validating this SCT.
+ * If it has not been validated yet, returns SCT_VALIDATION_STATUS_NOT_SET.
+ */
+sct_validation_status_t SCT_get_validation_status(const SCT *sct);
+
+/*
+ * Validates the given SCT with the provided context.
+ * Sets the "validation_status" field of the SCT.
+ * Returns 1 if the SCT is valid and the signature verifies.
+ * Returns 0 if the SCT is invalid or could not be verified.
+ * Returns -1 if an error occurs.
+ */
+__owur int SCT_validate(SCT *sct, const CT_POLICY_EVAL_CTX *ctx);
+
+/*
+ * Validates the given list of SCTs with the provided context.
+ * Sets the "validation_status" field of each SCT.
+ * Returns 1 if there are no invalid SCTs and all signatures verify.
+ * Returns 0 if at least one SCT is invalid or could not be verified.
+ * Returns a negative integer if an error occurs.
+ */
+__owur int SCT_LIST_validate(const STACK_OF(SCT) *scts,
+ CT_POLICY_EVAL_CTX *ctx);
+
+
+/*********************************
+ * SCT parsing and serialization *
+ *********************************/
+
+/*
+ * Serialize (to TLS format) a stack of SCTs and return the length.
+ * "a" must not be NULL.
+ * If "pp" is NULL, just return the length of what would have been serialized.
+ * If "pp" is not NULL and "*pp" is null, function will allocate a new pointer
+ * for data that caller is responsible for freeing (only if function returns
+ * successfully).
+ * If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring
+ * that "*pp" is large enough to accept all of the serialized data.
+ * Returns < 0 on error, >= 0 indicating bytes written (or would have been)
+ * on success.
+ */
+__owur int i2o_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp);
+
+/*
+ * Convert TLS format SCT list to a stack of SCTs.
+ * If "a" or "*a" is NULL, a new stack will be created that the caller is
+ * responsible for freeing (by calling SCT_LIST_free).
+ * "**pp" and "*pp" must not be NULL.
+ * Upon success, "*pp" will point to after the last bytes read, and a stack
+ * will be returned.
+ * Upon failure, a NULL pointer will be returned, and the position of "*pp" is
+ * not defined.
+ */
+STACK_OF(SCT) *o2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
+ size_t len);
+
+/*
+ * Serialize (to DER format) a stack of SCTs and return the length.
+ * "a" must not be NULL.
+ * If "pp" is NULL, just returns the length of what would have been serialized.
+ * If "pp" is not NULL and "*pp" is null, function will allocate a new pointer
+ * for data that caller is responsible for freeing (only if function returns
+ * successfully).
+ * If "pp" is NULL and "*pp" is not NULL, caller is responsible for ensuring
+ * that "*pp" is large enough to accept all of the serialized data.
+ * Returns < 0 on error, >= 0 indicating bytes written (or would have been)
+ * on success.
+ */
+__owur int i2d_SCT_LIST(const STACK_OF(SCT) *a, unsigned char **pp);
+
+/*
+ * Parses an SCT list in DER format and returns it.
+ * If "a" or "*a" is NULL, a new stack will be created that the caller is
+ * responsible for freeing (by calling SCT_LIST_free).
+ * "**pp" and "*pp" must not be NULL.
+ * Upon success, "*pp" will point to after the last bytes read, and a stack
+ * will be returned.
+ * Upon failure, a NULL pointer will be returned, and the position of "*pp" is
+ * not defined.
+ */
+STACK_OF(SCT) *d2i_SCT_LIST(STACK_OF(SCT) **a, const unsigned char **pp,
+ long len);
+
+/*
+ * Serialize (to TLS format) an |sct| and write it to |out|.
+ * If |out| is null, no SCT will be output but the length will still be returned.
+ * If |out| points to a null pointer, a string will be allocated to hold the
+ * TLS-format SCT. It is the responsibility of the caller to free it.
+ * If |out| points to an allocated string, the TLS-format SCT will be written
+ * to it.
+ * The length of the SCT in TLS format will be returned.
+ */
+__owur int i2o_SCT(const SCT *sct, unsigned char **out);
+
+/*
+ * Parses an SCT in TLS format and returns it.
+ * If |psct| is not null, it will end up pointing to the parsed SCT. If it
+ * already points to a non-null pointer, the pointer will be free'd.
+ * |in| should be a pointer to a string containing the TLS-format SCT.
+ * |in| will be advanced to the end of the SCT if parsing succeeds.
+ * |len| should be the length of the SCT in |in|.
+ * Returns NULL if an error occurs.
+ * If the SCT is an unsupported version, only the SCT's 'sct' and 'sct_len'
+ * fields will be populated (with |in| and |len| respectively).
+ */
+SCT *o2i_SCT(SCT **psct, const unsigned char **in, size_t len);
+
+/********************
+ * CT log functions *
+ ********************/
+
+/*
+ * Creates a new CT log instance with the given |public_key| and |name| and
+ * associates it with the give library context |libctx| and property query
+ * string |propq|.
+ * Takes ownership of |public_key| but copies |name|.
+ * Returns NULL if malloc fails or if |public_key| cannot be converted to DER.
+ * Should be deleted by the caller using CTLOG_free when no longer needed.
+ */
+CTLOG *CTLOG_new_ex(EVP_PKEY *public_key, const char *name, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+/*
+ * The same as CTLOG_new_ex except that the default library context and
+ * property query string are used.
+ */
+CTLOG *CTLOG_new(EVP_PKEY *public_key, const char *name);
+
+/*
+ * Creates a new CTLOG instance with the base64-encoded SubjectPublicKeyInfo DER
+ * in |pkey_base64| and associated with the given library context |libctx| and
+ * property query string |propq|. The |name| is a string to help users identify
+ * this log.
+ * Returns 1 on success, 0 on failure.
+ * Should be deleted by the caller using CTLOG_free when no longer needed.
+ */
+int CTLOG_new_from_base64_ex(CTLOG **ct_log, const char *pkey_base64,
+ const char *name, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+/*
+ * The same as CTLOG_new_from_base64_ex() except that the default
+ * library context and property query string are used.
+ * Returns 1 on success, 0 on failure.
+ */
+int CTLOG_new_from_base64(CTLOG ** ct_log,
+ const char *pkey_base64, const char *name);
+
+/*
+ * Deletes a CT log instance and its fields.
+ */
+void CTLOG_free(CTLOG *log);
+
+/* Gets the name of the CT log */
+const char *CTLOG_get0_name(const CTLOG *log);
+/* Gets the ID of the CT log */
+void CTLOG_get0_log_id(const CTLOG *log, const uint8_t **log_id,
+ size_t *log_id_len);
+/* Gets the public key of the CT log */
+EVP_PKEY *CTLOG_get0_public_key(const CTLOG *log);
+
+/**************************
+ * CT log store functions *
+ **************************/
+
+/*
+ * Creates a new CT log store and associates it with the given libctx and
+ * property query string.
+ * Should be deleted by the caller using CTLOG_STORE_free when no longer needed.
+ */
+CTLOG_STORE *CTLOG_STORE_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+/*
+ * Same as CTLOG_STORE_new_ex except that the default libctx and
+ * property query string are used.
+ * Should be deleted by the caller using CTLOG_STORE_free when no longer needed.
+ */
+CTLOG_STORE *CTLOG_STORE_new(void);
+
+/*
+ * Deletes a CT log store and all of the CT log instances held within.
+ */
+void CTLOG_STORE_free(CTLOG_STORE *store);
+
+/*
+ * Finds a CT log in the store based on its log ID.
+ * Returns the CT log, or NULL if no match is found.
+ */
+const CTLOG *CTLOG_STORE_get0_log_by_id(const CTLOG_STORE *store,
+ const uint8_t *log_id,
+ size_t log_id_len);
+
+/*
+ * Loads a CT log list into a |store| from a |file|.
+ * Returns 1 if loading is successful, or 0 otherwise.
+ */
+__owur int CTLOG_STORE_load_file(CTLOG_STORE *store, const char *file);
+
+/*
+ * Loads the default CT log list into a |store|.
+ * Returns 1 if loading is successful, or 0 otherwise.
+ */
+__owur int CTLOG_STORE_load_default_file(CTLOG_STORE *store);
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/cterr.h b/include/openssl/cterr.h
new file mode 100644
index 00000000..935d32d8
--- /dev/null
+++ b/include/openssl/cterr.h
@@ -0,0 +1,45 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_CTERR_H
+# define OPENSSL_CTERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_CT
+
+
+/*
+ * CT reason codes.
+ */
+# define CT_R_BASE64_DECODE_ERROR 108
+# define CT_R_INVALID_LOG_ID_LENGTH 100
+# define CT_R_LOG_CONF_INVALID 109
+# define CT_R_LOG_CONF_INVALID_KEY 110
+# define CT_R_LOG_CONF_MISSING_DESCRIPTION 111
+# define CT_R_LOG_CONF_MISSING_KEY 112
+# define CT_R_LOG_KEY_INVALID 113
+# define CT_R_SCT_FUTURE_TIMESTAMP 116
+# define CT_R_SCT_INVALID 104
+# define CT_R_SCT_INVALID_SIGNATURE 107
+# define CT_R_SCT_LIST_INVALID 105
+# define CT_R_SCT_LOG_ID_MISMATCH 114
+# define CT_R_SCT_NOT_SET 106
+# define CT_R_SCT_UNSUPPORTED_VERSION 115
+# define CT_R_UNRECOGNIZED_SIGNATURE_NID 101
+# define CT_R_UNSUPPORTED_ENTRY_TYPE 102
+# define CT_R_UNSUPPORTED_VERSION 103
+
+# endif
+#endif
diff --git a/include/openssl/decoder.h b/include/openssl/decoder.h
new file mode 100644
index 00000000..d4ee2cf4
--- /dev/null
+++ b/include/openssl/decoder.h
@@ -0,0 +1,133 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DECODER_H
+# define OPENSSL_DECODER_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+# include <stdarg.h>
+# include <stddef.h>
+# include <openssl/decodererr.h>
+# include <openssl/types.h>
+# include <openssl/core.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+OSSL_DECODER *OSSL_DECODER_fetch(OSSL_LIB_CTX *libctx, const char *name,
+ const char *properties);
+int OSSL_DECODER_up_ref(OSSL_DECODER *encoder);
+void OSSL_DECODER_free(OSSL_DECODER *encoder);
+
+const OSSL_PROVIDER *OSSL_DECODER_get0_provider(const OSSL_DECODER *encoder);
+const char *OSSL_DECODER_get0_properties(const OSSL_DECODER *encoder);
+const char *OSSL_DECODER_get0_name(const OSSL_DECODER *decoder);
+const char *OSSL_DECODER_get0_description(const OSSL_DECODER *decoder);
+int OSSL_DECODER_is_a(const OSSL_DECODER *encoder, const char *name);
+
+void OSSL_DECODER_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(OSSL_DECODER *encoder, void *arg),
+ void *arg);
+int OSSL_DECODER_names_do_all(const OSSL_DECODER *encoder,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PARAM *OSSL_DECODER_gettable_params(OSSL_DECODER *decoder);
+int OSSL_DECODER_get_params(OSSL_DECODER *decoder, OSSL_PARAM params[]);
+
+const OSSL_PARAM *OSSL_DECODER_settable_ctx_params(OSSL_DECODER *encoder);
+OSSL_DECODER_CTX *OSSL_DECODER_CTX_new(void);
+int OSSL_DECODER_CTX_set_params(OSSL_DECODER_CTX *ctx,
+ const OSSL_PARAM params[]);
+void OSSL_DECODER_CTX_free(OSSL_DECODER_CTX *ctx);
+
+/* Utilities that help set specific parameters */
+int OSSL_DECODER_CTX_set_passphrase(OSSL_DECODER_CTX *ctx,
+ const unsigned char *kstr, size_t klen);
+int OSSL_DECODER_CTX_set_pem_password_cb(OSSL_DECODER_CTX *ctx,
+ pem_password_cb *cb, void *cbarg);
+int OSSL_DECODER_CTX_set_passphrase_cb(OSSL_DECODER_CTX *ctx,
+ OSSL_PASSPHRASE_CALLBACK *cb,
+ void *cbarg);
+int OSSL_DECODER_CTX_set_passphrase_ui(OSSL_DECODER_CTX *ctx,
+ const UI_METHOD *ui_method,
+ void *ui_data);
+
+/*
+ * Utilities to read the object to decode, with the result sent to cb.
+ * These will discover all provided methods
+ */
+
+int OSSL_DECODER_CTX_set_selection(OSSL_DECODER_CTX *ctx, int selection);
+int OSSL_DECODER_CTX_set_input_type(OSSL_DECODER_CTX *ctx,
+ const char *input_type);
+int OSSL_DECODER_CTX_set_input_structure(OSSL_DECODER_CTX *ctx,
+ const char *input_structure);
+int OSSL_DECODER_CTX_add_decoder(OSSL_DECODER_CTX *ctx, OSSL_DECODER *decoder);
+int OSSL_DECODER_CTX_add_extra(OSSL_DECODER_CTX *ctx,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int OSSL_DECODER_CTX_get_num_decoders(OSSL_DECODER_CTX *ctx);
+
+typedef struct ossl_decoder_instance_st OSSL_DECODER_INSTANCE;
+OSSL_DECODER *
+OSSL_DECODER_INSTANCE_get_decoder(OSSL_DECODER_INSTANCE *decoder_inst);
+void *
+OSSL_DECODER_INSTANCE_get_decoder_ctx(OSSL_DECODER_INSTANCE *decoder_inst);
+const char *
+OSSL_DECODER_INSTANCE_get_input_type(OSSL_DECODER_INSTANCE *decoder_inst);
+const char *
+OSSL_DECODER_INSTANCE_get_input_structure(OSSL_DECODER_INSTANCE *decoder_inst,
+ int *was_set);
+
+typedef int OSSL_DECODER_CONSTRUCT(OSSL_DECODER_INSTANCE *decoder_inst,
+ const OSSL_PARAM *params,
+ void *construct_data);
+typedef void OSSL_DECODER_CLEANUP(void *construct_data);
+
+int OSSL_DECODER_CTX_set_construct(OSSL_DECODER_CTX *ctx,
+ OSSL_DECODER_CONSTRUCT *construct);
+int OSSL_DECODER_CTX_set_construct_data(OSSL_DECODER_CTX *ctx,
+ void *construct_data);
+int OSSL_DECODER_CTX_set_cleanup(OSSL_DECODER_CTX *ctx,
+ OSSL_DECODER_CLEANUP *cleanup);
+OSSL_DECODER_CONSTRUCT *OSSL_DECODER_CTX_get_construct(OSSL_DECODER_CTX *ctx);
+void *OSSL_DECODER_CTX_get_construct_data(OSSL_DECODER_CTX *ctx);
+OSSL_DECODER_CLEANUP *OSSL_DECODER_CTX_get_cleanup(OSSL_DECODER_CTX *ctx);
+
+int OSSL_DECODER_export(OSSL_DECODER_INSTANCE *decoder_inst,
+ void *reference, size_t reference_sz,
+ OSSL_CALLBACK *export_cb, void *export_cbarg);
+
+int OSSL_DECODER_from_bio(OSSL_DECODER_CTX *ctx, BIO *in);
+#ifndef OPENSSL_NO_STDIO
+int OSSL_DECODER_from_fp(OSSL_DECODER_CTX *ctx, FILE *in);
+#endif
+int OSSL_DECODER_from_data(OSSL_DECODER_CTX *ctx, const unsigned char **pdata,
+ size_t *pdata_len);
+
+/*
+ * Create the OSSL_DECODER_CTX with an associated type. This will perform
+ * an implicit OSSL_DECODER_fetch(), suitable for the object of that type.
+ */
+OSSL_DECODER_CTX *
+OSSL_DECODER_CTX_new_for_pkey(EVP_PKEY **pkey,
+ const char *input_type,
+ const char *input_struct,
+ const char *keytype, int selection,
+ OSSL_LIB_CTX *libctx, const char *propquery);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/decodererr.h b/include/openssl/decodererr.h
new file mode 100644
index 00000000..4212a38b
--- /dev/null
+++ b/include/openssl/decodererr.h
@@ -0,0 +1,28 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DECODERERR_H
+# define OPENSSL_DECODERERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * OSSL_DECODER reason codes.
+ */
+# define OSSL_DECODER_R_COULD_NOT_DECODE_OBJECT 101
+# define OSSL_DECODER_R_DECODER_NOT_FOUND 102
+# define OSSL_DECODER_R_MISSING_GET_PARAMS 100
+
+#endif
diff --git a/include/openssl/des.h b/include/openssl/des.h
new file mode 100644
index 00000000..09798a61
--- /dev/null
+++ b/include/openssl/des.h
@@ -0,0 +1,211 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DES_H
+# define OPENSSL_DES_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_DES_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_DES
+# ifdef __cplusplus
+extern "C" {
+# endif
+# include <openssl/e_os2.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef unsigned int DES_LONG;
+
+# ifdef OPENSSL_BUILD_SHLIBCRYPTO
+# undef OPENSSL_EXTERN
+# define OPENSSL_EXTERN OPENSSL_EXPORT
+# endif
+
+typedef unsigned char DES_cblock[8];
+typedef /* const */ unsigned char const_DES_cblock[8];
+/*
+ * With "const", gcc 2.8.1 on Solaris thinks that DES_cblock * and
+ * const_DES_cblock * are incompatible pointer types.
+ */
+
+typedef struct DES_ks {
+ union {
+ DES_cblock cblock;
+ /*
+ * make sure things are correct size on machines with 8 byte longs
+ */
+ DES_LONG deslong[2];
+ } ks[16];
+} DES_key_schedule;
+
+# define DES_KEY_SZ (sizeof(DES_cblock))
+# define DES_SCHEDULE_SZ (sizeof(DES_key_schedule))
+
+# define DES_ENCRYPT 1
+# define DES_DECRYPT 0
+
+# define DES_CBC_MODE 0
+# define DES_PCBC_MODE 1
+
+# define DES_ecb2_encrypt(i,o,k1,k2,e) \
+ DES_ecb3_encrypt((i),(o),(k1),(k2),(k1),(e))
+
+# define DES_ede2_cbc_encrypt(i,o,l,k1,k2,iv,e) \
+ DES_ede3_cbc_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(e))
+
+# define DES_ede2_cfb64_encrypt(i,o,l,k1,k2,iv,n,e) \
+ DES_ede3_cfb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n),(e))
+
+# define DES_ede2_ofb64_encrypt(i,o,l,k1,k2,iv,n) \
+ DES_ede3_ofb64_encrypt((i),(o),(l),(k1),(k2),(k1),(iv),(n))
+
+# define DES_fixup_key_parity DES_set_odd_parity
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *DES_options(void);
+OSSL_DEPRECATEDIN_3_0
+void DES_ecb3_encrypt(const_DES_cblock *input, DES_cblock *output,
+ DES_key_schedule *ks1, DES_key_schedule *ks2,
+ DES_key_schedule *ks3, int enc);
+OSSL_DEPRECATEDIN_3_0
+DES_LONG DES_cbc_cksum(const unsigned char *input, DES_cblock *output,
+ long length, DES_key_schedule *schedule,
+ const_DES_cblock *ivec);
+# endif
+/* DES_cbc_encrypt does not update the IV! Use DES_ncbc_encrypt instead. */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+void DES_cbc_encrypt(const unsigned char *input, unsigned char *output,
+ long length, DES_key_schedule *schedule, DES_cblock *ivec,
+ int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_ncbc_encrypt(const unsigned char *input, unsigned char *output,
+ long length, DES_key_schedule *schedule, DES_cblock *ivec,
+ int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_xcbc_encrypt(const unsigned char *input, unsigned char *output,
+ long length, DES_key_schedule *schedule, DES_cblock *ivec,
+ const_DES_cblock *inw, const_DES_cblock *outw, int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_cfb_encrypt(const unsigned char *in, unsigned char *out, int numbits,
+ long length, DES_key_schedule *schedule, DES_cblock *ivec,
+ int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_ecb_encrypt(const_DES_cblock *input, DES_cblock *output,
+ DES_key_schedule *ks, int enc);
+# endif
+
+/*
+ * This is the DES encryption function that gets called by just about every
+ * other DES routine in the library. You should not use this function except
+ * to implement 'modes' of DES. I say this because the functions that call
+ * this routine do the conversion from 'char *' to long, and this needs to be
+ * done to make sure 'non-aligned' memory access do not occur. The
+ * characters are loaded 'little endian'. Data is a pointer to 2 unsigned
+ * long's and ks is the DES_key_schedule to use. enc, is non zero specifies
+ * encryption, zero if decryption.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+void DES_encrypt1(DES_LONG *data, DES_key_schedule *ks, int enc);
+# endif
+
+/*
+ * This functions is the same as DES_encrypt1() except that the DES initial
+ * permutation (IP) and final permutation (FP) have been left out. As for
+ * DES_encrypt1(), you should not use this function. It is used by the
+ * routines in the library that implement triple DES. IP() DES_encrypt2()
+ * DES_encrypt2() DES_encrypt2() FP() is the same as DES_encrypt1()
+ * DES_encrypt1() DES_encrypt1() except faster :-).
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+void DES_encrypt2(DES_LONG *data, DES_key_schedule *ks, int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_encrypt3(DES_LONG *data, DES_key_schedule *ks1, DES_key_schedule *ks2,
+ DES_key_schedule *ks3);
+OSSL_DEPRECATEDIN_3_0
+void DES_decrypt3(DES_LONG *data, DES_key_schedule *ks1, DES_key_schedule *ks2,
+ DES_key_schedule *ks3);
+OSSL_DEPRECATEDIN_3_0
+void DES_ede3_cbc_encrypt(const unsigned char *input, unsigned char *output,
+ long length, DES_key_schedule *ks1,
+ DES_key_schedule *ks2, DES_key_schedule *ks3,
+ DES_cblock *ivec, int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_ede3_cfb64_encrypt(const unsigned char *in, unsigned char *out,
+ long length, DES_key_schedule *ks1,
+ DES_key_schedule *ks2, DES_key_schedule *ks3,
+ DES_cblock *ivec, int *num, int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_ede3_cfb_encrypt(const unsigned char *in, unsigned char *out,
+ int numbits, long length, DES_key_schedule *ks1,
+ DES_key_schedule *ks2, DES_key_schedule *ks3,
+ DES_cblock *ivec, int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_ede3_ofb64_encrypt(const unsigned char *in, unsigned char *out,
+ long length, DES_key_schedule *ks1,
+ DES_key_schedule *ks2, DES_key_schedule *ks3,
+ DES_cblock *ivec, int *num);
+OSSL_DEPRECATEDIN_3_0
+char *DES_fcrypt(const char *buf, const char *salt, char *ret);
+OSSL_DEPRECATEDIN_3_0
+char *DES_crypt(const char *buf, const char *salt);
+OSSL_DEPRECATEDIN_3_0
+void DES_ofb_encrypt(const unsigned char *in, unsigned char *out, int numbits,
+ long length, DES_key_schedule *schedule, DES_cblock *ivec);
+OSSL_DEPRECATEDIN_3_0
+void DES_pcbc_encrypt(const unsigned char *input, unsigned char *output,
+ long length, DES_key_schedule *schedule,
+ DES_cblock *ivec, int enc);
+OSSL_DEPRECATEDIN_3_0
+DES_LONG DES_quad_cksum(const unsigned char *input, DES_cblock output[],
+ long length, int out_count, DES_cblock *seed);
+OSSL_DEPRECATEDIN_3_0 int DES_random_key(DES_cblock *ret);
+OSSL_DEPRECATEDIN_3_0 void DES_set_odd_parity(DES_cblock *key);
+OSSL_DEPRECATEDIN_3_0 int DES_check_key_parity(const_DES_cblock *key);
+OSSL_DEPRECATEDIN_3_0 int DES_is_weak_key(const_DES_cblock *key);
+# endif
+/*
+ * DES_set_key (= set_key = DES_key_sched = key_sched) calls
+ * DES_set_key_checked
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int DES_set_key(const_DES_cblock *key, DES_key_schedule *schedule);
+OSSL_DEPRECATEDIN_3_0
+int DES_key_sched(const_DES_cblock *key, DES_key_schedule *schedule);
+OSSL_DEPRECATEDIN_3_0
+int DES_set_key_checked(const_DES_cblock *key, DES_key_schedule *schedule);
+OSSL_DEPRECATEDIN_3_0
+void DES_set_key_unchecked(const_DES_cblock *key, DES_key_schedule *schedule);
+OSSL_DEPRECATEDIN_3_0 void DES_string_to_key(const char *str, DES_cblock *key);
+OSSL_DEPRECATEDIN_3_0
+void DES_string_to_2keys(const char *str, DES_cblock *key1, DES_cblock *key2);
+OSSL_DEPRECATEDIN_3_0
+void DES_cfb64_encrypt(const unsigned char *in, unsigned char *out,
+ long length, DES_key_schedule *schedule,
+ DES_cblock *ivec, int *num, int enc);
+OSSL_DEPRECATEDIN_3_0
+void DES_ofb64_encrypt(const unsigned char *in, unsigned char *out,
+ long length, DES_key_schedule *schedule,
+ DES_cblock *ivec, int *num);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/dh.h b/include/openssl/dh.h
new file mode 100644
index 00000000..b97871ec
--- /dev/null
+++ b/include/openssl/dh.h
@@ -0,0 +1,328 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DH_H
+# define OPENSSL_DH_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_DH_H
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+#include <stdlib.h>
+
+/* DH parameter generation types used by EVP_PKEY_CTX_set_dh_paramgen_type() */
+# define DH_PARAMGEN_TYPE_GENERATOR 0 /* Use a safe prime generator */
+# define DH_PARAMGEN_TYPE_FIPS_186_2 1 /* Use FIPS186-2 standard */
+# define DH_PARAMGEN_TYPE_FIPS_186_4 2 /* Use FIPS186-4 standard */
+# define DH_PARAMGEN_TYPE_GROUP 3 /* Use a named safe prime group */
+
+int EVP_PKEY_CTX_set_dh_paramgen_type(EVP_PKEY_CTX *ctx, int typ);
+int EVP_PKEY_CTX_set_dh_paramgen_gindex(EVP_PKEY_CTX *ctx, int gindex);
+int EVP_PKEY_CTX_set_dh_paramgen_seed(EVP_PKEY_CTX *ctx,
+ const unsigned char *seed,
+ size_t seedlen);
+int EVP_PKEY_CTX_set_dh_paramgen_prime_len(EVP_PKEY_CTX *ctx, int pbits);
+int EVP_PKEY_CTX_set_dh_paramgen_subprime_len(EVP_PKEY_CTX *ctx, int qlen);
+int EVP_PKEY_CTX_set_dh_paramgen_generator(EVP_PKEY_CTX *ctx, int gen);
+int EVP_PKEY_CTX_set_dh_nid(EVP_PKEY_CTX *ctx, int nid);
+int EVP_PKEY_CTX_set_dh_rfc5114(EVP_PKEY_CTX *ctx, int gen);
+int EVP_PKEY_CTX_set_dhx_rfc5114(EVP_PKEY_CTX *ctx, int gen);
+int EVP_PKEY_CTX_set_dh_pad(EVP_PKEY_CTX *ctx, int pad);
+
+int EVP_PKEY_CTX_set_dh_kdf_type(EVP_PKEY_CTX *ctx, int kdf);
+int EVP_PKEY_CTX_get_dh_kdf_type(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_CTX_set0_dh_kdf_oid(EVP_PKEY_CTX *ctx, ASN1_OBJECT *oid);
+int EVP_PKEY_CTX_get0_dh_kdf_oid(EVP_PKEY_CTX *ctx, ASN1_OBJECT **oid);
+int EVP_PKEY_CTX_set_dh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+int EVP_PKEY_CTX_get_dh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD **md);
+int EVP_PKEY_CTX_set_dh_kdf_outlen(EVP_PKEY_CTX *ctx, int len);
+int EVP_PKEY_CTX_get_dh_kdf_outlen(EVP_PKEY_CTX *ctx, int *len);
+int EVP_PKEY_CTX_set0_dh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char *ukm, int len);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_CTX_get0_dh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char **ukm);
+#endif
+
+# define EVP_PKEY_CTRL_DH_PARAMGEN_PRIME_LEN (EVP_PKEY_ALG_CTRL + 1)
+# define EVP_PKEY_CTRL_DH_PARAMGEN_GENERATOR (EVP_PKEY_ALG_CTRL + 2)
+# define EVP_PKEY_CTRL_DH_RFC5114 (EVP_PKEY_ALG_CTRL + 3)
+# define EVP_PKEY_CTRL_DH_PARAMGEN_SUBPRIME_LEN (EVP_PKEY_ALG_CTRL + 4)
+# define EVP_PKEY_CTRL_DH_PARAMGEN_TYPE (EVP_PKEY_ALG_CTRL + 5)
+# define EVP_PKEY_CTRL_DH_KDF_TYPE (EVP_PKEY_ALG_CTRL + 6)
+# define EVP_PKEY_CTRL_DH_KDF_MD (EVP_PKEY_ALG_CTRL + 7)
+# define EVP_PKEY_CTRL_GET_DH_KDF_MD (EVP_PKEY_ALG_CTRL + 8)
+# define EVP_PKEY_CTRL_DH_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 9)
+# define EVP_PKEY_CTRL_GET_DH_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 10)
+# define EVP_PKEY_CTRL_DH_KDF_UKM (EVP_PKEY_ALG_CTRL + 11)
+# define EVP_PKEY_CTRL_GET_DH_KDF_UKM (EVP_PKEY_ALG_CTRL + 12)
+# define EVP_PKEY_CTRL_DH_KDF_OID (EVP_PKEY_ALG_CTRL + 13)
+# define EVP_PKEY_CTRL_GET_DH_KDF_OID (EVP_PKEY_ALG_CTRL + 14)
+# define EVP_PKEY_CTRL_DH_NID (EVP_PKEY_ALG_CTRL + 15)
+# define EVP_PKEY_CTRL_DH_PAD (EVP_PKEY_ALG_CTRL + 16)
+
+/* KDF types */
+# define EVP_PKEY_DH_KDF_NONE 1
+# define EVP_PKEY_DH_KDF_X9_42 2
+
+# ifndef OPENSSL_NO_DH
+# include <openssl/e_os2.h>
+# include <openssl/bio.h>
+# include <openssl/asn1.h>
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/bn.h>
+# endif
+# include <openssl/dherr.h>
+
+# ifndef OPENSSL_DH_MAX_MODULUS_BITS
+# define OPENSSL_DH_MAX_MODULUS_BITS 10000
+# endif
+
+# define OPENSSL_DH_FIPS_MIN_MODULUS_BITS 1024
+
+# define DH_FLAG_CACHE_MONT_P 0x01
+
+# define DH_FLAG_TYPE_MASK 0xF000
+# define DH_FLAG_TYPE_DH 0x0000
+# define DH_FLAG_TYPE_DHX 0x1000
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/*
+ * Does nothing. Previously this switched off constant time behaviour.
+ */
+# define DH_FLAG_NO_EXP_CONSTTIME 0x00
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/*
+ * If this flag is set the DH method is FIPS compliant and can be used in
+ * FIPS mode. This is set in the validated module method. If an application
+ * sets this flag in its own methods it is its responsibility to ensure the
+ * result is compliant.
+ */
+
+# define DH_FLAG_FIPS_METHOD 0x0400
+
+/*
+ * If this flag is set the operations normally disabled in FIPS mode are
+ * permitted it is then the applications responsibility to ensure that the
+ * usage is compliant.
+ */
+
+# define DH_FLAG_NON_FIPS_ALLOW 0x0400
+# endif
+
+/* Already defined in ossl_typ.h */
+/* typedef struct dh_st DH; */
+/* typedef struct dh_method DH_METHOD; */
+
+DECLARE_ASN1_ITEM(DHparams)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DH_GENERATOR_2 2
+# define DH_GENERATOR_3 3
+# define DH_GENERATOR_5 5
+
+/* DH_check error codes */
+/*
+ * NB: These values must align with the equivalently named macros in
+ * internal/ffc.h.
+ */
+# define DH_CHECK_P_NOT_PRIME 0x01
+# define DH_CHECK_P_NOT_SAFE_PRIME 0x02
+# define DH_UNABLE_TO_CHECK_GENERATOR 0x04
+# define DH_NOT_SUITABLE_GENERATOR 0x08
+# define DH_CHECK_Q_NOT_PRIME 0x10
+# define DH_CHECK_INVALID_Q_VALUE 0x20
+# define DH_CHECK_INVALID_J_VALUE 0x40
+# define DH_MODULUS_TOO_SMALL 0x80
+# define DH_MODULUS_TOO_LARGE 0x100
+
+/* DH_check_pub_key error codes */
+# define DH_CHECK_PUBKEY_TOO_SMALL 0x01
+# define DH_CHECK_PUBKEY_TOO_LARGE 0x02
+# define DH_CHECK_PUBKEY_INVALID 0x04
+
+/*
+ * primes p where (p-1)/2 is prime too are called "safe"; we define this for
+ * backward compatibility:
+ */
+# define DH_CHECK_P_NOT_STRONG_PRIME DH_CHECK_P_NOT_SAFE_PRIME
+
+# define d2i_DHparams_fp(fp, x) \
+ (DH *)ASN1_d2i_fp((char *(*)())DH_new, \
+ (char *(*)())d2i_DHparams, \
+ (fp), \
+ (unsigned char **)(x))
+# define i2d_DHparams_fp(fp, x) \
+ ASN1_i2d_fp(i2d_DHparams,(fp), (unsigned char *)(x))
+# define d2i_DHparams_bio(bp, x) \
+ ASN1_d2i_bio_of(DH, DH_new, d2i_DHparams, bp, x)
+# define i2d_DHparams_bio(bp, x) \
+ ASN1_i2d_bio_of(DH, i2d_DHparams, bp, x)
+
+# define d2i_DHxparams_fp(fp,x) \
+ (DH *)ASN1_d2i_fp((char *(*)())DH_new, \
+ (char *(*)())d2i_DHxparams, \
+ (fp), \
+ (unsigned char **)(x))
+# define i2d_DHxparams_fp(fp, x) \
+ ASN1_i2d_fp(i2d_DHxparams,(fp), (unsigned char *)(x))
+# define d2i_DHxparams_bio(bp, x) \
+ ASN1_d2i_bio_of(DH, DH_new, d2i_DHxparams, bp, x)
+# define i2d_DHxparams_bio(bp, x) \
+ ASN1_i2d_bio_of(DH, i2d_DHxparams, bp, x)
+
+DECLARE_ASN1_DUP_FUNCTION_name_attr(OSSL_DEPRECATEDIN_3_0, DH, DHparams)
+
+OSSL_DEPRECATEDIN_3_0 const DH_METHOD *DH_OpenSSL(void);
+
+OSSL_DEPRECATEDIN_3_0 void DH_set_default_method(const DH_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 const DH_METHOD *DH_get_default_method(void);
+OSSL_DEPRECATEDIN_3_0 int DH_set_method(DH *dh, const DH_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 DH *DH_new_method(ENGINE *engine);
+
+OSSL_DEPRECATEDIN_3_0 DH *DH_new(void);
+OSSL_DEPRECATEDIN_3_0 void DH_free(DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_up_ref(DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_bits(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_size(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_security_bits(const DH *dh);
+
+# define DH_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_DH, l, p, newf, dupf, freef)
+
+OSSL_DEPRECATEDIN_3_0 int DH_set_ex_data(DH *d, int idx, void *arg);
+OSSL_DEPRECATEDIN_3_0 void *DH_get_ex_data(const DH *d, int idx);
+
+OSSL_DEPRECATEDIN_3_0 int DH_generate_parameters_ex(DH *dh, int prime_len,
+ int generator,
+ BN_GENCB *cb);
+
+OSSL_DEPRECATEDIN_3_0 int DH_check_params_ex(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_check_ex(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_check_pub_key_ex(const DH *dh, const BIGNUM *pub_key);
+OSSL_DEPRECATEDIN_3_0 int DH_check_params(const DH *dh, int *ret);
+OSSL_DEPRECATEDIN_3_0 int DH_check(const DH *dh, int *codes);
+OSSL_DEPRECATEDIN_3_0 int DH_check_pub_key(const DH *dh, const BIGNUM *pub_key,
+ int *codes);
+OSSL_DEPRECATEDIN_3_0 int DH_generate_key(DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_compute_key(unsigned char *key,
+ const BIGNUM *pub_key, DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_compute_key_padded(unsigned char *key,
+ const BIGNUM *pub_key, DH *dh);
+
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, DH, DHparams)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, DH, DHxparams)
+
+# ifndef OPENSSL_NO_STDIO
+OSSL_DEPRECATEDIN_3_0 int DHparams_print_fp(FILE *fp, const DH *x);
+# endif
+OSSL_DEPRECATEDIN_3_0 int DHparams_print(BIO *bp, const DH *x);
+
+/* RFC 5114 parameters */
+OSSL_DEPRECATEDIN_3_0 DH *DH_get_1024_160(void);
+OSSL_DEPRECATEDIN_3_0 DH *DH_get_2048_224(void);
+OSSL_DEPRECATEDIN_3_0 DH *DH_get_2048_256(void);
+
+/* Named parameters, currently RFC7919 and RFC3526 */
+OSSL_DEPRECATEDIN_3_0 DH *DH_new_by_nid(int nid);
+OSSL_DEPRECATEDIN_3_0 int DH_get_nid(const DH *dh);
+
+/* RFC2631 KDF */
+OSSL_DEPRECATEDIN_3_0 int DH_KDF_X9_42(unsigned char *out, size_t outlen,
+ const unsigned char *Z, size_t Zlen,
+ ASN1_OBJECT *key_oid,
+ const unsigned char *ukm,
+ size_t ukmlen, const EVP_MD *md);
+
+OSSL_DEPRECATEDIN_3_0 void DH_get0_pqg(const DH *dh, const BIGNUM **p,
+ const BIGNUM **q, const BIGNUM **g);
+OSSL_DEPRECATEDIN_3_0 int DH_set0_pqg(DH *dh, BIGNUM *p, BIGNUM *q, BIGNUM *g);
+OSSL_DEPRECATEDIN_3_0 void DH_get0_key(const DH *dh, const BIGNUM **pub_key,
+ const BIGNUM **priv_key);
+OSSL_DEPRECATEDIN_3_0 int DH_set0_key(DH *dh, BIGNUM *pub_key, BIGNUM *priv_key);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DH_get0_p(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DH_get0_q(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DH_get0_g(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DH_get0_priv_key(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DH_get0_pub_key(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 void DH_clear_flags(DH *dh, int flags);
+OSSL_DEPRECATEDIN_3_0 int DH_test_flags(const DH *dh, int flags);
+OSSL_DEPRECATEDIN_3_0 void DH_set_flags(DH *dh, int flags);
+OSSL_DEPRECATEDIN_3_0 ENGINE *DH_get0_engine(DH *d);
+OSSL_DEPRECATEDIN_3_0 long DH_get_length(const DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_set_length(DH *dh, long length);
+
+OSSL_DEPRECATEDIN_3_0 DH_METHOD *DH_meth_new(const char *name, int flags);
+OSSL_DEPRECATEDIN_3_0 void DH_meth_free(DH_METHOD *dhm);
+OSSL_DEPRECATEDIN_3_0 DH_METHOD *DH_meth_dup(const DH_METHOD *dhm);
+OSSL_DEPRECATEDIN_3_0 const char *DH_meth_get0_name(const DH_METHOD *dhm);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set1_name(DH_METHOD *dhm, const char *name);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_get_flags(const DH_METHOD *dhm);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set_flags(DH_METHOD *dhm, int flags);
+OSSL_DEPRECATEDIN_3_0 void *DH_meth_get0_app_data(const DH_METHOD *dhm);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set0_app_data(DH_METHOD *dhm, void *app_data);
+OSSL_DEPRECATEDIN_3_0 int (*DH_meth_get_generate_key(const DH_METHOD *dhm)) (DH *);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set_generate_key(DH_METHOD *dhm,
+ int (*generate_key) (DH *));
+OSSL_DEPRECATEDIN_3_0 int (*DH_meth_get_compute_key(const DH_METHOD *dhm))
+ (unsigned char *key,
+ const BIGNUM *pub_key,
+ DH *dh);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set_compute_key(DH_METHOD *dhm,
+ int (*compute_key)
+ (unsigned char *key,
+ const BIGNUM *pub_key,
+ DH *dh));
+OSSL_DEPRECATEDIN_3_0 int (*DH_meth_get_bn_mod_exp(const DH_METHOD *dhm))
+ (const DH *, BIGNUM *,
+ const BIGNUM *,
+ const BIGNUM *,
+ const BIGNUM *, BN_CTX *,
+ BN_MONT_CTX *);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set_bn_mod_exp(DH_METHOD *dhm,
+ int (*bn_mod_exp)
+ (const DH *, BIGNUM *,
+ const BIGNUM *, const BIGNUM *,
+ const BIGNUM *, BN_CTX *,
+ BN_MONT_CTX *));
+OSSL_DEPRECATEDIN_3_0 int (*DH_meth_get_init(const DH_METHOD *dhm))(DH *);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set_init(DH_METHOD *dhm, int (*init)(DH *));
+OSSL_DEPRECATEDIN_3_0 int (*DH_meth_get_finish(const DH_METHOD *dhm)) (DH *);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set_finish(DH_METHOD *dhm, int (*finish) (DH *));
+OSSL_DEPRECATEDIN_3_0 int (*DH_meth_get_generate_params(const DH_METHOD *dhm))
+ (DH *, int, int,
+ BN_GENCB *);
+OSSL_DEPRECATEDIN_3_0 int DH_meth_set_generate_params(DH_METHOD *dhm,
+ int (*generate_params)
+ (DH *, int, int,
+ BN_GENCB *));
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+# ifndef OPENSSL_NO_DEPRECATED_0_9_8
+OSSL_DEPRECATEDIN_0_9_8 DH *DH_generate_parameters(int prime_len, int generator,
+ void (*callback) (int, int,
+ void *),
+ void *cb_arg);
+# endif
+
+# endif
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/dherr.h b/include/openssl/dherr.h
new file mode 100644
index 00000000..5d2a762a
--- /dev/null
+++ b/include/openssl/dherr.h
@@ -0,0 +1,57 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DHERR_H
+# define OPENSSL_DHERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_DH
+
+
+/*
+ * DH reason codes.
+ */
+# define DH_R_BAD_FFC_PARAMETERS 127
+# define DH_R_BAD_GENERATOR 101
+# define DH_R_BN_DECODE_ERROR 109
+# define DH_R_BN_ERROR 106
+# define DH_R_CHECK_INVALID_J_VALUE 115
+# define DH_R_CHECK_INVALID_Q_VALUE 116
+# define DH_R_CHECK_PUBKEY_INVALID 122
+# define DH_R_CHECK_PUBKEY_TOO_LARGE 123
+# define DH_R_CHECK_PUBKEY_TOO_SMALL 124
+# define DH_R_CHECK_P_NOT_PRIME 117
+# define DH_R_CHECK_P_NOT_SAFE_PRIME 118
+# define DH_R_CHECK_Q_NOT_PRIME 119
+# define DH_R_DECODE_ERROR 104
+# define DH_R_INVALID_PARAMETER_NAME 110
+# define DH_R_INVALID_PARAMETER_NID 114
+# define DH_R_INVALID_PUBKEY 102
+# define DH_R_INVALID_SECRET 128
+# define DH_R_KDF_PARAMETER_ERROR 112
+# define DH_R_KEYS_NOT_SET 108
+# define DH_R_MISSING_PUBKEY 125
+# define DH_R_MODULUS_TOO_LARGE 103
+# define DH_R_MODULUS_TOO_SMALL 126
+# define DH_R_NOT_SUITABLE_GENERATOR 120
+# define DH_R_NO_PARAMETERS_SET 107
+# define DH_R_NO_PRIVATE_VALUE 100
+# define DH_R_PARAMETER_ENCODING_ERROR 105
+# define DH_R_PEER_KEY_ERROR 111
+# define DH_R_SHARED_INFO_ERROR 113
+# define DH_R_UNABLE_TO_CHECK_GENERATOR 121
+
+# endif
+#endif
diff --git a/include/openssl/dsa.h b/include/openssl/dsa.h
new file mode 100644
index 00000000..5c0e4cdd
--- /dev/null
+++ b/include/openssl/dsa.h
@@ -0,0 +1,275 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DSA_H
+# define OPENSSL_DSA_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_DSA_H
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# include <stdlib.h>
+
+int EVP_PKEY_CTX_set_dsa_paramgen_bits(EVP_PKEY_CTX *ctx, int nbits);
+int EVP_PKEY_CTX_set_dsa_paramgen_q_bits(EVP_PKEY_CTX *ctx, int qbits);
+int EVP_PKEY_CTX_set_dsa_paramgen_md_props(EVP_PKEY_CTX *ctx,
+ const char *md_name,
+ const char *md_properties);
+int EVP_PKEY_CTX_set_dsa_paramgen_gindex(EVP_PKEY_CTX *ctx, int gindex);
+int EVP_PKEY_CTX_set_dsa_paramgen_type(EVP_PKEY_CTX *ctx, const char *name);
+int EVP_PKEY_CTX_set_dsa_paramgen_seed(EVP_PKEY_CTX *ctx,
+ const unsigned char *seed,
+ size_t seedlen);
+int EVP_PKEY_CTX_set_dsa_paramgen_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+
+# define EVP_PKEY_CTRL_DSA_PARAMGEN_BITS (EVP_PKEY_ALG_CTRL + 1)
+# define EVP_PKEY_CTRL_DSA_PARAMGEN_Q_BITS (EVP_PKEY_ALG_CTRL + 2)
+# define EVP_PKEY_CTRL_DSA_PARAMGEN_MD (EVP_PKEY_ALG_CTRL + 3)
+
+# ifndef OPENSSL_NO_DSA
+# include <openssl/e_os2.h>
+# include <openssl/asn1.h>
+# include <openssl/bio.h>
+# include <openssl/crypto.h>
+# include <openssl/bn.h>
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/dh.h>
+# endif
+# include <openssl/dsaerr.h>
+
+# ifndef OPENSSL_DSA_MAX_MODULUS_BITS
+# define OPENSSL_DSA_MAX_MODULUS_BITS 10000
+# endif
+
+# define OPENSSL_DSA_FIPS_MIN_MODULUS_BITS 1024
+
+typedef struct DSA_SIG_st DSA_SIG;
+DSA_SIG *DSA_SIG_new(void);
+void DSA_SIG_free(DSA_SIG *a);
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(DSA_SIG, DSA_SIG)
+void DSA_SIG_get0(const DSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps);
+int DSA_SIG_set0(DSA_SIG *sig, BIGNUM *r, BIGNUM *s);
+
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/*
+ * Does nothing. Previously this switched off constant time behaviour.
+ */
+# define DSA_FLAG_NO_EXP_CONSTTIME 0x00
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DSA_FLAG_CACHE_MONT_P 0x01
+
+/*
+ * If this flag is set the DSA method is FIPS compliant and can be used in
+ * FIPS mode. This is set in the validated module method. If an application
+ * sets this flag in its own methods it is its responsibility to ensure the
+ * result is compliant.
+ */
+
+# define DSA_FLAG_FIPS_METHOD 0x0400
+
+/*
+ * If this flag is set the operations normally disabled in FIPS mode are
+ * permitted it is then the applications responsibility to ensure that the
+ * usage is compliant.
+ */
+
+# define DSA_FLAG_NON_FIPS_ALLOW 0x0400
+# define DSA_FLAG_FIPS_CHECKED 0x0800
+
+/* Already defined in ossl_typ.h */
+/* typedef struct dsa_st DSA; */
+/* typedef struct dsa_method DSA_METHOD; */
+
+# define d2i_DSAparams_fp(fp, x) \
+ (DSA *)ASN1_d2i_fp((char *(*)())DSA_new, \
+ (char *(*)())d2i_DSAparams, (fp), \
+ (unsigned char **)(x))
+# define i2d_DSAparams_fp(fp, x) \
+ ASN1_i2d_fp(i2d_DSAparams, (fp), (unsigned char *)(x))
+# define d2i_DSAparams_bio(bp, x) \
+ ASN1_d2i_bio_of(DSA, DSA_new, d2i_DSAparams, bp, x)
+# define i2d_DSAparams_bio(bp, x) \
+ ASN1_i2d_bio_of(DSA, i2d_DSAparams, bp, x)
+
+DECLARE_ASN1_DUP_FUNCTION_name_attr(OSSL_DEPRECATEDIN_3_0, DSA, DSAparams)
+OSSL_DEPRECATEDIN_3_0 DSA_SIG *DSA_do_sign(const unsigned char *dgst, int dlen,
+ DSA *dsa);
+OSSL_DEPRECATEDIN_3_0 int DSA_do_verify(const unsigned char *dgst, int dgst_len,
+ DSA_SIG *sig, DSA *dsa);
+
+OSSL_DEPRECATEDIN_3_0 const DSA_METHOD *DSA_OpenSSL(void);
+
+OSSL_DEPRECATEDIN_3_0 void DSA_set_default_method(const DSA_METHOD *);
+OSSL_DEPRECATEDIN_3_0 const DSA_METHOD *DSA_get_default_method(void);
+OSSL_DEPRECATEDIN_3_0 int DSA_set_method(DSA *dsa, const DSA_METHOD *);
+OSSL_DEPRECATEDIN_3_0 const DSA_METHOD *DSA_get_method(DSA *d);
+
+OSSL_DEPRECATEDIN_3_0 DSA *DSA_new(void);
+OSSL_DEPRECATEDIN_3_0 DSA *DSA_new_method(ENGINE *engine);
+OSSL_DEPRECATEDIN_3_0 void DSA_free(DSA *r);
+/* "up" the DSA object's reference count */
+OSSL_DEPRECATEDIN_3_0 int DSA_up_ref(DSA *r);
+OSSL_DEPRECATEDIN_3_0 int DSA_size(const DSA *);
+OSSL_DEPRECATEDIN_3_0 int DSA_bits(const DSA *d);
+OSSL_DEPRECATEDIN_3_0 int DSA_security_bits(const DSA *d);
+ /* next 4 return -1 on error */
+OSSL_DEPRECATEDIN_3_0 int DSA_sign_setup(DSA *dsa, BN_CTX *ctx_in,
+ BIGNUM **kinvp, BIGNUM **rp);
+OSSL_DEPRECATEDIN_3_0 int DSA_sign(int type, const unsigned char *dgst,
+ int dlen, unsigned char *sig,
+ unsigned int *siglen, DSA *dsa);
+OSSL_DEPRECATEDIN_3_0 int DSA_verify(int type, const unsigned char *dgst,
+ int dgst_len, const unsigned char *sigbuf,
+ int siglen, DSA *dsa);
+
+# define DSA_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_DSA, l, p, newf, dupf, freef)
+OSSL_DEPRECATEDIN_3_0 int DSA_set_ex_data(DSA *d, int idx, void *arg);
+OSSL_DEPRECATEDIN_3_0 void *DSA_get_ex_data(const DSA *d, int idx);
+
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,
+ DSA, DSAPublicKey)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,
+ DSA, DSAPrivateKey)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,
+ DSA, DSAparams)
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_0_9_8
+/* Deprecated version */
+OSSL_DEPRECATEDIN_0_9_8
+DSA *DSA_generate_parameters(int bits, unsigned char *seed, int seed_len,
+ int *counter_ret, unsigned long *h_ret,
+ void (*callback) (int, int, void *),
+ void *cb_arg);
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* New version */
+OSSL_DEPRECATEDIN_3_0 int DSA_generate_parameters_ex(DSA *dsa, int bits,
+ const unsigned char *seed,
+ int seed_len,
+ int *counter_ret,
+ unsigned long *h_ret,
+ BN_GENCB *cb);
+
+OSSL_DEPRECATEDIN_3_0 int DSA_generate_key(DSA *a);
+
+OSSL_DEPRECATEDIN_3_0 int DSAparams_print(BIO *bp, const DSA *x);
+OSSL_DEPRECATEDIN_3_0 int DSA_print(BIO *bp, const DSA *x, int off);
+# ifndef OPENSSL_NO_STDIO
+OSSL_DEPRECATEDIN_3_0 int DSAparams_print_fp(FILE *fp, const DSA *x);
+OSSL_DEPRECATEDIN_3_0 int DSA_print_fp(FILE *bp, const DSA *x, int off);
+# endif
+
+# define DSS_prime_checks 64
+/*
+ * Primality test according to FIPS PUB 186-4, Appendix C.3. Since we only
+ * have one value here we set the number of checks to 64 which is the 128 bit
+ * security level that is the highest level and valid for creating a 3072 bit
+ * DSA key.
+ */
+# define DSA_is_prime(n, callback, cb_arg) \
+ BN_is_prime(n, DSS_prime_checks, callback, NULL, cb_arg)
+
+# ifndef OPENSSL_NO_DH
+/*
+ * Convert DSA structure (key or just parameters) into DH structure (be
+ * careful to avoid small subgroup attacks when using this!)
+ */
+OSSL_DEPRECATEDIN_3_0 DH *DSA_dup_DH(const DSA *r);
+# endif
+
+OSSL_DEPRECATEDIN_3_0 void DSA_get0_pqg(const DSA *d, const BIGNUM **p,
+ const BIGNUM **q, const BIGNUM **g);
+OSSL_DEPRECATEDIN_3_0 int DSA_set0_pqg(DSA *d, BIGNUM *p, BIGNUM *q, BIGNUM *g);
+OSSL_DEPRECATEDIN_3_0 void DSA_get0_key(const DSA *d, const BIGNUM **pub_key,
+ const BIGNUM **priv_key);
+OSSL_DEPRECATEDIN_3_0 int DSA_set0_key(DSA *d, BIGNUM *pub_key,
+ BIGNUM *priv_key);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DSA_get0_p(const DSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DSA_get0_q(const DSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DSA_get0_g(const DSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DSA_get0_pub_key(const DSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *DSA_get0_priv_key(const DSA *d);
+OSSL_DEPRECATEDIN_3_0 void DSA_clear_flags(DSA *d, int flags);
+OSSL_DEPRECATEDIN_3_0 int DSA_test_flags(const DSA *d, int flags);
+OSSL_DEPRECATEDIN_3_0 void DSA_set_flags(DSA *d, int flags);
+OSSL_DEPRECATEDIN_3_0 ENGINE *DSA_get0_engine(DSA *d);
+
+OSSL_DEPRECATEDIN_3_0 DSA_METHOD *DSA_meth_new(const char *name, int flags);
+OSSL_DEPRECATEDIN_3_0 void DSA_meth_free(DSA_METHOD *dsam);
+OSSL_DEPRECATEDIN_3_0 DSA_METHOD *DSA_meth_dup(const DSA_METHOD *dsam);
+OSSL_DEPRECATEDIN_3_0 const char *DSA_meth_get0_name(const DSA_METHOD *dsam);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set1_name(DSA_METHOD *dsam,
+ const char *name);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_get_flags(const DSA_METHOD *dsam);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_flags(DSA_METHOD *dsam, int flags);
+OSSL_DEPRECATEDIN_3_0 void *DSA_meth_get0_app_data(const DSA_METHOD *dsam);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set0_app_data(DSA_METHOD *dsam,
+ void *app_data);
+OSSL_DEPRECATEDIN_3_0 DSA_SIG *(*DSA_meth_get_sign(const DSA_METHOD *dsam))
+ (const unsigned char *, int, DSA *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_sign(DSA_METHOD *dsam,
+ DSA_SIG *(*sign) (const unsigned char *, int, DSA *));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_sign_setup(const DSA_METHOD *dsam))
+ (DSA *, BN_CTX *, BIGNUM **, BIGNUM **);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_sign_setup(DSA_METHOD *dsam,
+ int (*sign_setup) (DSA *, BN_CTX *, BIGNUM **, BIGNUM **));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_verify(const DSA_METHOD *dsam))
+ (const unsigned char *, int, DSA_SIG *, DSA *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_verify(DSA_METHOD *dsam,
+ int (*verify) (const unsigned char *, int, DSA_SIG *, DSA *));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_mod_exp(const DSA_METHOD *dsam))
+ (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *,
+ const BIGNUM *, const BIGNUM *, BN_CTX *, BN_MONT_CTX *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_mod_exp(DSA_METHOD *dsam,
+ int (*mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *,
+ const BIGNUM *, const BIGNUM *, const BIGNUM *, BN_CTX *,
+ BN_MONT_CTX *));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_bn_mod_exp(const DSA_METHOD *dsam))
+ (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *, const BIGNUM *,
+ BN_CTX *, BN_MONT_CTX *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_bn_mod_exp(DSA_METHOD *dsam,
+ int (*bn_mod_exp) (DSA *, BIGNUM *, const BIGNUM *, const BIGNUM *,
+ const BIGNUM *, BN_CTX *, BN_MONT_CTX *));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_init(const DSA_METHOD *dsam))(DSA *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_init(DSA_METHOD *dsam,
+ int (*init)(DSA *));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_finish(const DSA_METHOD *dsam))(DSA *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_finish(DSA_METHOD *dsam,
+ int (*finish)(DSA *));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_paramgen(const DSA_METHOD *dsam))
+ (DSA *, int, const unsigned char *, int, int *, unsigned long *,
+ BN_GENCB *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_paramgen(DSA_METHOD *dsam,
+ int (*paramgen) (DSA *, int, const unsigned char *, int, int *,
+ unsigned long *, BN_GENCB *));
+OSSL_DEPRECATEDIN_3_0 int (*DSA_meth_get_keygen(const DSA_METHOD *dsam))(DSA *);
+OSSL_DEPRECATEDIN_3_0 int DSA_meth_set_keygen(DSA_METHOD *dsam,
+ int (*keygen) (DSA *));
+
+# endif
+# endif
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/dsaerr.h b/include/openssl/dsaerr.h
new file mode 100644
index 00000000..5f0ca8d1
--- /dev/null
+++ b/include/openssl/dsaerr.h
@@ -0,0 +1,43 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DSAERR_H
+# define OPENSSL_DSAERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_DSA
+
+
+/*
+ * DSA reason codes.
+ */
+# define DSA_R_BAD_FFC_PARAMETERS 114
+# define DSA_R_BAD_Q_VALUE 102
+# define DSA_R_BN_DECODE_ERROR 108
+# define DSA_R_BN_ERROR 109
+# define DSA_R_DECODE_ERROR 104
+# define DSA_R_INVALID_DIGEST_TYPE 106
+# define DSA_R_INVALID_PARAMETERS 112
+# define DSA_R_MISSING_PARAMETERS 101
+# define DSA_R_MISSING_PRIVATE_KEY 111
+# define DSA_R_MODULUS_TOO_LARGE 103
+# define DSA_R_NO_PARAMETERS_SET 107
+# define DSA_R_PARAMETER_ENCODING_ERROR 105
+# define DSA_R_P_NOT_PRIME 115
+# define DSA_R_Q_NOT_PRIME 113
+# define DSA_R_SEED_LEN_SMALL 110
+
+# endif
+#endif
diff --git a/include/openssl/dtls1.h b/include/openssl/dtls1.h
new file mode 100644
index 00000000..5dc6b541
--- /dev/null
+++ b/include/openssl/dtls1.h
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2005-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_DTLS1_H
+# define OPENSSL_DTLS1_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_DTLS1_H
+# endif
+
+# include <openssl/prov_ssl.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <openssl/opensslconf.h>
+
+/* DTLS*_VERSION constants are defined in prov_ssl.h */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DTLS_MIN_VERSION DTLS1_VERSION
+# define DTLS_MAX_VERSION DTLS1_2_VERSION
+# endif
+# define DTLS1_VERSION_MAJOR 0xFE
+
+/* Special value for method supporting multiple versions */
+# define DTLS_ANY_VERSION 0x1FFFF
+
+/* lengths of messages */
+
+# define DTLS1_COOKIE_LENGTH 255
+
+# define DTLS1_RT_HEADER_LENGTH 13
+
+# define DTLS1_HM_HEADER_LENGTH 12
+
+# define DTLS1_HM_BAD_FRAGMENT -2
+# define DTLS1_HM_FRAGMENT_RETRY -3
+
+# define DTLS1_CCS_HEADER_LENGTH 1
+
+# define DTLS1_AL_HEADER_LENGTH 2
+
+# define DTLS1_TMO_ALERT_COUNT 12
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/e_os2.h b/include/openssl/e_os2.h
new file mode 100644
index 00000000..67289092
--- /dev/null
+++ b/include/openssl/e_os2.h
@@ -0,0 +1,305 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_E_OS2_H
+# define OPENSSL_E_OS2_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_E_OS2_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/******************************************************************************
+ * Detect operating systems. This probably needs completing.
+ * The result is that at least one OPENSSL_SYS_os macro should be defined.
+ * However, if none is defined, Unix is assumed.
+ **/
+
+# define OPENSSL_SYS_UNIX
+
+/* --------------------- Microsoft operating systems ---------------------- */
+
+/*
+ * Note that MSDOS actually denotes 32-bit environments running on top of
+ * MS-DOS, such as DJGPP one.
+ */
+# if defined(OPENSSL_SYS_MSDOS)
+# undef OPENSSL_SYS_UNIX
+# endif
+
+/*
+ * For 32 bit environment, there seems to be the CygWin environment and then
+ * all the others that try to do the same thing Microsoft does...
+ */
+/*
+ * UEFI lives here because it might be built with a Microsoft toolchain and
+ * we need to avoid the false positive match on Windows.
+ */
+# if defined(OPENSSL_SYS_UEFI)
+# undef OPENSSL_SYS_UNIX
+# elif defined(OPENSSL_SYS_UWIN)
+# undef OPENSSL_SYS_UNIX
+# define OPENSSL_SYS_WIN32_UWIN
+# else
+# if defined(__CYGWIN__) || defined(OPENSSL_SYS_CYGWIN)
+# define OPENSSL_SYS_WIN32_CYGWIN
+# else
+# if defined(_WIN32) || defined(OPENSSL_SYS_WIN32)
+# undef OPENSSL_SYS_UNIX
+# if !defined(OPENSSL_SYS_WIN32)
+# define OPENSSL_SYS_WIN32
+# endif
+# endif
+# if defined(_WIN64) || defined(OPENSSL_SYS_WIN64)
+# undef OPENSSL_SYS_UNIX
+# if !defined(OPENSSL_SYS_WIN64)
+# define OPENSSL_SYS_WIN64
+# endif
+# endif
+# if defined(OPENSSL_SYS_WINNT)
+# undef OPENSSL_SYS_UNIX
+# endif
+# if defined(OPENSSL_SYS_WINCE)
+# undef OPENSSL_SYS_UNIX
+# endif
+# endif
+# endif
+
+/* Anything that tries to look like Microsoft is "Windows" */
+# if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_WIN64) || defined(OPENSSL_SYS_WINNT) || defined(OPENSSL_SYS_WINCE)
+# undef OPENSSL_SYS_UNIX
+# define OPENSSL_SYS_WINDOWS
+# ifndef OPENSSL_SYS_MSDOS
+# define OPENSSL_SYS_MSDOS
+# endif
+# endif
+
+/*
+ * DLL settings. This part is a bit tough, because it's up to the
+ * application implementor how he or she will link the application, so it
+ * requires some macro to be used.
+ */
+# ifdef OPENSSL_SYS_WINDOWS
+# ifndef OPENSSL_OPT_WINDLL
+# if defined(_WINDLL) /* This is used when building OpenSSL to
+ * indicate that DLL linkage should be used */
+# define OPENSSL_OPT_WINDLL
+# endif
+# endif
+# endif
+
+/* ------------------------------- OpenVMS -------------------------------- */
+# if defined(__VMS) || defined(VMS)
+# if !defined(OPENSSL_SYS_VMS)
+# undef OPENSSL_SYS_UNIX
+# define OPENSSL_SYS_VMS
+# endif
+# if defined(__DECC)
+# define OPENSSL_SYS_VMS_DECC
+# elif defined(__DECCXX)
+# define OPENSSL_SYS_VMS_DECC
+# define OPENSSL_SYS_VMS_DECCXX
+# else
+# define OPENSSL_SYS_VMS_NODECC
+# endif
+# endif
+
+/* -------------------------------- Unix ---------------------------------- */
+# ifdef OPENSSL_SYS_UNIX
+# if defined(linux) || defined(__linux__) && !defined(OPENSSL_SYS_LINUX)
+# define OPENSSL_SYS_LINUX
+# endif
+# if defined(_AIX) && !defined(OPENSSL_SYS_AIX)
+# define OPENSSL_SYS_AIX
+# endif
+# endif
+
+/* -------------------------------- VOS ----------------------------------- */
+# if defined(__VOS__) && !defined(OPENSSL_SYS_VOS)
+# define OPENSSL_SYS_VOS
+# ifdef __HPPA__
+# define OPENSSL_SYS_VOS_HPPA
+# endif
+# ifdef __IA32__
+# define OPENSSL_SYS_VOS_IA32
+# endif
+# endif
+
+/* ---------------------------- HP NonStop -------------------------------- */
+# ifdef __TANDEM
+# ifdef _STRING
+# include <strings.h>
+# endif
+# define OPENSSL_USE_BUILD_DATE
+# if defined(OPENSSL_THREADS) && defined(_SPT_MODEL_)
+# define SPT_THREAD_SIGNAL 1
+# define SPT_THREAD_AWARE 1
+# include <spthread.h>
+# elif defined(OPENSSL_THREADS) && defined(_PUT_MODEL_)
+# include <pthread.h>
+# endif
+# endif
+
+/**
+ * That's it for OS-specific stuff
+ *****************************************************************************/
+
+/*-
+ * OPENSSL_EXTERN is normally used to declare a symbol with possible extra
+ * attributes to handle its presence in a shared library.
+ * OPENSSL_EXPORT is used to define a symbol with extra possible attributes
+ * to make it visible in a shared library.
+ * Care needs to be taken when a header file is used both to declare and
+ * define symbols. Basically, for any library that exports some global
+ * variables, the following code must be present in the header file that
+ * declares them, before OPENSSL_EXTERN is used:
+ *
+ * #ifdef SOME_BUILD_FLAG_MACRO
+ * # undef OPENSSL_EXTERN
+ * # define OPENSSL_EXTERN OPENSSL_EXPORT
+ * #endif
+ *
+ * The default is to have OPENSSL_EXPORT and OPENSSL_EXTERN
+ * have some generally sensible values.
+ */
+
+# if defined(OPENSSL_SYS_WINDOWS) && defined(OPENSSL_OPT_WINDLL)
+# define OPENSSL_EXPORT extern __declspec(dllexport)
+# define OPENSSL_EXTERN extern __declspec(dllimport)
+# else
+# define OPENSSL_EXPORT extern
+# define OPENSSL_EXTERN extern
+# endif
+
+# ifdef _WIN32
+# ifdef _WIN64
+# define ossl_ssize_t __int64
+# define OSSL_SSIZE_MAX _I64_MAX
+# else
+# define ossl_ssize_t int
+# define OSSL_SSIZE_MAX INT_MAX
+# endif
+# endif
+
+# if defined(OPENSSL_SYS_UEFI) && !defined(ossl_ssize_t)
+# define ossl_ssize_t INTN
+# define OSSL_SSIZE_MAX MAX_INTN
+# endif
+
+# ifndef ossl_ssize_t
+# define ossl_ssize_t ssize_t
+# if defined(SSIZE_MAX)
+# define OSSL_SSIZE_MAX SSIZE_MAX
+# elif defined(_POSIX_SSIZE_MAX)
+# define OSSL_SSIZE_MAX _POSIX_SSIZE_MAX
+# else
+# define OSSL_SSIZE_MAX ((ssize_t)(SIZE_MAX>>1))
+# endif
+# endif
+
+# if defined(UNUSEDRESULT_DEBUG)
+# define __owur __attribute__((__warn_unused_result__))
+# else
+# define __owur
+# endif
+
+/* Standard integer types */
+# define OPENSSL_NO_INTTYPES_H
+# define OPENSSL_NO_STDINT_H
+# if defined(OPENSSL_SYS_UEFI)
+typedef INT8 int8_t;
+typedef UINT8 uint8_t;
+typedef INT16 int16_t;
+typedef UINT16 uint16_t;
+typedef INT32 int32_t;
+typedef UINT32 uint32_t;
+typedef INT64 int64_t;
+typedef UINT64 uint64_t;
+# elif (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L) || \
+ defined(__osf__) || defined(__sgi) || defined(__hpux) || \
+ defined(OPENSSL_SYS_VMS) || defined (__OpenBSD__)
+# include <inttypes.h>
+# undef OPENSSL_NO_INTTYPES_H
+/* Because the specs say that inttypes.h includes stdint.h if present */
+# undef OPENSSL_NO_STDINT_H
+# elif defined(_MSC_VER) && _MSC_VER<1600
+/*
+ * minimally required typdefs for systems not supporting inttypes.h or
+ * stdint.h: currently just older VC++
+ */
+typedef signed char int8_t;
+typedef unsigned char uint8_t;
+typedef short int16_t;
+typedef unsigned short uint16_t;
+typedef int int32_t;
+typedef unsigned int uint32_t;
+typedef __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+# else
+# include <stdint.h>
+# undef OPENSSL_NO_STDINT_H
+# endif
+# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L && \
+ defined(INTMAX_MAX) && defined(UINTMAX_MAX)
+typedef intmax_t ossl_intmax_t;
+typedef uintmax_t ossl_uintmax_t;
+# else
+/* Fall back to the largest we know we require and can handle */
+typedef int64_t ossl_intmax_t;
+typedef uint64_t ossl_uintmax_t;
+# endif
+
+/* ossl_inline: portable inline definition usable in public headers */
+# if !defined(inline) && !defined(__cplusplus)
+# if defined(__STDC_VERSION__) && __STDC_VERSION__>=199901L
+ /* just use inline */
+# define ossl_inline inline
+# elif defined(__GNUC__) && __GNUC__>=2
+# define ossl_inline __inline__
+# elif defined(_MSC_VER)
+ /*
+ * Visual Studio: inline is available in C++ only, however
+ * __inline is available for C, see
+ * http://msdn.microsoft.com/en-us/library/z8y1yy88.aspx
+ */
+# define ossl_inline __inline
+# else
+# define ossl_inline
+# endif
+# else
+# define ossl_inline inline
+# endif
+
+# if defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L && \
+ !defined(__cplusplus)
+# define ossl_noreturn _Noreturn
+# elif defined(__GNUC__) && __GNUC__ >= 2
+# define ossl_noreturn __attribute__((noreturn))
+# else
+# define ossl_noreturn
+# endif
+
+/* ossl_unused: portable unused attribute for use in public headers */
+# if defined(__GNUC__)
+# define ossl_unused __attribute__((unused))
+# else
+# define ossl_unused
+# endif
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/ebcdic.h b/include/openssl/ebcdic.h
new file mode 100644
index 00000000..e0ae1aa8
--- /dev/null
+++ b/include/openssl/ebcdic.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright 1999-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_EBCDIC_H
+# define OPENSSL_EBCDIC_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_EBCDIC_H
+# endif
+
+# include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Avoid name clashes with other applications */
+# define os_toascii _openssl_os_toascii
+# define os_toebcdic _openssl_os_toebcdic
+# define ebcdic2ascii _openssl_ebcdic2ascii
+# define ascii2ebcdic _openssl_ascii2ebcdic
+
+extern const unsigned char os_toascii[256];
+extern const unsigned char os_toebcdic[256];
+void *ebcdic2ascii(void *dest, const void *srce, size_t count);
+void *ascii2ebcdic(void *dest, const void *srce, size_t count);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/ec.h b/include/openssl/ec.h
new file mode 100644
index 00000000..f59b4f92
--- /dev/null
+++ b/include/openssl/ec.h
@@ -0,0 +1,1566 @@
+/*
+ * Copyright 2002-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_EC_H
+# define OPENSSL_EC_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_EC_H
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* Values for EVP_PKEY_CTX_set_ec_param_enc() */
+# define OPENSSL_EC_EXPLICIT_CURVE 0x000
+# define OPENSSL_EC_NAMED_CURVE 0x001
+
+int EVP_PKEY_CTX_set_ec_paramgen_curve_nid(EVP_PKEY_CTX *ctx, int nid);
+int EVP_PKEY_CTX_set_ec_param_enc(EVP_PKEY_CTX *ctx, int param_enc);
+int EVP_PKEY_CTX_set_ecdh_cofactor_mode(EVP_PKEY_CTX *ctx, int cofactor_mode);
+int EVP_PKEY_CTX_get_ecdh_cofactor_mode(EVP_PKEY_CTX *ctx);
+
+int EVP_PKEY_CTX_set_ecdh_kdf_type(EVP_PKEY_CTX *ctx, int kdf);
+int EVP_PKEY_CTX_get_ecdh_kdf_type(EVP_PKEY_CTX *ctx);
+
+int EVP_PKEY_CTX_set_ecdh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+int EVP_PKEY_CTX_get_ecdh_kdf_md(EVP_PKEY_CTX *ctx, const EVP_MD **md);
+
+int EVP_PKEY_CTX_set_ecdh_kdf_outlen(EVP_PKEY_CTX *ctx, int len);
+int EVP_PKEY_CTX_get_ecdh_kdf_outlen(EVP_PKEY_CTX *ctx, int *len);
+
+int EVP_PKEY_CTX_set0_ecdh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char *ukm,
+ int len);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_CTX_get0_ecdh_kdf_ukm(EVP_PKEY_CTX *ctx, unsigned char **ukm);
+# endif
+
+# define EVP_PKEY_CTRL_EC_PARAMGEN_CURVE_NID (EVP_PKEY_ALG_CTRL + 1)
+# define EVP_PKEY_CTRL_EC_PARAM_ENC (EVP_PKEY_ALG_CTRL + 2)
+# define EVP_PKEY_CTRL_EC_ECDH_COFACTOR (EVP_PKEY_ALG_CTRL + 3)
+# define EVP_PKEY_CTRL_EC_KDF_TYPE (EVP_PKEY_ALG_CTRL + 4)
+# define EVP_PKEY_CTRL_EC_KDF_MD (EVP_PKEY_ALG_CTRL + 5)
+# define EVP_PKEY_CTRL_GET_EC_KDF_MD (EVP_PKEY_ALG_CTRL + 6)
+# define EVP_PKEY_CTRL_EC_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 7)
+# define EVP_PKEY_CTRL_GET_EC_KDF_OUTLEN (EVP_PKEY_ALG_CTRL + 8)
+# define EVP_PKEY_CTRL_EC_KDF_UKM (EVP_PKEY_ALG_CTRL + 9)
+# define EVP_PKEY_CTRL_GET_EC_KDF_UKM (EVP_PKEY_ALG_CTRL + 10)
+
+/* KDF types */
+# define EVP_PKEY_ECDH_KDF_NONE 1
+# define EVP_PKEY_ECDH_KDF_X9_63 2
+/*
+ * The old name for EVP_PKEY_ECDH_KDF_X9_63
+ * The ECDH KDF specification has been mistakenly attributed to ANSI X9.62,
+ * it is actually specified in ANSI X9.63.
+ * This identifier is retained for backwards compatibility
+ */
+# define EVP_PKEY_ECDH_KDF_X9_62 EVP_PKEY_ECDH_KDF_X9_63
+
+/** Enum for the point conversion form as defined in X9.62 (ECDSA)
+ * for the encoding of a elliptic curve point (x,y) */
+typedef enum {
+ /** the point is encoded as z||x, where the octet z specifies
+ * which solution of the quadratic equation y is */
+ POINT_CONVERSION_COMPRESSED = 2,
+ /** the point is encoded as z||x||y, where z is the octet 0x04 */
+ POINT_CONVERSION_UNCOMPRESSED = 4,
+ /** the point is encoded as z||x||y, where the octet z specifies
+ * which solution of the quadratic equation y is */
+ POINT_CONVERSION_HYBRID = 6
+} point_conversion_form_t;
+
+const char *OSSL_EC_curve_nid2name(int nid);
+
+# ifndef OPENSSL_NO_EC
+# include <openssl/asn1.h>
+# include <openssl/symhacks.h>
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/bn.h>
+# endif
+# include <openssl/ecerr.h>
+
+# ifndef OPENSSL_ECC_MAX_FIELD_BITS
+# define OPENSSL_ECC_MAX_FIELD_BITS 661
+# endif
+
+# include <openssl/params.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef struct ec_method_st EC_METHOD;
+# endif
+typedef struct ec_group_st EC_GROUP;
+typedef struct ec_point_st EC_POINT;
+typedef struct ecpk_parameters_st ECPKPARAMETERS;
+typedef struct ec_parameters_st ECPARAMETERS;
+
+/********************************************************************/
+/* EC_METHODs for curves over GF(p) */
+/********************************************************************/
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/** Returns the basic GFp ec methods which provides the basis for the
+ * optimized methods.
+ * \return EC_METHOD object
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GFp_simple_method(void);
+
+/** Returns GFp methods using montgomery multiplication.
+ * \return EC_METHOD object
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GFp_mont_method(void);
+
+/** Returns GFp methods using optimized methods for NIST recommended curves
+ * \return EC_METHOD object
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GFp_nist_method(void);
+
+# ifndef OPENSSL_NO_EC_NISTP_64_GCC_128
+/** Returns 64-bit optimized methods for nistp224
+ * \return EC_METHOD object
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GFp_nistp224_method(void);
+
+/** Returns 64-bit optimized methods for nistp256
+ * \return EC_METHOD object
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GFp_nistp256_method(void);
+
+/** Returns 64-bit optimized methods for nistp521
+ * \return EC_METHOD object
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GFp_nistp521_method(void);
+# endif /* OPENSSL_NO_EC_NISTP_64_GCC_128 */
+
+# ifndef OPENSSL_NO_EC2M
+/********************************************************************/
+/* EC_METHOD for curves over GF(2^m) */
+/********************************************************************/
+
+/** Returns the basic GF2m ec method
+ * \return EC_METHOD object
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GF2m_simple_method(void);
+
+# endif
+
+/********************************************************************/
+/* EC_GROUP functions */
+/********************************************************************/
+
+/**
+ * Creates a new EC_GROUP object
+ * \param meth EC_METHOD to use
+ * \return newly created EC_GROUP object or NULL in case of an error.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_GROUP *EC_GROUP_new(const EC_METHOD *meth);
+
+/** Clears and frees a EC_GROUP object
+ * \param group EC_GROUP object to be cleared and freed.
+ */
+OSSL_DEPRECATEDIN_3_0 void EC_GROUP_clear_free(EC_GROUP *group);
+
+/** Returns the EC_METHOD of the EC_GROUP object.
+ * \param group EC_GROUP object
+ * \return EC_METHOD used in this EC_GROUP object.
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_GROUP_method_of(const EC_GROUP *group);
+
+/** Returns the field type of the EC_METHOD.
+ * \param meth EC_METHOD object
+ * \return NID of the underlying field type OID.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_METHOD_get_field_type(const EC_METHOD *meth);
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/** Frees a EC_GROUP object
+ * \param group EC_GROUP object to be freed.
+ */
+void EC_GROUP_free(EC_GROUP *group);
+
+/** Copies EC_GROUP objects. Note: both EC_GROUPs must use the same EC_METHOD.
+ * \param dst destination EC_GROUP object
+ * \param src source EC_GROUP object
+ * \return 1 on success and 0 if an error occurred.
+ */
+int EC_GROUP_copy(EC_GROUP *dst, const EC_GROUP *src);
+
+/** Creates a new EC_GROUP object and copies the content
+ * form src to the newly created EC_KEY object
+ * \param src source EC_GROUP object
+ * \return newly created EC_GROUP object or NULL in case of an error.
+ */
+EC_GROUP *EC_GROUP_dup(const EC_GROUP *src);
+
+/** Sets the generator and its order/cofactor of a EC_GROUP object.
+ * \param group EC_GROUP object
+ * \param generator EC_POINT object with the generator.
+ * \param order the order of the group generated by the generator.
+ * \param cofactor the index of the sub-group generated by the generator
+ * in the group of all points on the elliptic curve.
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_GROUP_set_generator(EC_GROUP *group, const EC_POINT *generator,
+ const BIGNUM *order, const BIGNUM *cofactor);
+
+/** Returns the generator of a EC_GROUP object.
+ * \param group EC_GROUP object
+ * \return the currently used generator (possibly NULL).
+ */
+const EC_POINT *EC_GROUP_get0_generator(const EC_GROUP *group);
+
+/** Returns the montgomery data for order(Generator)
+ * \param group EC_GROUP object
+ * \return the currently used montgomery data (possibly NULL).
+*/
+BN_MONT_CTX *EC_GROUP_get_mont_data(const EC_GROUP *group);
+
+/** Gets the order of a EC_GROUP
+ * \param group EC_GROUP object
+ * \param order BIGNUM to which the order is copied
+ * \param ctx unused
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_GROUP_get_order(const EC_GROUP *group, BIGNUM *order, BN_CTX *ctx);
+
+/** Gets the order of an EC_GROUP
+ * \param group EC_GROUP object
+ * \return the group order
+ */
+const BIGNUM *EC_GROUP_get0_order(const EC_GROUP *group);
+
+/** Gets the number of bits of the order of an EC_GROUP
+ * \param group EC_GROUP object
+ * \return number of bits of group order.
+ */
+int EC_GROUP_order_bits(const EC_GROUP *group);
+
+/** Gets the cofactor of a EC_GROUP
+ * \param group EC_GROUP object
+ * \param cofactor BIGNUM to which the cofactor is copied
+ * \param ctx unused
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_GROUP_get_cofactor(const EC_GROUP *group, BIGNUM *cofactor,
+ BN_CTX *ctx);
+
+/** Gets the cofactor of an EC_GROUP
+ * \param group EC_GROUP object
+ * \return the group cofactor
+ */
+const BIGNUM *EC_GROUP_get0_cofactor(const EC_GROUP *group);
+
+/** Sets the name of a EC_GROUP object
+ * \param group EC_GROUP object
+ * \param nid NID of the curve name OID
+ */
+void EC_GROUP_set_curve_name(EC_GROUP *group, int nid);
+
+/** Returns the curve name of a EC_GROUP object
+ * \param group EC_GROUP object
+ * \return NID of the curve name OID or 0 if not set.
+ */
+int EC_GROUP_get_curve_name(const EC_GROUP *group);
+
+/** Gets the field of an EC_GROUP
+ * \param group EC_GROUP object
+ * \return the group field
+ */
+const BIGNUM *EC_GROUP_get0_field(const EC_GROUP *group);
+
+/** Returns the field type of the EC_GROUP.
+ * \param group EC_GROUP object
+ * \return NID of the underlying field type OID.
+ */
+int EC_GROUP_get_field_type(const EC_GROUP *group);
+
+void EC_GROUP_set_asn1_flag(EC_GROUP *group, int flag);
+int EC_GROUP_get_asn1_flag(const EC_GROUP *group);
+
+void EC_GROUP_set_point_conversion_form(EC_GROUP *group,
+ point_conversion_form_t form);
+point_conversion_form_t EC_GROUP_get_point_conversion_form(const EC_GROUP *);
+
+unsigned char *EC_GROUP_get0_seed(const EC_GROUP *x);
+size_t EC_GROUP_get_seed_len(const EC_GROUP *);
+size_t EC_GROUP_set_seed(EC_GROUP *, const unsigned char *, size_t len);
+
+/** Sets the parameters of an ec curve defined by y^2 = x^3 + a*x + b (for GFp)
+ * or y^2 + x*y = x^3 + a*x^2 + b (for GF2m)
+ * \param group EC_GROUP object
+ * \param p BIGNUM with the prime number (GFp) or the polynomial
+ * defining the underlying field (GF2m)
+ * \param a BIGNUM with parameter a of the equation
+ * \param b BIGNUM with parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_GROUP_set_curve(EC_GROUP *group, const BIGNUM *p, const BIGNUM *a,
+ const BIGNUM *b, BN_CTX *ctx);
+
+/** Gets the parameters of the ec curve defined by y^2 = x^3 + a*x + b (for GFp)
+ * or y^2 + x*y = x^3 + a*x^2 + b (for GF2m)
+ * \param group EC_GROUP object
+ * \param p BIGNUM with the prime number (GFp) or the polynomial
+ * defining the underlying field (GF2m)
+ * \param a BIGNUM for parameter a of the equation
+ * \param b BIGNUM for parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_GROUP_get_curve(const EC_GROUP *group, BIGNUM *p, BIGNUM *a, BIGNUM *b,
+ BN_CTX *ctx);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/** Sets the parameters of an ec curve. Synonym for EC_GROUP_set_curve
+ * \param group EC_GROUP object
+ * \param p BIGNUM with the prime number (GFp) or the polynomial
+ * defining the underlying field (GF2m)
+ * \param a BIGNUM with parameter a of the equation
+ * \param b BIGNUM with parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_GROUP_set_curve_GFp(EC_GROUP *group,
+ const BIGNUM *p,
+ const BIGNUM *a,
+ const BIGNUM *b,
+ BN_CTX *ctx);
+
+/** Gets the parameters of an ec curve. Synonym for EC_GROUP_get_curve
+ * \param group EC_GROUP object
+ * \param p BIGNUM with the prime number (GFp) or the polynomial
+ * defining the underlying field (GF2m)
+ * \param a BIGNUM for parameter a of the equation
+ * \param b BIGNUM for parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_GROUP_get_curve_GFp(const EC_GROUP *group,
+ BIGNUM *p,
+ BIGNUM *a, BIGNUM *b,
+ BN_CTX *ctx);
+
+# ifndef OPENSSL_NO_EC2M
+/** Sets the parameter of an ec curve. Synonym for EC_GROUP_set_curve
+ * \param group EC_GROUP object
+ * \param p BIGNUM with the prime number (GFp) or the polynomial
+ * defining the underlying field (GF2m)
+ * \param a BIGNUM with parameter a of the equation
+ * \param b BIGNUM with parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_GROUP_set_curve_GF2m(EC_GROUP *group,
+ const BIGNUM *p,
+ const BIGNUM *a,
+ const BIGNUM *b,
+ BN_CTX *ctx);
+
+/** Gets the parameters of an ec curve. Synonym for EC_GROUP_get_curve
+ * \param group EC_GROUP object
+ * \param p BIGNUM with the prime number (GFp) or the polynomial
+ * defining the underlying field (GF2m)
+ * \param a BIGNUM for parameter a of the equation
+ * \param b BIGNUM for parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_GROUP_get_curve_GF2m(const EC_GROUP *group,
+ BIGNUM *p,
+ BIGNUM *a, BIGNUM *b,
+ BN_CTX *ctx);
+# endif /* OPENSSL_NO_EC2M */
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/** Returns the number of bits needed to represent a field element
+ * \param group EC_GROUP object
+ * \return number of bits needed to represent a field element
+ */
+int EC_GROUP_get_degree(const EC_GROUP *group);
+
+/** Checks whether the parameter in the EC_GROUP define a valid ec group
+ * \param group EC_GROUP object
+ * \param ctx BN_CTX object (optional)
+ * \return 1 if group is a valid ec group and 0 otherwise
+ */
+int EC_GROUP_check(const EC_GROUP *group, BN_CTX *ctx);
+
+/** Checks whether the discriminant of the elliptic curve is zero or not
+ * \param group EC_GROUP object
+ * \param ctx BN_CTX object (optional)
+ * \return 1 if the discriminant is not zero and 0 otherwise
+ */
+int EC_GROUP_check_discriminant(const EC_GROUP *group, BN_CTX *ctx);
+
+/** Compares two EC_GROUP objects
+ * \param a first EC_GROUP object
+ * \param b second EC_GROUP object
+ * \param ctx BN_CTX object (optional)
+ * \return 0 if the groups are equal, 1 if not, or -1 on error
+ */
+int EC_GROUP_cmp(const EC_GROUP *a, const EC_GROUP *b, BN_CTX *ctx);
+
+/*
+ * EC_GROUP_new_GF*() calls EC_GROUP_new() and EC_GROUP_set_GF*() after
+ * choosing an appropriate EC_METHOD
+ */
+
+/** Creates a new EC_GROUP object with the specified parameters defined
+ * over GFp (defined by the equation y^2 = x^3 + a*x + b)
+ * \param p BIGNUM with the prime number
+ * \param a BIGNUM with the parameter a of the equation
+ * \param b BIGNUM with the parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return newly created EC_GROUP object with the specified parameters
+ */
+EC_GROUP *EC_GROUP_new_curve_GFp(const BIGNUM *p, const BIGNUM *a,
+ const BIGNUM *b, BN_CTX *ctx);
+# ifndef OPENSSL_NO_EC2M
+/** Creates a new EC_GROUP object with the specified parameters defined
+ * over GF2m (defined by the equation y^2 + x*y = x^3 + a*x^2 + b)
+ * \param p BIGNUM with the polynomial defining the underlying field
+ * \param a BIGNUM with the parameter a of the equation
+ * \param b BIGNUM with the parameter b of the equation
+ * \param ctx BN_CTX object (optional)
+ * \return newly created EC_GROUP object with the specified parameters
+ */
+EC_GROUP *EC_GROUP_new_curve_GF2m(const BIGNUM *p, const BIGNUM *a,
+ const BIGNUM *b, BN_CTX *ctx);
+# endif
+
+/**
+ * Creates a EC_GROUP object with a curve specified by parameters.
+ * The parameters may be explicit or a named curve,
+ * \param params A list of parameters describing the group.
+ * \param libctx The associated library context or NULL for the default
+ * context
+ * \param propq A property query string
+ * \return newly created EC_GROUP object with specified parameters or NULL
+ * if an error occurred
+ */
+EC_GROUP *EC_GROUP_new_from_params(const OSSL_PARAM params[],
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+/**
+ * Creates a EC_GROUP object with a curve specified by a NID
+ * \param libctx The associated library context or NULL for the default
+ * context
+ * \param propq A property query string
+ * \param nid NID of the OID of the curve name
+ * \return newly created EC_GROUP object with specified curve or NULL
+ * if an error occurred
+ */
+EC_GROUP *EC_GROUP_new_by_curve_name_ex(OSSL_LIB_CTX *libctx, const char *propq,
+ int nid);
+
+/**
+ * Creates a EC_GROUP object with a curve specified by a NID. Same as
+ * EC_GROUP_new_by_curve_name_ex but the libctx and propq are always
+ * NULL.
+ * \param nid NID of the OID of the curve name
+ * \return newly created EC_GROUP object with specified curve or NULL
+ * if an error occurred
+ */
+EC_GROUP *EC_GROUP_new_by_curve_name(int nid);
+
+/** Creates a new EC_GROUP object from an ECPARAMETERS object
+ * \param params pointer to the ECPARAMETERS object
+ * \return newly created EC_GROUP object with specified curve or NULL
+ * if an error occurred
+ */
+EC_GROUP *EC_GROUP_new_from_ecparameters(const ECPARAMETERS *params);
+
+/** Creates an ECPARAMETERS object for the given EC_GROUP object.
+ * \param group pointer to the EC_GROUP object
+ * \param params pointer to an existing ECPARAMETERS object or NULL
+ * \return pointer to the new ECPARAMETERS object or NULL
+ * if an error occurred.
+ */
+ECPARAMETERS *EC_GROUP_get_ecparameters(const EC_GROUP *group,
+ ECPARAMETERS *params);
+
+/** Creates a new EC_GROUP object from an ECPKPARAMETERS object
+ * \param params pointer to an existing ECPKPARAMETERS object, or NULL
+ * \return newly created EC_GROUP object with specified curve, or NULL
+ * if an error occurred
+ */
+EC_GROUP *EC_GROUP_new_from_ecpkparameters(const ECPKPARAMETERS *params);
+
+/** Creates an ECPKPARAMETERS object for the given EC_GROUP object.
+ * \param group pointer to the EC_GROUP object
+ * \param params pointer to an existing ECPKPARAMETERS object or NULL
+ * \return pointer to the new ECPKPARAMETERS object or NULL
+ * if an error occurred.
+ */
+ECPKPARAMETERS *EC_GROUP_get_ecpkparameters(const EC_GROUP *group,
+ ECPKPARAMETERS *params);
+
+/********************************************************************/
+/* handling of internal curves */
+/********************************************************************/
+
+typedef struct {
+ int nid;
+ const char *comment;
+} EC_builtin_curve;
+
+/*
+ * EC_builtin_curves(EC_builtin_curve *r, size_t size) returns number of all
+ * available curves or zero if a error occurred. In case r is not zero,
+ * nitems EC_builtin_curve structures are filled with the data of the first
+ * nitems internal groups
+ */
+size_t EC_get_builtin_curves(EC_builtin_curve *r, size_t nitems);
+
+const char *EC_curve_nid2nist(int nid);
+int EC_curve_nist2nid(const char *name);
+int EC_GROUP_check_named_curve(const EC_GROUP *group, int nist_only,
+ BN_CTX *ctx);
+
+/********************************************************************/
+/* EC_POINT functions */
+/********************************************************************/
+
+/** Creates a new EC_POINT object for the specified EC_GROUP
+ * \param group EC_GROUP the underlying EC_GROUP object
+ * \return newly created EC_POINT object or NULL if an error occurred
+ */
+EC_POINT *EC_POINT_new(const EC_GROUP *group);
+
+/** Frees a EC_POINT object
+ * \param point EC_POINT object to be freed
+ */
+void EC_POINT_free(EC_POINT *point);
+
+/** Clears and frees a EC_POINT object
+ * \param point EC_POINT object to be cleared and freed
+ */
+void EC_POINT_clear_free(EC_POINT *point);
+
+/** Copies EC_POINT object
+ * \param dst destination EC_POINT object
+ * \param src source EC_POINT object
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_copy(EC_POINT *dst, const EC_POINT *src);
+
+/** Creates a new EC_POINT object and copies the content of the supplied
+ * EC_POINT
+ * \param src source EC_POINT object
+ * \param group underlying the EC_GROUP object
+ * \return newly created EC_POINT object or NULL if an error occurred
+ */
+EC_POINT *EC_POINT_dup(const EC_POINT *src, const EC_GROUP *group);
+
+/** Sets a point to infinity (neutral element)
+ * \param group underlying EC_GROUP object
+ * \param point EC_POINT to set to infinity
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_set_to_infinity(const EC_GROUP *group, EC_POINT *point);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/** Returns the EC_METHOD used in EC_POINT object
+ * \param point EC_POINT object
+ * \return the EC_METHOD used
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_METHOD *EC_POINT_method_of(const EC_POINT *point);
+
+/** Sets the jacobian projective coordinates of a EC_POINT over GFp
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM with the x-coordinate
+ * \param y BIGNUM with the y-coordinate
+ * \param z BIGNUM with the z-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_set_Jprojective_coordinates_GFp
+ (const EC_GROUP *group, EC_POINT *p,
+ const BIGNUM *x, const BIGNUM *y, const BIGNUM *z,
+ BN_CTX *ctx);
+
+/** Gets the jacobian projective coordinates of a EC_POINT over GFp
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM for the x-coordinate
+ * \param y BIGNUM for the y-coordinate
+ * \param z BIGNUM for the z-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_get_Jprojective_coordinates_GFp
+ (const EC_GROUP *group, const EC_POINT *p,
+ BIGNUM *x, BIGNUM *y, BIGNUM *z, BN_CTX *ctx);
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/** Sets the affine coordinates of an EC_POINT
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM with the x-coordinate
+ * \param y BIGNUM with the y-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_set_affine_coordinates(const EC_GROUP *group, EC_POINT *p,
+ const BIGNUM *x, const BIGNUM *y,
+ BN_CTX *ctx);
+
+/** Gets the affine coordinates of an EC_POINT.
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM for the x-coordinate
+ * \param y BIGNUM for the y-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_get_affine_coordinates(const EC_GROUP *group, const EC_POINT *p,
+ BIGNUM *x, BIGNUM *y, BN_CTX *ctx);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/** Sets the affine coordinates of an EC_POINT. A synonym of
+ * EC_POINT_set_affine_coordinates
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM with the x-coordinate
+ * \param y BIGNUM with the y-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_set_affine_coordinates_GFp
+ (const EC_GROUP *group, EC_POINT *p,
+ const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx);
+
+/** Gets the affine coordinates of an EC_POINT. A synonym of
+ * EC_POINT_get_affine_coordinates
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM for the x-coordinate
+ * \param y BIGNUM for the y-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_get_affine_coordinates_GFp
+ (const EC_GROUP *group, const EC_POINT *p,
+ BIGNUM *x, BIGNUM *y, BN_CTX *ctx);
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/** Sets the x9.62 compressed coordinates of a EC_POINT
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM with x-coordinate
+ * \param y_bit integer with the y-Bit (either 0 or 1)
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_set_compressed_coordinates(const EC_GROUP *group, EC_POINT *p,
+ const BIGNUM *x, int y_bit,
+ BN_CTX *ctx);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/** Sets the x9.62 compressed coordinates of a EC_POINT. A synonym of
+ * EC_POINT_set_compressed_coordinates
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM with x-coordinate
+ * \param y_bit integer with the y-Bit (either 0 or 1)
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_set_compressed_coordinates_GFp
+ (const EC_GROUP *group, EC_POINT *p,
+ const BIGNUM *x, int y_bit, BN_CTX *ctx);
+# ifndef OPENSSL_NO_EC2M
+/** Sets the affine coordinates of an EC_POINT. A synonym of
+ * EC_POINT_set_affine_coordinates
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM with the x-coordinate
+ * \param y BIGNUM with the y-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_set_affine_coordinates_GF2m
+ (const EC_GROUP *group, EC_POINT *p,
+ const BIGNUM *x, const BIGNUM *y, BN_CTX *ctx);
+
+/** Gets the affine coordinates of an EC_POINT. A synonym of
+ * EC_POINT_get_affine_coordinates
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM for the x-coordinate
+ * \param y BIGNUM for the y-coordinate
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_get_affine_coordinates_GF2m
+ (const EC_GROUP *group, const EC_POINT *p,
+ BIGNUM *x, BIGNUM *y, BN_CTX *ctx);
+
+/** Sets the x9.62 compressed coordinates of a EC_POINT. A synonym of
+ * EC_POINT_set_compressed_coordinates
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param x BIGNUM with x-coordinate
+ * \param y_bit integer with the y-Bit (either 0 or 1)
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_set_compressed_coordinates_GF2m
+ (const EC_GROUP *group, EC_POINT *p,
+ const BIGNUM *x, int y_bit, BN_CTX *ctx);
+# endif
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/** Encodes a EC_POINT object to a octet string
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param form point conversion form
+ * \param buf memory buffer for the result. If NULL the function returns
+ * required buffer size.
+ * \param len length of the memory buffer
+ * \param ctx BN_CTX object (optional)
+ * \return the length of the encoded octet string or 0 if an error occurred
+ */
+size_t EC_POINT_point2oct(const EC_GROUP *group, const EC_POINT *p,
+ point_conversion_form_t form,
+ unsigned char *buf, size_t len, BN_CTX *ctx);
+
+/** Decodes a EC_POINT from a octet string
+ * \param group underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \param buf memory buffer with the encoded ec point
+ * \param len length of the encoded ec point
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_oct2point(const EC_GROUP *group, EC_POINT *p,
+ const unsigned char *buf, size_t len, BN_CTX *ctx);
+
+/** Encodes an EC_POINT object to an allocated octet string
+ * \param group underlying EC_GROUP object
+ * \param point EC_POINT object
+ * \param form point conversion form
+ * \param pbuf returns pointer to allocated buffer
+ * \param ctx BN_CTX object (optional)
+ * \return the length of the encoded octet string or 0 if an error occurred
+ */
+size_t EC_POINT_point2buf(const EC_GROUP *group, const EC_POINT *point,
+ point_conversion_form_t form,
+ unsigned char **pbuf, BN_CTX *ctx);
+
+/* other interfaces to point2oct/oct2point: */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 BIGNUM *EC_POINT_point2bn(const EC_GROUP *,
+ const EC_POINT *,
+ point_conversion_form_t form,
+ BIGNUM *, BN_CTX *);
+OSSL_DEPRECATEDIN_3_0 EC_POINT *EC_POINT_bn2point(const EC_GROUP *,
+ const BIGNUM *,
+ EC_POINT *, BN_CTX *);
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+char *EC_POINT_point2hex(const EC_GROUP *, const EC_POINT *,
+ point_conversion_form_t form, BN_CTX *);
+EC_POINT *EC_POINT_hex2point(const EC_GROUP *, const char *,
+ EC_POINT *, BN_CTX *);
+
+/********************************************************************/
+/* functions for doing EC_POINT arithmetic */
+/********************************************************************/
+
+/** Computes the sum of two EC_POINT
+ * \param group underlying EC_GROUP object
+ * \param r EC_POINT object for the result (r = a + b)
+ * \param a EC_POINT object with the first summand
+ * \param b EC_POINT object with the second summand
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_add(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
+ const EC_POINT *b, BN_CTX *ctx);
+
+/** Computes the double of a EC_POINT
+ * \param group underlying EC_GROUP object
+ * \param r EC_POINT object for the result (r = 2 * a)
+ * \param a EC_POINT object
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_dbl(const EC_GROUP *group, EC_POINT *r, const EC_POINT *a,
+ BN_CTX *ctx);
+
+/** Computes the inverse of a EC_POINT
+ * \param group underlying EC_GROUP object
+ * \param a EC_POINT object to be inverted (it's used for the result as well)
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_invert(const EC_GROUP *group, EC_POINT *a, BN_CTX *ctx);
+
+/** Checks whether the point is the neutral element of the group
+ * \param group the underlying EC_GROUP object
+ * \param p EC_POINT object
+ * \return 1 if the point is the neutral element and 0 otherwise
+ */
+int EC_POINT_is_at_infinity(const EC_GROUP *group, const EC_POINT *p);
+
+/** Checks whether the point is on the curve
+ * \param group underlying EC_GROUP object
+ * \param point EC_POINT object to check
+ * \param ctx BN_CTX object (optional)
+ * \return 1 if the point is on the curve, 0 if not, or -1 on error
+ */
+int EC_POINT_is_on_curve(const EC_GROUP *group, const EC_POINT *point,
+ BN_CTX *ctx);
+
+/** Compares two EC_POINTs
+ * \param group underlying EC_GROUP object
+ * \param a first EC_POINT object
+ * \param b second EC_POINT object
+ * \param ctx BN_CTX object (optional)
+ * \return 1 if the points are not equal, 0 if they are, or -1 on error
+ */
+int EC_POINT_cmp(const EC_GROUP *group, const EC_POINT *a, const EC_POINT *b,
+ BN_CTX *ctx);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int EC_POINT_make_affine(const EC_GROUP *group,
+ EC_POINT *point, BN_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 int EC_POINTs_make_affine(const EC_GROUP *group, size_t num,
+ EC_POINT *points[], BN_CTX *ctx);
+
+/** Computes r = generator * n + sum_{i=0}^{num-1} p[i] * m[i]
+ * \param group underlying EC_GROUP object
+ * \param r EC_POINT object for the result
+ * \param n BIGNUM with the multiplier for the group generator (optional)
+ * \param num number further summands
+ * \param p array of size num of EC_POINT objects
+ * \param m array of size num of BIGNUM objects
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_POINTs_mul(const EC_GROUP *group, EC_POINT *r,
+ const BIGNUM *n, size_t num,
+ const EC_POINT *p[], const BIGNUM *m[],
+ BN_CTX *ctx);
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/** Computes r = generator * n + q * m
+ * \param group underlying EC_GROUP object
+ * \param r EC_POINT object for the result
+ * \param n BIGNUM with the multiplier for the group generator (optional)
+ * \param q EC_POINT object with the first factor of the second summand
+ * \param m BIGNUM with the second factor of the second summand
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+int EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n,
+ const EC_POINT *q, const BIGNUM *m, BN_CTX *ctx);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/** Stores multiples of generator for faster point multiplication
+ * \param group EC_GROUP object
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_GROUP_precompute_mult(EC_GROUP *group, BN_CTX *ctx);
+
+/** Reports whether a precomputation has been done
+ * \param group EC_GROUP object
+ * \return 1 if a pre-computation has been done and 0 otherwise
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_GROUP_have_precompute_mult(const EC_GROUP *group);
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/********************************************************************/
+/* ASN1 stuff */
+/********************************************************************/
+
+DECLARE_ASN1_ITEM(ECPKPARAMETERS)
+DECLARE_ASN1_ALLOC_FUNCTIONS(ECPKPARAMETERS)
+DECLARE_ASN1_ITEM(ECPARAMETERS)
+DECLARE_ASN1_ALLOC_FUNCTIONS(ECPARAMETERS)
+
+/*
+ * EC_GROUP_get_basis_type() returns the NID of the basis type used to
+ * represent the field elements
+ */
+int EC_GROUP_get_basis_type(const EC_GROUP *);
+# ifndef OPENSSL_NO_EC2M
+int EC_GROUP_get_trinomial_basis(const EC_GROUP *, unsigned int *k);
+int EC_GROUP_get_pentanomial_basis(const EC_GROUP *, unsigned int *k1,
+ unsigned int *k2, unsigned int *k3);
+# endif
+
+EC_GROUP *d2i_ECPKParameters(EC_GROUP **, const unsigned char **in, long len);
+int i2d_ECPKParameters(const EC_GROUP *, unsigned char **out);
+
+# define d2i_ECPKParameters_bio(bp,x) \
+ ASN1_d2i_bio_of(EC_GROUP, NULL, d2i_ECPKParameters, bp, x)
+# define i2d_ECPKParameters_bio(bp,x) \
+ ASN1_i2d_bio_of(EC_GROUP, i2d_ECPKParameters, bp, x)
+# define d2i_ECPKParameters_fp(fp,x) \
+ (EC_GROUP *)ASN1_d2i_fp(NULL, (d2i_of_void *)d2i_ECPKParameters, (fp), \
+ (void **)(x))
+# define i2d_ECPKParameters_fp(fp,x) \
+ ASN1_i2d_fp((i2d_of_void *)i2d_ECPKParameters, (fp), (void *)(x))
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ECPKParameters_print(BIO *bp, const EC_GROUP *x,
+ int off);
+# ifndef OPENSSL_NO_STDIO
+OSSL_DEPRECATEDIN_3_0 int ECPKParameters_print_fp(FILE *fp, const EC_GROUP *x,
+ int off);
+# endif
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/********************************************************************/
+/* EC_KEY functions */
+/********************************************************************/
+
+/* some values for the encoding_flag */
+# define EC_PKEY_NO_PARAMETERS 0x001
+# define EC_PKEY_NO_PUBKEY 0x002
+
+/* some values for the flags field */
+# define EC_FLAG_SM2_RANGE 0x0004
+# define EC_FLAG_COFACTOR_ECDH 0x1000
+# define EC_FLAG_CHECK_NAMED_GROUP 0x2000
+# define EC_FLAG_CHECK_NAMED_GROUP_NIST 0x4000
+# define EC_FLAG_CHECK_NAMED_GROUP_MASK \
+ (EC_FLAG_CHECK_NAMED_GROUP | EC_FLAG_CHECK_NAMED_GROUP_NIST)
+
+/* Deprecated flags - it was using 0x01..0x02 */
+# define EC_FLAG_NON_FIPS_ALLOW 0x0000
+# define EC_FLAG_FIPS_CHECKED 0x0000
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/**
+ * Creates a new EC_KEY object.
+ * \param ctx The library context for to use for this EC_KEY. May be NULL in
+ * which case the default library context is used.
+ * \return EC_KEY object or NULL if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *EC_KEY_new_ex(OSSL_LIB_CTX *ctx, const char *propq);
+
+/**
+ * Creates a new EC_KEY object. Same as calling EC_KEY_new_ex with a
+ * NULL library context
+ * \return EC_KEY object or NULL if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *EC_KEY_new(void);
+
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_get_flags(const EC_KEY *key);
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_set_flags(EC_KEY *key, int flags);
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_clear_flags(EC_KEY *key, int flags);
+
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_decoded_from_explicit_params(const EC_KEY *key);
+
+/**
+ * Creates a new EC_KEY object using a named curve as underlying
+ * EC_GROUP object.
+ * \param ctx The library context for to use for this EC_KEY. May be NULL in
+ * which case the default library context is used.
+ * \param propq Any property query string
+ * \param nid NID of the named curve.
+ * \return EC_KEY object or NULL if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *EC_KEY_new_by_curve_name_ex(OSSL_LIB_CTX *ctx,
+ const char *propq,
+ int nid);
+
+/**
+ * Creates a new EC_KEY object using a named curve as underlying
+ * EC_GROUP object. Same as calling EC_KEY_new_by_curve_name_ex with a NULL
+ * library context and property query string.
+ * \param nid NID of the named curve.
+ * \return EC_KEY object or NULL if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *EC_KEY_new_by_curve_name(int nid);
+
+/** Frees a EC_KEY object.
+ * \param key EC_KEY object to be freed.
+ */
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_free(EC_KEY *key);
+
+/** Copies a EC_KEY object.
+ * \param dst destination EC_KEY object
+ * \param src src EC_KEY object
+ * \return dst or NULL if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *EC_KEY_copy(EC_KEY *dst, const EC_KEY *src);
+
+/** Creates a new EC_KEY object and copies the content from src to it.
+ * \param src the source EC_KEY object
+ * \return newly created EC_KEY object or NULL if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *EC_KEY_dup(const EC_KEY *src);
+
+/** Increases the internal reference count of a EC_KEY object.
+ * \param key EC_KEY object
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_up_ref(EC_KEY *key);
+
+/** Returns the ENGINE object of a EC_KEY object
+ * \param eckey EC_KEY object
+ * \return the ENGINE object (possibly NULL).
+ */
+OSSL_DEPRECATEDIN_3_0 ENGINE *EC_KEY_get0_engine(const EC_KEY *eckey);
+
+/** Returns the EC_GROUP object of a EC_KEY object
+ * \param key EC_KEY object
+ * \return the EC_GROUP object (possibly NULL).
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_GROUP *EC_KEY_get0_group(const EC_KEY *key);
+
+/** Sets the EC_GROUP of a EC_KEY object.
+ * \param key EC_KEY object
+ * \param group EC_GROUP to use in the EC_KEY object (note: the EC_KEY
+ * object will use an own copy of the EC_GROUP).
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_set_group(EC_KEY *key, const EC_GROUP *group);
+
+/** Returns the private key of a EC_KEY object.
+ * \param key EC_KEY object
+ * \return a BIGNUM with the private key (possibly NULL).
+ */
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key);
+
+/** Sets the private key of a EC_KEY object.
+ * \param key EC_KEY object
+ * \param prv BIGNUM with the private key (note: the EC_KEY object
+ * will use an own copy of the BIGNUM).
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_set_private_key(EC_KEY *key, const BIGNUM *prv);
+
+/** Returns the public key of a EC_KEY object.
+ * \param key the EC_KEY object
+ * \return a EC_POINT object with the public key (possibly NULL)
+ */
+OSSL_DEPRECATEDIN_3_0 const EC_POINT *EC_KEY_get0_public_key(const EC_KEY *key);
+
+/** Sets the public key of a EC_KEY object.
+ * \param key EC_KEY object
+ * \param pub EC_POINT object with the public key (note: the EC_KEY object
+ * will use an own copy of the EC_POINT object).
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_set_public_key(EC_KEY *key, const EC_POINT *pub);
+
+OSSL_DEPRECATEDIN_3_0 unsigned EC_KEY_get_enc_flags(const EC_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_set_enc_flags(EC_KEY *eckey, unsigned int flags);
+OSSL_DEPRECATEDIN_3_0 point_conversion_form_t EC_KEY_get_conv_form(const EC_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_set_conv_form(EC_KEY *eckey,
+ point_conversion_form_t cform);
+# endif /*OPENSSL_NO_DEPRECATED_3_0 */
+
+# define EC_KEY_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_EC_KEY, l, p, newf, dupf, freef)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_set_ex_data(EC_KEY *key, int idx, void *arg);
+OSSL_DEPRECATEDIN_3_0 void *EC_KEY_get_ex_data(const EC_KEY *key, int idx);
+
+/* wrapper functions for the underlying EC_GROUP object */
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_set_asn1_flag(EC_KEY *eckey, int asn1_flag);
+
+/** Creates a table of pre-computed multiples of the generator to
+ * accelerate further EC_KEY operations.
+ * \param key EC_KEY object
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_precompute_mult(EC_KEY *key, BN_CTX *ctx);
+
+/** Creates a new ec private (and optional a new public) key.
+ * \param key EC_KEY object
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_generate_key(EC_KEY *key);
+
+/** Verifies that a private and/or public key is valid.
+ * \param key the EC_KEY object
+ * \return 1 on success and 0 otherwise.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_check_key(const EC_KEY *key);
+
+/** Indicates if an EC_KEY can be used for signing.
+ * \param eckey the EC_KEY object
+ * \return 1 if can can sign and 0 otherwise.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_can_sign(const EC_KEY *eckey);
+
+/** Sets a public key from affine coordinates performing
+ * necessary NIST PKV tests.
+ * \param key the EC_KEY object
+ * \param x public key x coordinate
+ * \param y public key y coordinate
+ * \return 1 on success and 0 otherwise.
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_set_public_key_affine_coordinates(EC_KEY *key,
+ BIGNUM *x,
+ BIGNUM *y);
+
+/** Encodes an EC_KEY public key to an allocated octet string
+ * \param key key to encode
+ * \param form point conversion form
+ * \param pbuf returns pointer to allocated buffer
+ * \param ctx BN_CTX object (optional)
+ * \return the length of the encoded octet string or 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 size_t EC_KEY_key2buf(const EC_KEY *key,
+ point_conversion_form_t form,
+ unsigned char **pbuf, BN_CTX *ctx);
+
+/** Decodes a EC_KEY public key from a octet string
+ * \param key key to decode
+ * \param buf memory buffer with the encoded ec point
+ * \param len length of the encoded ec point
+ * \param ctx BN_CTX object (optional)
+ * \return 1 on success and 0 if an error occurred
+ */
+
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_oct2key(EC_KEY *key, const unsigned char *buf,
+ size_t len, BN_CTX *ctx);
+
+/** Decodes an EC_KEY private key from an octet string
+ * \param key key to decode
+ * \param buf memory buffer with the encoded private key
+ * \param len length of the encoded key
+ * \return 1 on success and 0 if an error occurred
+ */
+
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_oct2priv(EC_KEY *key, const unsigned char *buf,
+ size_t len);
+
+/** Encodes a EC_KEY private key to an octet string
+ * \param key key to encode
+ * \param buf memory buffer for the result. If NULL the function returns
+ * required buffer size.
+ * \param len length of the memory buffer
+ * \return the length of the encoded octet string or 0 if an error occurred
+ */
+
+OSSL_DEPRECATEDIN_3_0 size_t EC_KEY_priv2oct(const EC_KEY *key,
+ unsigned char *buf, size_t len);
+
+/** Encodes an EC_KEY private key to an allocated octet string
+ * \param eckey key to encode
+ * \param pbuf returns pointer to allocated buffer
+ * \return the length of the encoded octet string or 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 size_t EC_KEY_priv2buf(const EC_KEY *eckey,
+ unsigned char **pbuf);
+
+/********************************************************************/
+/* de- and encoding functions for SEC1 ECPrivateKey */
+/********************************************************************/
+
+/** Decodes a private key from a memory buffer.
+ * \param key a pointer to a EC_KEY object which should be used (or NULL)
+ * \param in pointer to memory with the DER encoded private key
+ * \param len length of the DER encoded private key
+ * \return the decoded private key or NULL if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey(EC_KEY **key,
+ const unsigned char **in,
+ long len);
+
+/** Encodes a private key object and stores the result in a buffer.
+ * \param key the EC_KEY object to encode
+ * \param out the buffer for the result (if NULL the function returns number
+ * of bytes needed).
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey(const EC_KEY *key,
+ unsigned char **out);
+
+/********************************************************************/
+/* de- and encoding functions for EC parameters */
+/********************************************************************/
+
+/** Decodes ec parameter from a memory buffer.
+ * \param key a pointer to a EC_KEY object which should be used (or NULL)
+ * \param in pointer to memory with the DER encoded ec parameters
+ * \param len length of the DER encoded ec parameters
+ * \return a EC_KEY object with the decoded parameters or NULL if an error
+ * occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECParameters(EC_KEY **key,
+ const unsigned char **in,
+ long len);
+
+/** Encodes ec parameter and stores the result in a buffer.
+ * \param key the EC_KEY object with ec parameters to encode
+ * \param out the buffer for the result (if NULL the function returns number
+ * of bytes needed).
+ * \return 1 on success and 0 if an error occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 int i2d_ECParameters(const EC_KEY *key,
+ unsigned char **out);
+
+/********************************************************************/
+/* de- and encoding functions for EC public key */
+/* (octet string, not DER -- hence 'o2i' and 'i2o') */
+/********************************************************************/
+
+/** Decodes an ec public key from a octet string.
+ * \param key a pointer to a EC_KEY object which should be used
+ * \param in memory buffer with the encoded public key
+ * \param len length of the encoded public key
+ * \return EC_KEY object with decoded public key or NULL if an error
+ * occurred.
+ */
+OSSL_DEPRECATEDIN_3_0 EC_KEY *o2i_ECPublicKey(EC_KEY **key,
+ const unsigned char **in, long len);
+
+/** Encodes an ec public key in an octet string.
+ * \param key the EC_KEY object with the public key
+ * \param out the buffer for the result (if NULL the function returns number
+ * of bytes needed).
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int i2o_ECPublicKey(const EC_KEY *key, unsigned char **out);
+
+/** Prints out the ec parameters on human readable form.
+ * \param bp BIO object to which the information is printed
+ * \param key EC_KEY object
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int ECParameters_print(BIO *bp, const EC_KEY *key);
+
+/** Prints out the contents of a EC_KEY object
+ * \param bp BIO object to which the information is printed
+ * \param key EC_KEY object
+ * \param off line offset
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_print(BIO *bp, const EC_KEY *key, int off);
+
+# ifndef OPENSSL_NO_STDIO
+/** Prints out the ec parameters on human readable form.
+ * \param fp file descriptor to which the information is printed
+ * \param key EC_KEY object
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int ECParameters_print_fp(FILE *fp, const EC_KEY *key);
+
+/** Prints out the contents of a EC_KEY object
+ * \param fp file descriptor to which the information is printed
+ * \param key EC_KEY object
+ * \param off line offset
+ * \return 1 on success and 0 if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_print_fp(FILE *fp, const EC_KEY *key, int off);
+# endif /* OPENSSL_NO_STDIO */
+
+OSSL_DEPRECATEDIN_3_0 const EC_KEY_METHOD *EC_KEY_OpenSSL(void);
+OSSL_DEPRECATEDIN_3_0 const EC_KEY_METHOD *EC_KEY_get_default_method(void);
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_set_default_method(const EC_KEY_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 const EC_KEY_METHOD *EC_KEY_get_method(const EC_KEY *key);
+OSSL_DEPRECATEDIN_3_0 int EC_KEY_set_method(EC_KEY *key, const EC_KEY_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 EC_KEY *EC_KEY_new_method(ENGINE *engine);
+
+/** The old name for ecdh_KDF_X9_63
+ * The ECDH KDF specification has been mistakingly attributed to ANSI X9.62,
+ * it is actually specified in ANSI X9.63.
+ * This identifier is retained for backwards compatibility
+ */
+OSSL_DEPRECATEDIN_3_0 int ECDH_KDF_X9_62(unsigned char *out, size_t outlen,
+ const unsigned char *Z, size_t Zlen,
+ const unsigned char *sinfo,
+ size_t sinfolen, const EVP_MD *md);
+
+OSSL_DEPRECATEDIN_3_0 int ECDH_compute_key(void *out, size_t outlen,
+ const EC_POINT *pub_key,
+ const EC_KEY *ecdh,
+ void *(*KDF)(const void *in,
+ size_t inlen, void *out,
+ size_t *outlen));
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+typedef struct ECDSA_SIG_st ECDSA_SIG;
+
+/** Allocates and initialize a ECDSA_SIG structure
+ * \return pointer to a ECDSA_SIG structure or NULL if an error occurred
+ */
+ECDSA_SIG *ECDSA_SIG_new(void);
+
+/** frees a ECDSA_SIG structure
+ * \param sig pointer to the ECDSA_SIG structure
+ */
+void ECDSA_SIG_free(ECDSA_SIG *sig);
+
+/** i2d_ECDSA_SIG encodes content of ECDSA_SIG (note: this function modifies *pp
+ * (*pp += length of the DER encoded signature)).
+ * \param sig pointer to the ECDSA_SIG object
+ * \param pp pointer to a unsigned char pointer for the output or NULL
+ * \return the length of the DER encoded ECDSA_SIG object or a negative value
+ * on error
+ */
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(ECDSA_SIG, ECDSA_SIG)
+
+/** d2i_ECDSA_SIG decodes an ECDSA signature (note: this function modifies *pp
+ * (*pp += len)).
+ * \param sig pointer to ECDSA_SIG pointer (may be NULL)
+ * \param pp memory buffer with the DER encoded signature
+ * \param len length of the buffer
+ * \return pointer to the decoded ECDSA_SIG structure (or NULL)
+ */
+
+/** Accessor for r and s fields of ECDSA_SIG
+ * \param sig pointer to ECDSA_SIG structure
+ * \param pr pointer to BIGNUM pointer for r (may be NULL)
+ * \param ps pointer to BIGNUM pointer for s (may be NULL)
+ */
+void ECDSA_SIG_get0(const ECDSA_SIG *sig, const BIGNUM **pr, const BIGNUM **ps);
+
+/** Accessor for r field of ECDSA_SIG
+ * \param sig pointer to ECDSA_SIG structure
+ */
+const BIGNUM *ECDSA_SIG_get0_r(const ECDSA_SIG *sig);
+
+/** Accessor for s field of ECDSA_SIG
+ * \param sig pointer to ECDSA_SIG structure
+ */
+const BIGNUM *ECDSA_SIG_get0_s(const ECDSA_SIG *sig);
+
+/** Setter for r and s fields of ECDSA_SIG
+ * \param sig pointer to ECDSA_SIG structure
+ * \param r pointer to BIGNUM for r
+ * \param s pointer to BIGNUM for s
+ */
+int ECDSA_SIG_set0(ECDSA_SIG *sig, BIGNUM *r, BIGNUM *s);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/** Computes the ECDSA signature of the given hash value using
+ * the supplied private key and returns the created signature.
+ * \param dgst pointer to the hash value
+ * \param dgst_len length of the hash value
+ * \param eckey EC_KEY object containing a private EC key
+ * \return pointer to a ECDSA_SIG structure or NULL if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 ECDSA_SIG *ECDSA_do_sign(const unsigned char *dgst,
+ int dgst_len, EC_KEY *eckey);
+
+/** Computes ECDSA signature of a given hash value using the supplied
+ * private key (note: sig must point to ECDSA_size(eckey) bytes of memory).
+ * \param dgst pointer to the hash value to sign
+ * \param dgstlen length of the hash value
+ * \param kinv BIGNUM with a pre-computed inverse k (optional)
+ * \param rp BIGNUM with a pre-computed rp value (optional),
+ * see ECDSA_sign_setup
+ * \param eckey EC_KEY object containing a private EC key
+ * \return pointer to a ECDSA_SIG structure or NULL if an error occurred
+ */
+OSSL_DEPRECATEDIN_3_0 ECDSA_SIG *ECDSA_do_sign_ex(const unsigned char *dgst,
+ int dgstlen, const BIGNUM *kinv,
+ const BIGNUM *rp, EC_KEY *eckey);
+
+/** Verifies that the supplied signature is a valid ECDSA
+ * signature of the supplied hash value using the supplied public key.
+ * \param dgst pointer to the hash value
+ * \param dgst_len length of the hash value
+ * \param sig ECDSA_SIG structure
+ * \param eckey EC_KEY object containing a public EC key
+ * \return 1 if the signature is valid, 0 if the signature is invalid
+ * and -1 on error
+ */
+OSSL_DEPRECATEDIN_3_0 int ECDSA_do_verify(const unsigned char *dgst, int dgst_len,
+ const ECDSA_SIG *sig, EC_KEY *eckey);
+
+/** Precompute parts of the signing operation
+ * \param eckey EC_KEY object containing a private EC key
+ * \param ctx BN_CTX object (optional)
+ * \param kinv BIGNUM pointer for the inverse of k
+ * \param rp BIGNUM pointer for x coordinate of k * generator
+ * \return 1 on success and 0 otherwise
+ */
+OSSL_DEPRECATEDIN_3_0 int ECDSA_sign_setup(EC_KEY *eckey, BN_CTX *ctx,
+ BIGNUM **kinv, BIGNUM **rp);
+
+/** Computes ECDSA signature of a given hash value using the supplied
+ * private key (note: sig must point to ECDSA_size(eckey) bytes of memory).
+ * \param type this parameter is ignored
+ * \param dgst pointer to the hash value to sign
+ * \param dgstlen length of the hash value
+ * \param sig memory for the DER encoded created signature
+ * \param siglen pointer to the length of the returned signature
+ * \param eckey EC_KEY object containing a private EC key
+ * \return 1 on success and 0 otherwise
+ */
+OSSL_DEPRECATEDIN_3_0 int ECDSA_sign(int type, const unsigned char *dgst,
+ int dgstlen, unsigned char *sig,
+ unsigned int *siglen, EC_KEY *eckey);
+
+/** Computes ECDSA signature of a given hash value using the supplied
+ * private key (note: sig must point to ECDSA_size(eckey) bytes of memory).
+ * \param type this parameter is ignored
+ * \param dgst pointer to the hash value to sign
+ * \param dgstlen length of the hash value
+ * \param sig buffer to hold the DER encoded signature
+ * \param siglen pointer to the length of the returned signature
+ * \param kinv BIGNUM with a pre-computed inverse k (optional)
+ * \param rp BIGNUM with a pre-computed rp value (optional),
+ * see ECDSA_sign_setup
+ * \param eckey EC_KEY object containing a private EC key
+ * \return 1 on success and 0 otherwise
+ */
+OSSL_DEPRECATEDIN_3_0 int ECDSA_sign_ex(int type, const unsigned char *dgst,
+ int dgstlen, unsigned char *sig,
+ unsigned int *siglen, const BIGNUM *kinv,
+ const BIGNUM *rp, EC_KEY *eckey);
+
+/** Verifies that the given signature is valid ECDSA signature
+ * of the supplied hash value using the specified public key.
+ * \param type this parameter is ignored
+ * \param dgst pointer to the hash value
+ * \param dgstlen length of the hash value
+ * \param sig pointer to the DER encoded signature
+ * \param siglen length of the DER encoded signature
+ * \param eckey EC_KEY object containing a public EC key
+ * \return 1 if the signature is valid, 0 if the signature is invalid
+ * and -1 on error
+ */
+OSSL_DEPRECATEDIN_3_0 int ECDSA_verify(int type, const unsigned char *dgst,
+ int dgstlen, const unsigned char *sig,
+ int siglen, EC_KEY *eckey);
+
+/** Returns the maximum length of the DER encoded signature
+ * \param eckey EC_KEY object
+ * \return numbers of bytes required for the DER encoded signature
+ */
+OSSL_DEPRECATEDIN_3_0 int ECDSA_size(const EC_KEY *eckey);
+
+/********************************************************************/
+/* EC_KEY_METHOD constructors, destructors, writers and accessors */
+/********************************************************************/
+
+OSSL_DEPRECATEDIN_3_0 EC_KEY_METHOD *EC_KEY_METHOD_new(const EC_KEY_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_free(EC_KEY_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_set_init
+ (EC_KEY_METHOD *meth,
+ int (*init)(EC_KEY *key),
+ void (*finish)(EC_KEY *key),
+ int (*copy)(EC_KEY *dest, const EC_KEY *src),
+ int (*set_group)(EC_KEY *key, const EC_GROUP *grp),
+ int (*set_private)(EC_KEY *key, const BIGNUM *priv_key),
+ int (*set_public)(EC_KEY *key, const EC_POINT *pub_key));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_set_keygen(EC_KEY_METHOD *meth,
+ int (*keygen)(EC_KEY *key));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_set_compute_key
+ (EC_KEY_METHOD *meth,
+ int (*ckey)(unsigned char **psec, size_t *pseclen,
+ const EC_POINT *pub_key, const EC_KEY *ecdh));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_set_sign
+ (EC_KEY_METHOD *meth,
+ int (*sign)(int type, const unsigned char *dgst,
+ int dlen, unsigned char *sig,
+ unsigned int *siglen,
+ const BIGNUM *kinv, const BIGNUM *r,
+ EC_KEY *eckey),
+ int (*sign_setup)(EC_KEY *eckey, BN_CTX *ctx_in,
+ BIGNUM **kinvp, BIGNUM **rp),
+ ECDSA_SIG *(*sign_sig)(const unsigned char *dgst,
+ int dgst_len,
+ const BIGNUM *in_kinv,
+ const BIGNUM *in_r,
+ EC_KEY *eckey));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_set_verify
+ (EC_KEY_METHOD *meth,
+ int (*verify)(int type, const unsigned
+ char *dgst, int dgst_len,
+ const unsigned char *sigbuf,
+ int sig_len, EC_KEY *eckey),
+ int (*verify_sig)(const unsigned char *dgst,
+ int dgst_len, const ECDSA_SIG *sig,
+ EC_KEY *eckey));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_get_init
+ (const EC_KEY_METHOD *meth,
+ int (**pinit)(EC_KEY *key),
+ void (**pfinish)(EC_KEY *key),
+ int (**pcopy)(EC_KEY *dest, const EC_KEY *src),
+ int (**pset_group)(EC_KEY *key, const EC_GROUP *grp),
+ int (**pset_private)(EC_KEY *key, const BIGNUM *priv_key),
+ int (**pset_public)(EC_KEY *key, const EC_POINT *pub_key));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_get_keygen
+ (const EC_KEY_METHOD *meth, int (**pkeygen)(EC_KEY *key));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_get_compute_key
+ (const EC_KEY_METHOD *meth,
+ int (**pck)(unsigned char **psec,
+ size_t *pseclen,
+ const EC_POINT *pub_key,
+ const EC_KEY *ecdh));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_get_sign
+ (const EC_KEY_METHOD *meth,
+ int (**psign)(int type, const unsigned char *dgst,
+ int dlen, unsigned char *sig,
+ unsigned int *siglen,
+ const BIGNUM *kinv, const BIGNUM *r,
+ EC_KEY *eckey),
+ int (**psign_setup)(EC_KEY *eckey, BN_CTX *ctx_in,
+ BIGNUM **kinvp, BIGNUM **rp),
+ ECDSA_SIG *(**psign_sig)(const unsigned char *dgst,
+ int dgst_len,
+ const BIGNUM *in_kinv,
+ const BIGNUM *in_r,
+ EC_KEY *eckey));
+
+OSSL_DEPRECATEDIN_3_0 void EC_KEY_METHOD_get_verify
+ (const EC_KEY_METHOD *meth,
+ int (**pverify)(int type, const unsigned
+ char *dgst, int dgst_len,
+ const unsigned char *sigbuf,
+ int sig_len, EC_KEY *eckey),
+ int (**pverify_sig)(const unsigned char *dgst,
+ int dgst_len,
+ const ECDSA_SIG *sig,
+ EC_KEY *eckey));
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+# define EVP_EC_gen(curve) \
+ EVP_PKEY_Q_keygen(NULL, NULL, "EC", (char *)(strstr(curve, "")))
+# define ECParameters_dup(x) ASN1_dup_of(EC_KEY, i2d_ECParameters, \
+ d2i_ECParameters, x)
+
+# ifndef __cplusplus
+# if defined(__SUNPRO_C)
+# if __SUNPRO_C >= 0x520
+# pragma error_messages (default,E_ARRAY_OF_INCOMPLETE_NONAME,E_ARRAY_OF_INCOMPLETE)
+# endif
+# endif
+# endif
+
+# endif
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/ecdh.h b/include/openssl/ecdh.h
new file mode 100644
index 00000000..56bd4cc2
--- /dev/null
+++ b/include/openssl/ecdh.h
@@ -0,0 +1,10 @@
+/*
+ * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <openssl/ec.h>
diff --git a/include/openssl/ecdsa.h b/include/openssl/ecdsa.h
new file mode 100644
index 00000000..56bd4cc2
--- /dev/null
+++ b/include/openssl/ecdsa.h
@@ -0,0 +1,10 @@
+/*
+ * Copyright 2002-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#include <openssl/ec.h>
diff --git a/include/openssl/ecerr.h b/include/openssl/ecerr.h
new file mode 100644
index 00000000..49088d20
--- /dev/null
+++ b/include/openssl/ecerr.h
@@ -0,0 +1,102 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ECERR_H
+# define OPENSSL_ECERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_EC
+
+
+/*
+ * EC reason codes.
+ */
+# define EC_R_ASN1_ERROR 115
+# define EC_R_BAD_SIGNATURE 156
+# define EC_R_BIGNUM_OUT_OF_RANGE 144
+# define EC_R_BUFFER_TOO_SMALL 100
+# define EC_R_CANNOT_INVERT 165
+# define EC_R_COORDINATES_OUT_OF_RANGE 146
+# define EC_R_CURVE_DOES_NOT_SUPPORT_ECDH 160
+# define EC_R_CURVE_DOES_NOT_SUPPORT_ECDSA 170
+# define EC_R_CURVE_DOES_NOT_SUPPORT_SIGNING 159
+# define EC_R_DECODE_ERROR 142
+# define EC_R_DISCRIMINANT_IS_ZERO 118
+# define EC_R_EC_GROUP_NEW_BY_NAME_FAILURE 119
+# define EC_R_FAILED_MAKING_PUBLIC_KEY 166
+# define EC_R_FIELD_TOO_LARGE 143
+# define EC_R_GF2M_NOT_SUPPORTED 147
+# define EC_R_GROUP2PKPARAMETERS_FAILURE 120
+# define EC_R_I2D_ECPKPARAMETERS_FAILURE 121
+# define EC_R_INCOMPATIBLE_OBJECTS 101
+# define EC_R_INVALID_A 168
+# define EC_R_INVALID_ARGUMENT 112
+# define EC_R_INVALID_B 169
+# define EC_R_INVALID_COFACTOR 171
+# define EC_R_INVALID_COMPRESSED_POINT 110
+# define EC_R_INVALID_COMPRESSION_BIT 109
+# define EC_R_INVALID_CURVE 141
+# define EC_R_INVALID_DIGEST 151
+# define EC_R_INVALID_DIGEST_TYPE 138
+# define EC_R_INVALID_ENCODING 102
+# define EC_R_INVALID_FIELD 103
+# define EC_R_INVALID_FORM 104
+# define EC_R_INVALID_GENERATOR 173
+# define EC_R_INVALID_GROUP_ORDER 122
+# define EC_R_INVALID_KEY 116
+# define EC_R_INVALID_LENGTH 117
+# define EC_R_INVALID_NAMED_GROUP_CONVERSION 174
+# define EC_R_INVALID_OUTPUT_LENGTH 161
+# define EC_R_INVALID_P 172
+# define EC_R_INVALID_PEER_KEY 133
+# define EC_R_INVALID_PENTANOMIAL_BASIS 132
+# define EC_R_INVALID_PRIVATE_KEY 123
+# define EC_R_INVALID_SEED 175
+# define EC_R_INVALID_TRINOMIAL_BASIS 137
+# define EC_R_KDF_PARAMETER_ERROR 148
+# define EC_R_KEYS_NOT_SET 140
+# define EC_R_LADDER_POST_FAILURE 136
+# define EC_R_LADDER_PRE_FAILURE 153
+# define EC_R_LADDER_STEP_FAILURE 162
+# define EC_R_MISSING_OID 167
+# define EC_R_MISSING_PARAMETERS 124
+# define EC_R_MISSING_PRIVATE_KEY 125
+# define EC_R_NEED_NEW_SETUP_VALUES 157
+# define EC_R_NOT_A_NIST_PRIME 135
+# define EC_R_NOT_IMPLEMENTED 126
+# define EC_R_NOT_INITIALIZED 111
+# define EC_R_NO_PARAMETERS_SET 139
+# define EC_R_NO_PRIVATE_VALUE 154
+# define EC_R_OPERATION_NOT_SUPPORTED 152
+# define EC_R_PASSED_NULL_PARAMETER 134
+# define EC_R_PEER_KEY_ERROR 149
+# define EC_R_POINT_ARITHMETIC_FAILURE 155
+# define EC_R_POINT_AT_INFINITY 106
+# define EC_R_POINT_COORDINATES_BLIND_FAILURE 163
+# define EC_R_POINT_IS_NOT_ON_CURVE 107
+# define EC_R_RANDOM_NUMBER_GENERATION_FAILED 158
+# define EC_R_SHARED_INFO_ERROR 150
+# define EC_R_SLOT_FULL 108
+# define EC_R_UNDEFINED_GENERATOR 113
+# define EC_R_UNDEFINED_ORDER 128
+# define EC_R_UNKNOWN_COFACTOR 164
+# define EC_R_UNKNOWN_GROUP 129
+# define EC_R_UNKNOWN_ORDER 114
+# define EC_R_UNSUPPORTED_FIELD 131
+# define EC_R_WRONG_CURVE_PARAMETERS 145
+# define EC_R_WRONG_ORDER 130
+
+# endif
+#endif
diff --git a/include/openssl/encoder.h b/include/openssl/encoder.h
new file mode 100644
index 00000000..c37a6f16
--- /dev/null
+++ b/include/openssl/encoder.h
@@ -0,0 +1,124 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ENCODER_H
+# define OPENSSL_ENCODER_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+# include <stdarg.h>
+# include <stddef.h>
+# include <openssl/encodererr.h>
+# include <openssl/types.h>
+# include <openssl/core.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+OSSL_ENCODER *OSSL_ENCODER_fetch(OSSL_LIB_CTX *libctx, const char *name,
+ const char *properties);
+int OSSL_ENCODER_up_ref(OSSL_ENCODER *encoder);
+void OSSL_ENCODER_free(OSSL_ENCODER *encoder);
+
+const OSSL_PROVIDER *OSSL_ENCODER_get0_provider(const OSSL_ENCODER *encoder);
+const char *OSSL_ENCODER_get0_properties(const OSSL_ENCODER *encoder);
+const char *OSSL_ENCODER_get0_name(const OSSL_ENCODER *kdf);
+const char *OSSL_ENCODER_get0_description(const OSSL_ENCODER *kdf);
+int OSSL_ENCODER_is_a(const OSSL_ENCODER *encoder, const char *name);
+
+void OSSL_ENCODER_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(OSSL_ENCODER *encoder, void *arg),
+ void *arg);
+int OSSL_ENCODER_names_do_all(const OSSL_ENCODER *encoder,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PARAM *OSSL_ENCODER_gettable_params(OSSL_ENCODER *encoder);
+int OSSL_ENCODER_get_params(OSSL_ENCODER *encoder, OSSL_PARAM params[]);
+
+const OSSL_PARAM *OSSL_ENCODER_settable_ctx_params(OSSL_ENCODER *encoder);
+OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new(void);
+int OSSL_ENCODER_CTX_set_params(OSSL_ENCODER_CTX *ctx,
+ const OSSL_PARAM params[]);
+void OSSL_ENCODER_CTX_free(OSSL_ENCODER_CTX *ctx);
+
+/* Utilities that help set specific parameters */
+int OSSL_ENCODER_CTX_set_passphrase(OSSL_ENCODER_CTX *ctx,
+ const unsigned char *kstr, size_t klen);
+int OSSL_ENCODER_CTX_set_pem_password_cb(OSSL_ENCODER_CTX *ctx,
+ pem_password_cb *cb, void *cbarg);
+int OSSL_ENCODER_CTX_set_passphrase_cb(OSSL_ENCODER_CTX *ctx,
+ OSSL_PASSPHRASE_CALLBACK *cb,
+ void *cbarg);
+int OSSL_ENCODER_CTX_set_passphrase_ui(OSSL_ENCODER_CTX *ctx,
+ const UI_METHOD *ui_method,
+ void *ui_data);
+int OSSL_ENCODER_CTX_set_cipher(OSSL_ENCODER_CTX *ctx,
+ const char *cipher_name,
+ const char *propquery);
+int OSSL_ENCODER_CTX_set_selection(OSSL_ENCODER_CTX *ctx, int selection);
+int OSSL_ENCODER_CTX_set_output_type(OSSL_ENCODER_CTX *ctx,
+ const char *output_type);
+int OSSL_ENCODER_CTX_set_output_structure(OSSL_ENCODER_CTX *ctx,
+ const char *output_structure);
+
+/* Utilities to add encoders */
+int OSSL_ENCODER_CTX_add_encoder(OSSL_ENCODER_CTX *ctx, OSSL_ENCODER *encoder);
+int OSSL_ENCODER_CTX_add_extra(OSSL_ENCODER_CTX *ctx,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int OSSL_ENCODER_CTX_get_num_encoders(OSSL_ENCODER_CTX *ctx);
+
+typedef struct ossl_encoder_instance_st OSSL_ENCODER_INSTANCE;
+OSSL_ENCODER *
+OSSL_ENCODER_INSTANCE_get_encoder(OSSL_ENCODER_INSTANCE *encoder_inst);
+void *
+OSSL_ENCODER_INSTANCE_get_encoder_ctx(OSSL_ENCODER_INSTANCE *encoder_inst);
+const char *
+OSSL_ENCODER_INSTANCE_get_output_type(OSSL_ENCODER_INSTANCE *encoder_inst);
+const char *
+OSSL_ENCODER_INSTANCE_get_output_structure(OSSL_ENCODER_INSTANCE *encoder_inst);
+
+typedef const void *OSSL_ENCODER_CONSTRUCT(OSSL_ENCODER_INSTANCE *encoder_inst,
+ void *construct_data);
+typedef void OSSL_ENCODER_CLEANUP(void *construct_data);
+
+int OSSL_ENCODER_CTX_set_construct(OSSL_ENCODER_CTX *ctx,
+ OSSL_ENCODER_CONSTRUCT *construct);
+int OSSL_ENCODER_CTX_set_construct_data(OSSL_ENCODER_CTX *ctx,
+ void *construct_data);
+int OSSL_ENCODER_CTX_set_cleanup(OSSL_ENCODER_CTX *ctx,
+ OSSL_ENCODER_CLEANUP *cleanup);
+
+/* Utilities to output the object to encode */
+int OSSL_ENCODER_to_bio(OSSL_ENCODER_CTX *ctx, BIO *out);
+#ifndef OPENSSL_NO_STDIO
+int OSSL_ENCODER_to_fp(OSSL_ENCODER_CTX *ctx, FILE *fp);
+#endif
+int OSSL_ENCODER_to_data(OSSL_ENCODER_CTX *ctx, unsigned char **pdata,
+ size_t *pdata_len);
+
+/*
+ * Create the OSSL_ENCODER_CTX with an associated type. This will perform
+ * an implicit OSSL_ENCODER_fetch(), suitable for the object of that type.
+ * This is more useful than calling OSSL_ENCODER_CTX_new().
+ */
+OSSL_ENCODER_CTX *OSSL_ENCODER_CTX_new_for_pkey(const EVP_PKEY *pkey,
+ int selection,
+ const char *output_type,
+ const char *output_struct,
+ const char *propquery);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/encodererr.h b/include/openssl/encodererr.h
new file mode 100644
index 00000000..5e318b14
--- /dev/null
+++ b/include/openssl/encodererr.h
@@ -0,0 +1,28 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ENCODERERR_H
+# define OPENSSL_ENCODERERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * OSSL_ENCODER reason codes.
+ */
+# define OSSL_ENCODER_R_ENCODER_NOT_FOUND 101
+# define OSSL_ENCODER_R_INCORRECT_PROPERTY_QUERY 100
+# define OSSL_ENCODER_R_MISSING_GET_PARAMS 102
+
+#endif
diff --git a/include/openssl/engine.h b/include/openssl/engine.h
new file mode 100644
index 00000000..25c3cf7c
--- /dev/null
+++ b/include/openssl/engine.h
@@ -0,0 +1,832 @@
+/*
+ * Copyright 2000-2020 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ENGINE_H
+# define OPENSSL_ENGINE_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ENGINE_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_ENGINE
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/bn.h>
+# include <openssl/rsa.h>
+# include <openssl/dsa.h>
+# include <openssl/dh.h>
+# include <openssl/ec.h>
+# include <openssl/rand.h>
+# include <openssl/ui.h>
+# include <openssl/err.h>
+# endif
+# include <openssl/types.h>
+# include <openssl/symhacks.h>
+# include <openssl/x509.h>
+# include <openssl/engineerr.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * These flags are used to control combinations of algorithm (methods) by
+ * bitwise "OR"ing.
+ */
+# define ENGINE_METHOD_RSA (unsigned int)0x0001
+# define ENGINE_METHOD_DSA (unsigned int)0x0002
+# define ENGINE_METHOD_DH (unsigned int)0x0004
+# define ENGINE_METHOD_RAND (unsigned int)0x0008
+# define ENGINE_METHOD_CIPHERS (unsigned int)0x0040
+# define ENGINE_METHOD_DIGESTS (unsigned int)0x0080
+# define ENGINE_METHOD_PKEY_METHS (unsigned int)0x0200
+# define ENGINE_METHOD_PKEY_ASN1_METHS (unsigned int)0x0400
+# define ENGINE_METHOD_EC (unsigned int)0x0800
+/* Obvious all-or-nothing cases. */
+# define ENGINE_METHOD_ALL (unsigned int)0xFFFF
+# define ENGINE_METHOD_NONE (unsigned int)0x0000
+
+/*
+ * This(ese) flag(s) controls behaviour of the ENGINE_TABLE mechanism used
+ * internally to control registration of ENGINE implementations, and can be
+ * set by ENGINE_set_table_flags(). The "NOINIT" flag prevents attempts to
+ * initialise registered ENGINEs if they are not already initialised.
+ */
+# define ENGINE_TABLE_FLAG_NOINIT (unsigned int)0x0001
+
+/* ENGINE flags that can be set by ENGINE_set_flags(). */
+/* Not used */
+/* #define ENGINE_FLAGS_MALLOCED 0x0001 */
+
+/*
+ * This flag is for ENGINEs that wish to handle the various 'CMD'-related
+ * control commands on their own. Without this flag, ENGINE_ctrl() handles
+ * these control commands on behalf of the ENGINE using their "cmd_defns"
+ * data.
+ */
+# define ENGINE_FLAGS_MANUAL_CMD_CTRL (int)0x0002
+
+/*
+ * This flag is for ENGINEs who return new duplicate structures when found
+ * via "ENGINE_by_id()". When an ENGINE must store state (eg. if
+ * ENGINE_ctrl() commands are called in sequence as part of some stateful
+ * process like key-generation setup and execution), it can set this flag -
+ * then each attempt to obtain the ENGINE will result in it being copied into
+ * a new structure. Normally, ENGINEs don't declare this flag so
+ * ENGINE_by_id() just increments the existing ENGINE's structural reference
+ * count.
+ */
+# define ENGINE_FLAGS_BY_ID_COPY (int)0x0004
+
+/*
+ * This flag if for an ENGINE that does not want its methods registered as
+ * part of ENGINE_register_all_complete() for example if the methods are not
+ * usable as default methods.
+ */
+
+# define ENGINE_FLAGS_NO_REGISTER_ALL (int)0x0008
+
+/*
+ * ENGINEs can support their own command types, and these flags are used in
+ * ENGINE_CTRL_GET_CMD_FLAGS to indicate to the caller what kind of input
+ * each command expects. Currently only numeric and string input is
+ * supported. If a control command supports none of the _NUMERIC, _STRING, or
+ * _NO_INPUT options, then it is regarded as an "internal" control command -
+ * and not for use in config setting situations. As such, they're not
+ * available to the ENGINE_ctrl_cmd_string() function, only raw ENGINE_ctrl()
+ * access. Changes to this list of 'command types' should be reflected
+ * carefully in ENGINE_cmd_is_executable() and ENGINE_ctrl_cmd_string().
+ */
+
+/* accepts a 'long' input value (3rd parameter to ENGINE_ctrl) */
+# define ENGINE_CMD_FLAG_NUMERIC (unsigned int)0x0001
+/*
+ * accepts string input (cast from 'void*' to 'const char *', 4th parameter
+ * to ENGINE_ctrl)
+ */
+# define ENGINE_CMD_FLAG_STRING (unsigned int)0x0002
+/*
+ * Indicates that the control command takes *no* input. Ie. the control
+ * command is unparameterised.
+ */
+# define ENGINE_CMD_FLAG_NO_INPUT (unsigned int)0x0004
+/*
+ * Indicates that the control command is internal. This control command won't
+ * be shown in any output, and is only usable through the ENGINE_ctrl_cmd()
+ * function.
+ */
+# define ENGINE_CMD_FLAG_INTERNAL (unsigned int)0x0008
+
+/*
+ * NB: These 3 control commands are deprecated and should not be used.
+ * ENGINEs relying on these commands should compile conditional support for
+ * compatibility (eg. if these symbols are defined) but should also migrate
+ * the same functionality to their own ENGINE-specific control functions that
+ * can be "discovered" by calling applications. The fact these control
+ * commands wouldn't be "executable" (ie. usable by text-based config)
+ * doesn't change the fact that application code can find and use them
+ * without requiring per-ENGINE hacking.
+ */
+
+/*
+ * These flags are used to tell the ctrl function what should be done. All
+ * command numbers are shared between all engines, even if some don't make
+ * sense to some engines. In such a case, they do nothing but return the
+ * error ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED.
+ */
+# define ENGINE_CTRL_SET_LOGSTREAM 1
+# define ENGINE_CTRL_SET_PASSWORD_CALLBACK 2
+# define ENGINE_CTRL_HUP 3/* Close and reinitialise
+ * any handles/connections
+ * etc. */
+# define ENGINE_CTRL_SET_USER_INTERFACE 4/* Alternative to callback */
+# define ENGINE_CTRL_SET_CALLBACK_DATA 5/* User-specific data, used
+ * when calling the password
+ * callback and the user
+ * interface */
+# define ENGINE_CTRL_LOAD_CONFIGURATION 6/* Load a configuration,
+ * given a string that
+ * represents a file name
+ * or so */
+# define ENGINE_CTRL_LOAD_SECTION 7/* Load data from a given
+ * section in the already
+ * loaded configuration */
+
+/*
+ * These control commands allow an application to deal with an arbitrary
+ * engine in a dynamic way. Warn: Negative return values indicate errors FOR
+ * THESE COMMANDS because zero is used to indicate 'end-of-list'. Other
+ * commands, including ENGINE-specific command types, return zero for an
+ * error. An ENGINE can choose to implement these ctrl functions, and can
+ * internally manage things however it chooses - it does so by setting the
+ * ENGINE_FLAGS_MANUAL_CMD_CTRL flag (using ENGINE_set_flags()). Otherwise
+ * the ENGINE_ctrl() code handles this on the ENGINE's behalf using the
+ * cmd_defns data (set using ENGINE_set_cmd_defns()). This means an ENGINE's
+ * ctrl() handler need only implement its own commands - the above "meta"
+ * commands will be taken care of.
+ */
+
+/*
+ * Returns non-zero if the supplied ENGINE has a ctrl() handler. If "not",
+ * then all the remaining control commands will return failure, so it is
+ * worth checking this first if the caller is trying to "discover" the
+ * engine's capabilities and doesn't want errors generated unnecessarily.
+ */
+# define ENGINE_CTRL_HAS_CTRL_FUNCTION 10
+/*
+ * Returns a positive command number for the first command supported by the
+ * engine. Returns zero if no ctrl commands are supported.
+ */
+# define ENGINE_CTRL_GET_FIRST_CMD_TYPE 11
+/*
+ * The 'long' argument specifies a command implemented by the engine, and the
+ * return value is the next command supported, or zero if there are no more.
+ */
+# define ENGINE_CTRL_GET_NEXT_CMD_TYPE 12
+/*
+ * The 'void*' argument is a command name (cast from 'const char *'), and the
+ * return value is the command that corresponds to it.
+ */
+# define ENGINE_CTRL_GET_CMD_FROM_NAME 13
+/*
+ * The next two allow a command to be converted into its corresponding string
+ * form. In each case, the 'long' argument supplies the command. In the
+ * NAME_LEN case, the return value is the length of the command name (not
+ * counting a trailing EOL). In the NAME case, the 'void*' argument must be a
+ * string buffer large enough, and it will be populated with the name of the
+ * command (WITH a trailing EOL).
+ */
+# define ENGINE_CTRL_GET_NAME_LEN_FROM_CMD 14
+# define ENGINE_CTRL_GET_NAME_FROM_CMD 15
+/* The next two are similar but give a "short description" of a command. */
+# define ENGINE_CTRL_GET_DESC_LEN_FROM_CMD 16
+# define ENGINE_CTRL_GET_DESC_FROM_CMD 17
+/*
+ * With this command, the return value is the OR'd combination of
+ * ENGINE_CMD_FLAG_*** values that indicate what kind of input a given
+ * engine-specific ctrl command expects.
+ */
+# define ENGINE_CTRL_GET_CMD_FLAGS 18
+
+/*
+ * ENGINE implementations should start the numbering of their own control
+ * commands from this value. (ie. ENGINE_CMD_BASE, ENGINE_CMD_BASE + 1, etc).
+ */
+# define ENGINE_CMD_BASE 200
+
+/*
+ * NB: These 2 nCipher "chil" control commands are deprecated, and their
+ * functionality is now available through ENGINE-specific control commands
+ * (exposed through the above-mentioned 'CMD'-handling). Code using these 2
+ * commands should be migrated to the more general command handling before
+ * these are removed.
+ */
+
+/* Flags specific to the nCipher "chil" engine */
+# define ENGINE_CTRL_CHIL_SET_FORKCHECK 100
+ /*
+ * Depending on the value of the (long)i argument, this sets or
+ * unsets the SimpleForkCheck flag in the CHIL API to enable or
+ * disable checking and workarounds for applications that fork().
+ */
+# define ENGINE_CTRL_CHIL_NO_LOCKING 101
+ /*
+ * This prevents the initialisation function from providing mutex
+ * callbacks to the nCipher library.
+ */
+
+/*
+ * If an ENGINE supports its own specific control commands and wishes the
+ * framework to handle the above 'ENGINE_CMD_***'-manipulation commands on
+ * its behalf, it should supply a null-terminated array of ENGINE_CMD_DEFN
+ * entries to ENGINE_set_cmd_defns(). It should also implement a ctrl()
+ * handler that supports the stated commands (ie. the "cmd_num" entries as
+ * described by the array). NB: The array must be ordered in increasing order
+ * of cmd_num. "null-terminated" means that the last ENGINE_CMD_DEFN element
+ * has cmd_num set to zero and/or cmd_name set to NULL.
+ */
+typedef struct ENGINE_CMD_DEFN_st {
+ unsigned int cmd_num; /* The command number */
+ const char *cmd_name; /* The command name itself */
+ const char *cmd_desc; /* A short description of the command */
+ unsigned int cmd_flags; /* The input the command expects */
+} ENGINE_CMD_DEFN;
+
+/* Generic function pointer */
+typedef int (*ENGINE_GEN_FUNC_PTR) (void);
+/* Generic function pointer taking no arguments */
+typedef int (*ENGINE_GEN_INT_FUNC_PTR) (ENGINE *);
+/* Specific control function pointer */
+typedef int (*ENGINE_CTRL_FUNC_PTR) (ENGINE *, int, long, void *,
+ void (*f) (void));
+/* Generic load_key function pointer */
+typedef EVP_PKEY *(*ENGINE_LOAD_KEY_PTR)(ENGINE *, const char *,
+ UI_METHOD *ui_method,
+ void *callback_data);
+typedef int (*ENGINE_SSL_CLIENT_CERT_PTR) (ENGINE *, SSL *ssl,
+ STACK_OF(X509_NAME) *ca_dn,
+ X509 **pcert, EVP_PKEY **pkey,
+ STACK_OF(X509) **pother,
+ UI_METHOD *ui_method,
+ void *callback_data);
+/*-
+ * These callback types are for an ENGINE's handler for cipher and digest logic.
+ * These handlers have these prototypes;
+ * int foo(ENGINE *e, const EVP_CIPHER **cipher, const int **nids, int nid);
+ * int foo(ENGINE *e, const EVP_MD **digest, const int **nids, int nid);
+ * Looking at how to implement these handlers in the case of cipher support, if
+ * the framework wants the EVP_CIPHER for 'nid', it will call;
+ * foo(e, &p_evp_cipher, NULL, nid); (return zero for failure)
+ * If the framework wants a list of supported 'nid's, it will call;
+ * foo(e, NULL, &p_nids, 0); (returns number of 'nids' or -1 for error)
+ */
+/*
+ * Returns to a pointer to the array of supported cipher 'nid's. If the
+ * second parameter is non-NULL it is set to the size of the returned array.
+ */
+typedef int (*ENGINE_CIPHERS_PTR) (ENGINE *, const EVP_CIPHER **,
+ const int **, int);
+typedef int (*ENGINE_DIGESTS_PTR) (ENGINE *, const EVP_MD **, const int **,
+ int);
+typedef int (*ENGINE_PKEY_METHS_PTR) (ENGINE *, EVP_PKEY_METHOD **,
+ const int **, int);
+typedef int (*ENGINE_PKEY_ASN1_METHS_PTR) (ENGINE *, EVP_PKEY_ASN1_METHOD **,
+ const int **, int);
+/*
+ * STRUCTURE functions ... all of these functions deal with pointers to
+ * ENGINE structures where the pointers have a "structural reference". This
+ * means that their reference is to allowed access to the structure but it
+ * does not imply that the structure is functional. To simply increment or
+ * decrement the structural reference count, use ENGINE_by_id and
+ * ENGINE_free. NB: This is not required when iterating using ENGINE_get_next
+ * as it will automatically decrement the structural reference count of the
+ * "current" ENGINE and increment the structural reference count of the
+ * ENGINE it returns (unless it is NULL).
+ */
+
+/* Get the first/last "ENGINE" type available. */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_first(void);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_last(void);
+# endif
+/* Iterate to the next/previous "ENGINE" type (NULL = end of the list). */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_next(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_prev(ENGINE *e);
+# endif
+/* Add another "ENGINE" type into the array. */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_add(ENGINE *e);
+# endif
+/* Remove an existing "ENGINE" type from the array. */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_remove(ENGINE *e);
+# endif
+/* Retrieve an engine from the list by its unique "id" value. */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_by_id(const char *id);
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define ENGINE_load_openssl() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_OPENSSL, NULL)
+# define ENGINE_load_dynamic() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_DYNAMIC, NULL)
+# ifndef OPENSSL_NO_STATIC_ENGINE
+# define ENGINE_load_padlock() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_PADLOCK, NULL)
+# define ENGINE_load_capi() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_CAPI, NULL)
+# define ENGINE_load_afalg() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_AFALG, NULL)
+# endif
+# define ENGINE_load_cryptodev() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_CRYPTODEV, NULL)
+# define ENGINE_load_rdrand() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ENGINE_RDRAND, NULL)
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void ENGINE_load_builtin_engines(void);
+# endif
+
+/*
+ * Get and set global flags (ENGINE_TABLE_FLAG_***) for the implementation
+ * "registry" handling.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 unsigned int ENGINE_get_table_flags(void);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_set_table_flags(unsigned int flags);
+# endif
+
+/*- Manage registration of ENGINEs per "table". For each type, there are 3
+ * functions;
+ * ENGINE_register_***(e) - registers the implementation from 'e' (if it has one)
+ * ENGINE_unregister_***(e) - unregister the implementation from 'e'
+ * ENGINE_register_all_***() - call ENGINE_register_***() for each 'e' in the list
+ * Cleanup is automatically registered from each table when required.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_RSA(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_RSA(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_RSA(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_DSA(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_DSA(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_DSA(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_EC(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_EC(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_EC(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_DH(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_DH(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_DH(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_RAND(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_RAND(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_RAND(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_ciphers(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_ciphers(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_ciphers(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_digests(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_digests(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_digests(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_pkey_meths(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_pkey_meths(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_pkey_meths(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_pkey_asn1_meths(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_unregister_pkey_asn1_meths(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_register_all_pkey_asn1_meths(void);
+# endif
+
+/*
+ * These functions register all support from the above categories. Note, use
+ * of these functions can result in static linkage of code your application
+ * may not need. If you only need a subset of functionality, consider using
+ * more selective initialisation.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_complete(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_register_all_complete(void);
+# endif
+
+/*
+ * Send parameterised control commands to the engine. The possibilities to
+ * send down an integer, a pointer to data or a function pointer are
+ * provided. Any of the parameters may or may not be NULL, depending on the
+ * command number. In actuality, this function only requires a structural
+ * (rather than functional) reference to an engine, but many control commands
+ * may require the engine be functional. The caller should be aware of trying
+ * commands that require an operational ENGINE, and only use functional
+ * references in such situations.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_ctrl(ENGINE *e, int cmd, long i, void *p,
+ void (*f) (void));
+# endif
+
+/*
+ * This function tests if an ENGINE-specific command is usable as a
+ * "setting". Eg. in an application's config file that gets processed through
+ * ENGINE_ctrl_cmd_string(). If this returns zero, it is not available to
+ * ENGINE_ctrl_cmd_string(), only ENGINE_ctrl().
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_cmd_is_executable(ENGINE *e, int cmd);
+# endif
+
+/*
+ * This function works like ENGINE_ctrl() with the exception of taking a
+ * command name instead of a command number, and can handle optional
+ * commands. See the comment on ENGINE_ctrl_cmd_string() for an explanation
+ * on how to use the cmd_name and cmd_optional.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_ctrl_cmd(ENGINE *e, const char *cmd_name,
+ long i, void *p, void (*f) (void),
+ int cmd_optional);
+# endif
+
+/*
+ * This function passes a command-name and argument to an ENGINE. The
+ * cmd_name is converted to a command number and the control command is
+ * called using 'arg' as an argument (unless the ENGINE doesn't support such
+ * a command, in which case no control command is called). The command is
+ * checked for input flags, and if necessary the argument will be converted
+ * to a numeric value. If cmd_optional is non-zero, then if the ENGINE
+ * doesn't support the given cmd_name the return value will be success
+ * anyway. This function is intended for applications to use so that users
+ * (or config files) can supply engine-specific config data to the ENGINE at
+ * run-time to control behaviour of specific engines. As such, it shouldn't
+ * be used for calling ENGINE_ctrl() functions that return data, deal with
+ * binary data, or that are otherwise supposed to be used directly through
+ * ENGINE_ctrl() in application code. Any "return" data from an ENGINE_ctrl()
+ * operation in this function will be lost - the return value is interpreted
+ * as failure if the return value is zero, success otherwise, and this
+ * function returns a boolean value as a result. In other words, vendors of
+ * 'ENGINE'-enabled devices should write ENGINE implementations with
+ * parameterisations that work in this scheme, so that compliant ENGINE-based
+ * applications can work consistently with the same configuration for the
+ * same ENGINE-enabled devices, across applications.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_ctrl_cmd_string(ENGINE *e, const char *cmd_name, const char *arg,
+ int cmd_optional);
+# endif
+
+/*
+ * These functions are useful for manufacturing new ENGINE structures. They
+ * don't address reference counting at all - one uses them to populate an
+ * ENGINE structure with personalised implementations of things prior to
+ * using it directly or adding it to the builtin ENGINE list in OpenSSL.
+ * These are also here so that the ENGINE structure doesn't have to be
+ * exposed and break binary compatibility!
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_new(void);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_free(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_up_ref(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_id(ENGINE *e, const char *id);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_name(ENGINE *e, const char *name);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_RSA(ENGINE *e, const RSA_METHOD *rsa_meth);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_DSA(ENGINE *e, const DSA_METHOD *dsa_meth);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_EC(ENGINE *e, const EC_KEY_METHOD *ecdsa_meth);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_DH(ENGINE *e, const DH_METHOD *dh_meth);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_RAND(ENGINE *e, const RAND_METHOD *rand_meth);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_destroy_function(ENGINE *e,ENGINE_GEN_INT_FUNC_PTR destroy_f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_init_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR init_f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_finish_function(ENGINE *e, ENGINE_GEN_INT_FUNC_PTR finish_f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_ctrl_function(ENGINE *e, ENGINE_CTRL_FUNC_PTR ctrl_f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_load_privkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpriv_f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_load_pubkey_function(ENGINE *e, ENGINE_LOAD_KEY_PTR loadpub_f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_load_ssl_client_cert_function(ENGINE *e,
+ ENGINE_SSL_CLIENT_CERT_PTR loadssl_f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_ciphers(ENGINE *e, ENGINE_CIPHERS_PTR f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_digests(ENGINE *e, ENGINE_DIGESTS_PTR f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_pkey_meths(ENGINE *e, ENGINE_PKEY_METHS_PTR f);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_set_pkey_asn1_meths(ENGINE *e, ENGINE_PKEY_ASN1_METHS_PTR f);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_flags(ENGINE *e, int flags);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_cmd_defns(ENGINE *e,
+ const ENGINE_CMD_DEFN *defns);
+# endif
+/* These functions allow control over any per-structure ENGINE data. */
+# define ENGINE_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_ENGINE, l, p, newf, dupf, freef)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_ex_data(ENGINE *e, int idx, void *arg);
+OSSL_DEPRECATEDIN_3_0 void *ENGINE_get_ex_data(const ENGINE *e, int idx);
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/*
+ * This function previously cleaned up anything that needs it. Auto-deinit will
+ * now take care of it so it is no longer required to call this function.
+ */
+# define ENGINE_cleanup() while(0) continue
+# endif
+
+/*
+ * These return values from within the ENGINE structure. These can be useful
+ * with functional references as well as structural references - it depends
+ * which you obtained. Using the result for functional purposes if you only
+ * obtained a structural reference may be problematic!
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *ENGINE_get_id(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 const char *ENGINE_get_name(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 const RSA_METHOD *ENGINE_get_RSA(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 const DSA_METHOD *ENGINE_get_DSA(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 const EC_KEY_METHOD *ENGINE_get_EC(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 const DH_METHOD *ENGINE_get_DH(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 const RAND_METHOD *ENGINE_get_RAND(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_GEN_INT_FUNC_PTR ENGINE_get_destroy_function(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_GEN_INT_FUNC_PTR ENGINE_get_init_function(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_GEN_INT_FUNC_PTR ENGINE_get_finish_function(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_CTRL_FUNC_PTR ENGINE_get_ctrl_function(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_LOAD_KEY_PTR ENGINE_get_load_privkey_function(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_LOAD_KEY_PTR ENGINE_get_load_pubkey_function(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_SSL_CLIENT_CERT_PTR ENGINE_get_ssl_client_cert_function(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_CIPHERS_PTR ENGINE_get_ciphers(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_DIGESTS_PTR ENGINE_get_digests(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_PKEY_METHS_PTR ENGINE_get_pkey_meths(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE_PKEY_ASN1_METHS_PTR ENGINE_get_pkey_asn1_meths(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+const EVP_CIPHER *ENGINE_get_cipher(ENGINE *e, int nid);
+OSSL_DEPRECATEDIN_3_0
+const EVP_MD *ENGINE_get_digest(ENGINE *e, int nid);
+OSSL_DEPRECATEDIN_3_0
+const EVP_PKEY_METHOD *ENGINE_get_pkey_meth(ENGINE *e, int nid);
+OSSL_DEPRECATEDIN_3_0
+const EVP_PKEY_ASN1_METHOD *ENGINE_get_pkey_asn1_meth(ENGINE *e, int nid);
+OSSL_DEPRECATEDIN_3_0
+const EVP_PKEY_ASN1_METHOD *ENGINE_get_pkey_asn1_meth_str(ENGINE *e,
+ const char *str,
+ int len);
+OSSL_DEPRECATEDIN_3_0
+const EVP_PKEY_ASN1_METHOD *ENGINE_pkey_asn1_find_str(ENGINE **pe,
+ const char *str, int len);
+OSSL_DEPRECATEDIN_3_0
+const ENGINE_CMD_DEFN *ENGINE_get_cmd_defns(const ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_get_flags(const ENGINE *e);
+# endif
+
+/*
+ * FUNCTIONAL functions. These functions deal with ENGINE structures that
+ * have (or will) be initialised for use. Broadly speaking, the structural
+ * functions are useful for iterating the list of available engine types,
+ * creating new engine types, and other "list" operations. These functions
+ * actually deal with ENGINEs that are to be used. As such these functions
+ * can fail (if applicable) when particular engines are unavailable - eg. if
+ * a hardware accelerator is not attached or not functioning correctly. Each
+ * ENGINE has 2 reference counts; structural and functional. Every time a
+ * functional reference is obtained or released, a corresponding structural
+ * reference is automatically obtained or released too.
+ */
+
+/*
+ * Initialise a engine type for use (or up its reference count if it's
+ * already in use). This will fail if the engine is not currently operational
+ * and cannot initialise.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_init(ENGINE *e);
+# endif
+/*
+ * Free a functional reference to a engine type. This does not require a
+ * corresponding call to ENGINE_free as it also releases a structural
+ * reference.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_finish(ENGINE *e);
+# endif
+
+/*
+ * The following functions handle keys that are stored in some secondary
+ * location, handled by the engine. The storage may be on a card or
+ * whatever.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+EVP_PKEY *ENGINE_load_private_key(ENGINE *e, const char *key_id,
+ UI_METHOD *ui_method, void *callback_data);
+OSSL_DEPRECATEDIN_3_0
+EVP_PKEY *ENGINE_load_public_key(ENGINE *e, const char *key_id,
+ UI_METHOD *ui_method, void *callback_data);
+OSSL_DEPRECATEDIN_3_0
+int ENGINE_load_ssl_client_cert(ENGINE *e, SSL *s, STACK_OF(X509_NAME) *ca_dn,
+ X509 **pcert, EVP_PKEY **ppkey,
+ STACK_OF(X509) **pother,
+ UI_METHOD *ui_method, void *callback_data);
+# endif
+
+/*
+ * This returns a pointer for the current ENGINE structure that is (by
+ * default) performing any RSA operations. The value returned is an
+ * incremented reference, so it should be free'd (ENGINE_finish) before it is
+ * discarded.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_default_RSA(void);
+# endif
+/* Same for the other "methods" */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_default_DSA(void);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_default_EC(void);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_default_DH(void);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_default_RAND(void);
+# endif
+/*
+ * These functions can be used to get a functional reference to perform
+ * ciphering or digesting corresponding to "nid".
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_cipher_engine(int nid);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_digest_engine(int nid);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_pkey_meth_engine(int nid);
+OSSL_DEPRECATEDIN_3_0 ENGINE *ENGINE_get_pkey_asn1_meth_engine(int nid);
+# endif
+
+/*
+ * This sets a new default ENGINE structure for performing RSA operations. If
+ * the result is non-zero (success) then the ENGINE structure will have had
+ * its reference count up'd so the caller should still free their own
+ * reference 'e'.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_RSA(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_string(ENGINE *e,
+ const char *def_list);
+# endif
+/* Same for the other "methods" */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_DSA(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_EC(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_DH(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_RAND(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_ciphers(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_digests(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_pkey_meths(ENGINE *e);
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default_pkey_asn1_meths(ENGINE *e);
+# endif
+
+/*
+ * The combination "set" - the flags are bitwise "OR"d from the
+ * ENGINE_METHOD_*** defines above. As with the "ENGINE_register_complete()"
+ * function, this function can result in unnecessary static linkage. If your
+ * application requires only specific functionality, consider using more
+ * selective functions.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ENGINE_set_default(ENGINE *e, unsigned int flags);
+OSSL_DEPRECATEDIN_3_0 void ENGINE_add_conf_module(void);
+# endif
+
+/* Deprecated functions ... */
+/* int ENGINE_clear_defaults(void); */
+
+/**************************/
+/* DYNAMIC ENGINE SUPPORT */
+/**************************/
+
+/* Binary/behaviour compatibility levels */
+# define OSSL_DYNAMIC_VERSION (unsigned long)0x00030000
+/*
+ * Binary versions older than this are too old for us (whether we're a loader
+ * or a loadee)
+ */
+# define OSSL_DYNAMIC_OLDEST (unsigned long)0x00030000
+
+/*
+ * When compiling an ENGINE entirely as an external shared library, loadable
+ * by the "dynamic" ENGINE, these types are needed. The 'dynamic_fns'
+ * structure type provides the calling application's (or library's) error
+ * functionality and memory management function pointers to the loaded
+ * library. These should be used/set in the loaded library code so that the
+ * loading application's 'state' will be used/changed in all operations. The
+ * 'static_state' pointer allows the loaded library to know if it shares the
+ * same static data as the calling application (or library), and thus whether
+ * these callbacks need to be set or not.
+ */
+typedef void *(*dyn_MEM_malloc_fn) (size_t, const char *, int);
+typedef void *(*dyn_MEM_realloc_fn) (void *, size_t, const char *, int);
+typedef void (*dyn_MEM_free_fn) (void *, const char *, int);
+typedef struct st_dynamic_MEM_fns {
+ dyn_MEM_malloc_fn malloc_fn;
+ dyn_MEM_realloc_fn realloc_fn;
+ dyn_MEM_free_fn free_fn;
+} dynamic_MEM_fns;
+/*
+ * FIXME: Perhaps the memory and locking code (crypto.h) should declare and
+ * use these types so we (and any other dependent code) can simplify a bit??
+ */
+/* The top-level structure */
+typedef struct st_dynamic_fns {
+ void *static_state;
+ dynamic_MEM_fns mem_fns;
+} dynamic_fns;
+
+/*
+ * The version checking function should be of this prototype. NB: The
+ * ossl_version value passed in is the OSSL_DYNAMIC_VERSION of the loading
+ * code. If this function returns zero, it indicates a (potential) version
+ * incompatibility and the loaded library doesn't believe it can proceed.
+ * Otherwise, the returned value is the (latest) version supported by the
+ * loading library. The loader may still decide that the loaded code's
+ * version is unsatisfactory and could veto the load. The function is
+ * expected to be implemented with the symbol name "v_check", and a default
+ * implementation can be fully instantiated with
+ * IMPLEMENT_DYNAMIC_CHECK_FN().
+ */
+typedef unsigned long (*dynamic_v_check_fn) (unsigned long ossl_version);
+# define IMPLEMENT_DYNAMIC_CHECK_FN() \
+ OPENSSL_EXPORT unsigned long v_check(unsigned long v); \
+ OPENSSL_EXPORT unsigned long v_check(unsigned long v) { \
+ if (v >= OSSL_DYNAMIC_OLDEST) return OSSL_DYNAMIC_VERSION; \
+ return 0; }
+
+/*
+ * This function is passed the ENGINE structure to initialise with its own
+ * function and command settings. It should not adjust the structural or
+ * functional reference counts. If this function returns zero, (a) the load
+ * will be aborted, (b) the previous ENGINE state will be memcpy'd back onto
+ * the structure, and (c) the shared library will be unloaded. So
+ * implementations should do their own internal cleanup in failure
+ * circumstances otherwise they could leak. The 'id' parameter, if non-NULL,
+ * represents the ENGINE id that the loader is looking for. If this is NULL,
+ * the shared library can choose to return failure or to initialise a
+ * 'default' ENGINE. If non-NULL, the shared library must initialise only an
+ * ENGINE matching the passed 'id'. The function is expected to be
+ * implemented with the symbol name "bind_engine". A standard implementation
+ * can be instantiated with IMPLEMENT_DYNAMIC_BIND_FN(fn) where the parameter
+ * 'fn' is a callback function that populates the ENGINE structure and
+ * returns an int value (zero for failure). 'fn' should have prototype;
+ * [static] int fn(ENGINE *e, const char *id);
+ */
+typedef int (*dynamic_bind_engine) (ENGINE *e, const char *id,
+ const dynamic_fns *fns);
+# define IMPLEMENT_DYNAMIC_BIND_FN(fn) \
+ OPENSSL_EXPORT \
+ int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns); \
+ OPENSSL_EXPORT \
+ int bind_engine(ENGINE *e, const char *id, const dynamic_fns *fns) { \
+ if (ENGINE_get_static_state() == fns->static_state) goto skip_cbs; \
+ CRYPTO_set_mem_functions(fns->mem_fns.malloc_fn, \
+ fns->mem_fns.realloc_fn, \
+ fns->mem_fns.free_fn); \
+ skip_cbs: \
+ if (!fn(e, id)) return 0; \
+ return 1; }
+
+/*
+ * If the loading application (or library) and the loaded ENGINE library
+ * share the same static data (eg. they're both dynamically linked to the
+ * same libcrypto.so) we need a way to avoid trying to set system callbacks -
+ * this would fail, and for the same reason that it's unnecessary to try. If
+ * the loaded ENGINE has (or gets from through the loader) its own copy of
+ * the libcrypto static data, we will need to set the callbacks. The easiest
+ * way to detect this is to have a function that returns a pointer to some
+ * static data and let the loading application and loaded ENGINE compare
+ * their respective values.
+ */
+void *ENGINE_get_static_state(void);
+
+# if defined(__OpenBSD__) || defined(__FreeBSD__) || defined(__DragonFly__)
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void ENGINE_setup_bsd_cryptodev(void);
+# endif
+# endif
+
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* OPENSSL_NO_ENGINE */
+#endif /* OPENSSL_ENGINE_H */
diff --git a/include/openssl/engineerr.h b/include/openssl/engineerr.h
new file mode 100644
index 00000000..d439b682
--- /dev/null
+++ b/include/openssl/engineerr.h
@@ -0,0 +1,63 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ENGINEERR_H
+# define OPENSSL_ENGINEERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_ENGINE
+
+
+/*
+ * ENGINE reason codes.
+ */
+# define ENGINE_R_ALREADY_LOADED 100
+# define ENGINE_R_ARGUMENT_IS_NOT_A_NUMBER 133
+# define ENGINE_R_CMD_NOT_EXECUTABLE 134
+# define ENGINE_R_COMMAND_TAKES_INPUT 135
+# define ENGINE_R_COMMAND_TAKES_NO_INPUT 136
+# define ENGINE_R_CONFLICTING_ENGINE_ID 103
+# define ENGINE_R_CTRL_COMMAND_NOT_IMPLEMENTED 119
+# define ENGINE_R_DSO_FAILURE 104
+# define ENGINE_R_DSO_NOT_FOUND 132
+# define ENGINE_R_ENGINES_SECTION_ERROR 148
+# define ENGINE_R_ENGINE_CONFIGURATION_ERROR 102
+# define ENGINE_R_ENGINE_IS_NOT_IN_LIST 105
+# define ENGINE_R_ENGINE_SECTION_ERROR 149
+# define ENGINE_R_FAILED_LOADING_PRIVATE_KEY 128
+# define ENGINE_R_FAILED_LOADING_PUBLIC_KEY 129
+# define ENGINE_R_FINISH_FAILED 106
+# define ENGINE_R_ID_OR_NAME_MISSING 108
+# define ENGINE_R_INIT_FAILED 109
+# define ENGINE_R_INTERNAL_LIST_ERROR 110
+# define ENGINE_R_INVALID_ARGUMENT 143
+# define ENGINE_R_INVALID_CMD_NAME 137
+# define ENGINE_R_INVALID_CMD_NUMBER 138
+# define ENGINE_R_INVALID_INIT_VALUE 151
+# define ENGINE_R_INVALID_STRING 150
+# define ENGINE_R_NOT_INITIALISED 117
+# define ENGINE_R_NOT_LOADED 112
+# define ENGINE_R_NO_CONTROL_FUNCTION 120
+# define ENGINE_R_NO_INDEX 144
+# define ENGINE_R_NO_LOAD_FUNCTION 125
+# define ENGINE_R_NO_REFERENCE 130
+# define ENGINE_R_NO_SUCH_ENGINE 116
+# define ENGINE_R_UNIMPLEMENTED_CIPHER 146
+# define ENGINE_R_UNIMPLEMENTED_DIGEST 147
+# define ENGINE_R_UNIMPLEMENTED_PUBLIC_KEY_METHOD 101
+# define ENGINE_R_VERSION_INCOMPATIBILITY 145
+
+# endif
+#endif
diff --git a/include/openssl/err.h b/include/openssl/err.h
new file mode 100644
index 00000000..3c7299db
--- /dev/null
+++ b/include/openssl/err.h
@@ -0,0 +1,492 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_ERR_H
+# define OPENSSL_ERR_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ERR_H
+# endif
+
+# include <openssl/e_os2.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# include <stdlib.h>
+# endif
+
+# include <openssl/types.h>
+# include <openssl/bio.h>
+# include <openssl/lhash.h>
+# include <openssl/cryptoerr_legacy.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_FILENAMES
+# define ERR_PUT_error(l,f,r,fn,ln) ERR_put_error(l,f,r,fn,ln)
+# else
+# define ERR_PUT_error(l,f,r,fn,ln) ERR_put_error(l,f,r,NULL,0)
+# endif
+# endif
+
+# include <limits.h>
+# include <errno.h>
+
+# define ERR_TXT_MALLOCED 0x01
+# define ERR_TXT_STRING 0x02
+
+# if !defined(OPENSSL_NO_DEPRECATED_3_0) || defined(OSSL_FORCE_ERR_STATE)
+# define ERR_FLAG_MARK 0x01
+# define ERR_FLAG_CLEAR 0x02
+
+# define ERR_NUM_ERRORS 16
+struct err_state_st {
+ int err_flags[ERR_NUM_ERRORS];
+ int err_marks[ERR_NUM_ERRORS];
+ unsigned long err_buffer[ERR_NUM_ERRORS];
+ char *err_data[ERR_NUM_ERRORS];
+ size_t err_data_size[ERR_NUM_ERRORS];
+ int err_data_flags[ERR_NUM_ERRORS];
+ char *err_file[ERR_NUM_ERRORS];
+ int err_line[ERR_NUM_ERRORS];
+ char *err_func[ERR_NUM_ERRORS];
+ int top, bottom;
+};
+# endif
+
+/* library */
+# define ERR_LIB_NONE 1
+# define ERR_LIB_SYS 2
+# define ERR_LIB_BN 3
+# define ERR_LIB_RSA 4
+# define ERR_LIB_DH 5
+# define ERR_LIB_EVP 6
+# define ERR_LIB_BUF 7
+# define ERR_LIB_OBJ 8
+# define ERR_LIB_PEM 9
+# define ERR_LIB_DSA 10
+# define ERR_LIB_X509 11
+/* #define ERR_LIB_METH 12 */
+# define ERR_LIB_ASN1 13
+# define ERR_LIB_CONF 14
+# define ERR_LIB_CRYPTO 15
+# define ERR_LIB_EC 16
+# define ERR_LIB_SSL 20
+/* #define ERR_LIB_SSL23 21 */
+/* #define ERR_LIB_SSL2 22 */
+/* #define ERR_LIB_SSL3 23 */
+/* #define ERR_LIB_RSAREF 30 */
+/* #define ERR_LIB_PROXY 31 */
+# define ERR_LIB_BIO 32
+# define ERR_LIB_PKCS7 33
+# define ERR_LIB_X509V3 34
+# define ERR_LIB_PKCS12 35
+# define ERR_LIB_RAND 36
+# define ERR_LIB_DSO 37
+# define ERR_LIB_ENGINE 38
+# define ERR_LIB_OCSP 39
+# define ERR_LIB_UI 40
+# define ERR_LIB_COMP 41
+# define ERR_LIB_ECDSA 42
+# define ERR_LIB_ECDH 43
+# define ERR_LIB_OSSL_STORE 44
+# define ERR_LIB_FIPS 45
+# define ERR_LIB_CMS 46
+# define ERR_LIB_TS 47
+# define ERR_LIB_HMAC 48
+/* # define ERR_LIB_JPAKE 49 */
+# define ERR_LIB_CT 50
+# define ERR_LIB_ASYNC 51
+# define ERR_LIB_KDF 52
+# define ERR_LIB_SM2 53
+# define ERR_LIB_ESS 54
+# define ERR_LIB_PROP 55
+# define ERR_LIB_CRMF 56
+# define ERR_LIB_PROV 57
+# define ERR_LIB_CMP 58
+# define ERR_LIB_OSSL_ENCODER 59
+# define ERR_LIB_OSSL_DECODER 60
+# define ERR_LIB_HTTP 61
+
+# define ERR_LIB_USER 128
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define ASN1err(f, r) ERR_raise_data(ERR_LIB_ASN1, (r), NULL)
+# define ASYNCerr(f, r) ERR_raise_data(ERR_LIB_ASYNC, (r), NULL)
+# define BIOerr(f, r) ERR_raise_data(ERR_LIB_BIO, (r), NULL)
+# define BNerr(f, r) ERR_raise_data(ERR_LIB_BN, (r), NULL)
+# define BUFerr(f, r) ERR_raise_data(ERR_LIB_BUF, (r), NULL)
+# define CMPerr(f, r) ERR_raise_data(ERR_LIB_CMP, (r), NULL)
+# define CMSerr(f, r) ERR_raise_data(ERR_LIB_CMS, (r), NULL)
+# define COMPerr(f, r) ERR_raise_data(ERR_LIB_COMP, (r), NULL)
+# define CONFerr(f, r) ERR_raise_data(ERR_LIB_CONF, (r), NULL)
+# define CRMFerr(f, r) ERR_raise_data(ERR_LIB_CRMF, (r), NULL)
+# define CRYPTOerr(f, r) ERR_raise_data(ERR_LIB_CRYPTO, (r), NULL)
+# define CTerr(f, r) ERR_raise_data(ERR_LIB_CT, (r), NULL)
+# define DHerr(f, r) ERR_raise_data(ERR_LIB_DH, (r), NULL)
+# define DSAerr(f, r) ERR_raise_data(ERR_LIB_DSA, (r), NULL)
+# define DSOerr(f, r) ERR_raise_data(ERR_LIB_DSO, (r), NULL)
+# define ECDHerr(f, r) ERR_raise_data(ERR_LIB_ECDH, (r), NULL)
+# define ECDSAerr(f, r) ERR_raise_data(ERR_LIB_ECDSA, (r), NULL)
+# define ECerr(f, r) ERR_raise_data(ERR_LIB_EC, (r), NULL)
+# define ENGINEerr(f, r) ERR_raise_data(ERR_LIB_ENGINE, (r), NULL)
+# define ESSerr(f, r) ERR_raise_data(ERR_LIB_ESS, (r), NULL)
+# define EVPerr(f, r) ERR_raise_data(ERR_LIB_EVP, (r), NULL)
+# define FIPSerr(f, r) ERR_raise_data(ERR_LIB_FIPS, (r), NULL)
+# define HMACerr(f, r) ERR_raise_data(ERR_LIB_HMAC, (r), NULL)
+# define HTTPerr(f, r) ERR_raise_data(ERR_LIB_HTTP, (r), NULL)
+# define KDFerr(f, r) ERR_raise_data(ERR_LIB_KDF, (r), NULL)
+# define OBJerr(f, r) ERR_raise_data(ERR_LIB_OBJ, (r), NULL)
+# define OCSPerr(f, r) ERR_raise_data(ERR_LIB_OCSP, (r), NULL)
+# define OSSL_STOREerr(f, r) ERR_raise_data(ERR_LIB_OSSL_STORE, (r), NULL)
+# define PEMerr(f, r) ERR_raise_data(ERR_LIB_PEM, (r), NULL)
+# define PKCS12err(f, r) ERR_raise_data(ERR_LIB_PKCS12, (r), NULL)
+# define PKCS7err(f, r) ERR_raise_data(ERR_LIB_PKCS7, (r), NULL)
+# define PROPerr(f, r) ERR_raise_data(ERR_LIB_PROP, (r), NULL)
+# define PROVerr(f, r) ERR_raise_data(ERR_LIB_PROV, (r), NULL)
+# define RANDerr(f, r) ERR_raise_data(ERR_LIB_RAND, (r), NULL)
+# define RSAerr(f, r) ERR_raise_data(ERR_LIB_RSA, (r), NULL)
+# define KDFerr(f, r) ERR_raise_data(ERR_LIB_KDF, (r), NULL)
+# define SM2err(f, r) ERR_raise_data(ERR_LIB_SM2, (r), NULL)
+# define SSLerr(f, r) ERR_raise_data(ERR_LIB_SSL, (r), NULL)
+# define SYSerr(f, r) ERR_raise_data(ERR_LIB_SYS, (r), NULL)
+# define TSerr(f, r) ERR_raise_data(ERR_LIB_TS, (r), NULL)
+# define UIerr(f, r) ERR_raise_data(ERR_LIB_UI, (r), NULL)
+# define X509V3err(f, r) ERR_raise_data(ERR_LIB_X509V3, (r), NULL)
+# define X509err(f, r) ERR_raise_data(ERR_LIB_X509, (r), NULL)
+# endif
+
+/*-
+ * The error code packs differently depending on if it records a system
+ * error or an OpenSSL error.
+ *
+ * A system error packs like this (we follow POSIX and only allow positive
+ * numbers that fit in an |int|):
+ *
+ * +-+-------------------------------------------------------------+
+ * |1| system error number |
+ * +-+-------------------------------------------------------------+
+ *
+ * An OpenSSL error packs like this:
+ *
+ * <---------------------------- 32 bits -------------------------->
+ * <--- 8 bits ---><------------------ 23 bits ----------------->
+ * +-+---------------+---------------------------------------------+
+ * |0| library | reason |
+ * +-+---------------+---------------------------------------------+
+ *
+ * A few of the reason bits are reserved as flags with special meaning:
+ *
+ * <5 bits-<>--------- 19 bits ----------------->
+ * +-------+-+-----------------------------------+
+ * | rflags| | reason |
+ * +-------+-+-----------------------------------+
+ * ^
+ * |
+ * ERR_RFLAG_FATAL = ERR_R_FATAL
+ *
+ * The reason flags are part of the overall reason code for practical
+ * reasons, as they provide an easy way to place different types of
+ * reason codes in different numeric ranges.
+ *
+ * The currently known reason flags are:
+ *
+ * ERR_RFLAG_FATAL Flags that the reason code is considered fatal.
+ * For backward compatibility reasons, this flag
+ * is also the code for ERR_R_FATAL (that reason
+ * code served the dual purpose of flag and reason
+ * code in one in pre-3.0 OpenSSL).
+ * ERR_RFLAG_COMMON Flags that the reason code is common to all
+ * libraries. All ERR_R_ macros must use this flag,
+ * and no other _R_ macro is allowed to use it.
+ */
+
+/* Macros to help decode recorded system errors */
+# define ERR_SYSTEM_FLAG ((unsigned int)INT_MAX + 1)
+# define ERR_SYSTEM_MASK ((unsigned int)INT_MAX)
+
+/*
+ * Macros to help decode recorded OpenSSL errors
+ * As expressed above, RFLAGS and REASON overlap by one bit to allow
+ * ERR_R_FATAL to use ERR_RFLAG_FATAL as its reason code.
+ */
+# define ERR_LIB_OFFSET 23L
+# define ERR_LIB_MASK 0xFF
+# define ERR_RFLAGS_OFFSET 18L
+# define ERR_RFLAGS_MASK 0x1F
+# define ERR_REASON_MASK 0X7FFFFF
+
+/*
+ * Reason flags are defined pre-shifted to easily combine with the reason
+ * number.
+ */
+# define ERR_RFLAG_FATAL (0x1 << ERR_RFLAGS_OFFSET)
+# define ERR_RFLAG_COMMON (0x2 << ERR_RFLAGS_OFFSET)
+
+# define ERR_SYSTEM_ERROR(errcode) (((errcode) & ERR_SYSTEM_FLAG) != 0)
+
+static ossl_unused ossl_inline int ERR_GET_LIB(unsigned long errcode)
+{
+ if (ERR_SYSTEM_ERROR(errcode))
+ return ERR_LIB_SYS;
+ return (errcode >> ERR_LIB_OFFSET) & ERR_LIB_MASK;
+}
+
+static ossl_unused ossl_inline int ERR_GET_RFLAGS(unsigned long errcode)
+{
+ if (ERR_SYSTEM_ERROR(errcode))
+ return 0;
+ return errcode & (ERR_RFLAGS_MASK << ERR_RFLAGS_OFFSET);
+}
+
+static ossl_unused ossl_inline int ERR_GET_REASON(unsigned long errcode)
+{
+ if (ERR_SYSTEM_ERROR(errcode))
+ return errcode & ERR_SYSTEM_MASK;
+ return errcode & ERR_REASON_MASK;
+}
+
+static ossl_unused ossl_inline int ERR_FATAL_ERROR(unsigned long errcode)
+{
+ return (ERR_GET_RFLAGS(errcode) & ERR_RFLAG_FATAL) != 0;
+}
+
+static ossl_unused ossl_inline int ERR_COMMON_ERROR(unsigned long errcode)
+{
+ return (ERR_GET_RFLAGS(errcode) & ERR_RFLAG_COMMON) != 0;
+}
+
+/*
+ * ERR_PACK is a helper macro to properly pack OpenSSL error codes and may
+ * only be used for that purpose. System errors are packed internally.
+ * ERR_PACK takes reason flags and reason code combined in |reason|.
+ * ERR_PACK ignores |func|, that parameter is just legacy from pre-3.0 OpenSSL.
+ */
+# define ERR_PACK(lib,func,reason) \
+ ( (((unsigned long)(lib) & ERR_LIB_MASK ) << ERR_LIB_OFFSET) | \
+ (((unsigned long)(reason) & ERR_REASON_MASK)) )
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SYS_F_FOPEN 0
+# define SYS_F_CONNECT 0
+# define SYS_F_GETSERVBYNAME 0
+# define SYS_F_SOCKET 0
+# define SYS_F_IOCTLSOCKET 0
+# define SYS_F_BIND 0
+# define SYS_F_LISTEN 0
+# define SYS_F_ACCEPT 0
+# define SYS_F_WSASTARTUP 0
+# define SYS_F_OPENDIR 0
+# define SYS_F_FREAD 0
+# define SYS_F_GETADDRINFO 0
+# define SYS_F_GETNAMEINFO 0
+# define SYS_F_SETSOCKOPT 0
+# define SYS_F_GETSOCKOPT 0
+# define SYS_F_GETSOCKNAME 0
+# define SYS_F_GETHOSTBYNAME 0
+# define SYS_F_FFLUSH 0
+# define SYS_F_OPEN 0
+# define SYS_F_CLOSE 0
+# define SYS_F_IOCTL 0
+# define SYS_F_STAT 0
+# define SYS_F_FCNTL 0
+# define SYS_F_FSTAT 0
+# define SYS_F_SENDFILE 0
+# endif
+
+/*
+ * All ERR_R_ codes must be combined with ERR_RFLAG_COMMON.
+ */
+
+/* "we came from here" global reason codes, range 1..255 */
+# define ERR_R_SYS_LIB (ERR_LIB_SYS/* 2 */ | ERR_RFLAG_COMMON)
+# define ERR_R_BN_LIB (ERR_LIB_BN/* 3 */ | ERR_RFLAG_COMMON)
+# define ERR_R_RSA_LIB (ERR_LIB_RSA/* 4 */ | ERR_RFLAG_COMMON)
+# define ERR_R_DH_LIB (ERR_LIB_DH/* 5 */ | ERR_RFLAG_COMMON)
+# define ERR_R_EVP_LIB (ERR_LIB_EVP/* 6 */ | ERR_RFLAG_COMMON)
+# define ERR_R_BUF_LIB (ERR_LIB_BUF/* 7 */ | ERR_RFLAG_COMMON)
+# define ERR_R_OBJ_LIB (ERR_LIB_OBJ/* 8 */ | ERR_RFLAG_COMMON)
+# define ERR_R_PEM_LIB (ERR_LIB_PEM/* 9 */ | ERR_RFLAG_COMMON)
+# define ERR_R_DSA_LIB (ERR_LIB_DSA/* 10 */ | ERR_RFLAG_COMMON)
+# define ERR_R_X509_LIB (ERR_LIB_X509/* 11 */ | ERR_RFLAG_COMMON)
+# define ERR_R_ASN1_LIB (ERR_LIB_ASN1/* 13 */ | ERR_RFLAG_COMMON)
+# define ERR_R_CRYPTO_LIB (ERR_LIB_CRYPTO/* 15 */ | ERR_RFLAG_COMMON)
+# define ERR_R_EC_LIB (ERR_LIB_EC/* 16 */ | ERR_RFLAG_COMMON)
+# define ERR_R_BIO_LIB (ERR_LIB_BIO/* 32 */ | ERR_RFLAG_COMMON)
+# define ERR_R_PKCS7_LIB (ERR_LIB_PKCS7/* 33 */ | ERR_RFLAG_COMMON)
+# define ERR_R_X509V3_LIB (ERR_LIB_X509V3/* 34 */ | ERR_RFLAG_COMMON)
+# define ERR_R_ENGINE_LIB (ERR_LIB_ENGINE/* 38 */ | ERR_RFLAG_COMMON)
+# define ERR_R_UI_LIB (ERR_LIB_UI/* 40 */ | ERR_RFLAG_COMMON)
+# define ERR_R_ECDSA_LIB (ERR_LIB_ECDSA/* 42 */ | ERR_RFLAG_COMMON)
+# define ERR_R_OSSL_STORE_LIB (ERR_LIB_OSSL_STORE/* 44 */ | ERR_RFLAG_COMMON)
+# define ERR_R_OSSL_DECODER_LIB (ERR_LIB_OSSL_DECODER/* 60 */ | ERR_RFLAG_COMMON)
+
+/* Other common error codes, range 256..2^ERR_RFLAGS_OFFSET-1 */
+# define ERR_R_FATAL (ERR_RFLAG_FATAL|ERR_RFLAG_COMMON)
+# define ERR_R_MALLOC_FAILURE (256|ERR_R_FATAL)
+# define ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED (257|ERR_R_FATAL)
+# define ERR_R_PASSED_NULL_PARAMETER (258|ERR_R_FATAL)
+# define ERR_R_INTERNAL_ERROR (259|ERR_R_FATAL)
+# define ERR_R_DISABLED (260|ERR_R_FATAL)
+# define ERR_R_INIT_FAIL (261|ERR_R_FATAL)
+# define ERR_R_PASSED_INVALID_ARGUMENT (262|ERR_RFLAG_COMMON)
+# define ERR_R_OPERATION_FAIL (263|ERR_R_FATAL)
+# define ERR_R_INVALID_PROVIDER_FUNCTIONS (264|ERR_R_FATAL)
+# define ERR_R_INTERRUPTED_OR_CANCELLED (265|ERR_RFLAG_COMMON)
+# define ERR_R_NESTED_ASN1_ERROR (266|ERR_RFLAG_COMMON)
+# define ERR_R_MISSING_ASN1_EOS (267|ERR_RFLAG_COMMON)
+# define ERR_R_UNSUPPORTED (268|ERR_RFLAG_COMMON)
+# define ERR_R_FETCH_FAILED (269|ERR_RFLAG_COMMON)
+# define ERR_R_INVALID_PROPERTY_DEFINITION (270|ERR_RFLAG_COMMON)
+# define ERR_R_UNABLE_TO_GET_READ_LOCK (271|ERR_R_FATAL)
+# define ERR_R_UNABLE_TO_GET_WRITE_LOCK (272|ERR_R_FATAL)
+
+typedef struct ERR_string_data_st {
+ unsigned long error;
+ const char *string;
+} ERR_STRING_DATA;
+
+DEFINE_LHASH_OF_INTERNAL(ERR_STRING_DATA);
+#define lh_ERR_STRING_DATA_new(hfn, cmp) ((LHASH_OF(ERR_STRING_DATA) *)OPENSSL_LH_new(ossl_check_ERR_STRING_DATA_lh_hashfunc_type(hfn), ossl_check_ERR_STRING_DATA_lh_compfunc_type(cmp)))
+#define lh_ERR_STRING_DATA_free(lh) OPENSSL_LH_free(ossl_check_ERR_STRING_DATA_lh_type(lh))
+#define lh_ERR_STRING_DATA_flush(lh) OPENSSL_LH_flush(ossl_check_ERR_STRING_DATA_lh_type(lh))
+#define lh_ERR_STRING_DATA_insert(lh, ptr) ((ERR_STRING_DATA *)OPENSSL_LH_insert(ossl_check_ERR_STRING_DATA_lh_type(lh), ossl_check_ERR_STRING_DATA_lh_plain_type(ptr)))
+#define lh_ERR_STRING_DATA_delete(lh, ptr) ((ERR_STRING_DATA *)OPENSSL_LH_delete(ossl_check_ERR_STRING_DATA_lh_type(lh), ossl_check_const_ERR_STRING_DATA_lh_plain_type(ptr)))
+#define lh_ERR_STRING_DATA_retrieve(lh, ptr) ((ERR_STRING_DATA *)OPENSSL_LH_retrieve(ossl_check_ERR_STRING_DATA_lh_type(lh), ossl_check_const_ERR_STRING_DATA_lh_plain_type(ptr)))
+#define lh_ERR_STRING_DATA_error(lh) OPENSSL_LH_error(ossl_check_ERR_STRING_DATA_lh_type(lh))
+#define lh_ERR_STRING_DATA_num_items(lh) OPENSSL_LH_num_items(ossl_check_ERR_STRING_DATA_lh_type(lh))
+#define lh_ERR_STRING_DATA_node_stats_bio(lh, out) OPENSSL_LH_node_stats_bio(ossl_check_const_ERR_STRING_DATA_lh_type(lh), out)
+#define lh_ERR_STRING_DATA_node_usage_stats_bio(lh, out) OPENSSL_LH_node_usage_stats_bio(ossl_check_const_ERR_STRING_DATA_lh_type(lh), out)
+#define lh_ERR_STRING_DATA_stats_bio(lh, out) OPENSSL_LH_stats_bio(ossl_check_const_ERR_STRING_DATA_lh_type(lh), out)
+#define lh_ERR_STRING_DATA_get_down_load(lh) OPENSSL_LH_get_down_load(ossl_check_ERR_STRING_DATA_lh_type(lh))
+#define lh_ERR_STRING_DATA_set_down_load(lh, dl) OPENSSL_LH_set_down_load(ossl_check_ERR_STRING_DATA_lh_type(lh), dl)
+#define lh_ERR_STRING_DATA_doall(lh, dfn) OPENSSL_LH_doall(ossl_check_ERR_STRING_DATA_lh_type(lh), ossl_check_ERR_STRING_DATA_lh_doallfunc_type(dfn))
+
+
+/* 12 lines and some on an 80 column terminal */
+#define ERR_MAX_DATA_SIZE 1024
+
+/* Building blocks */
+void ERR_new(void);
+void ERR_set_debug(const char *file, int line, const char *func);
+void ERR_set_error(int lib, int reason, const char *fmt, ...);
+void ERR_vset_error(int lib, int reason, const char *fmt, va_list args);
+
+/* Main error raising functions */
+# define ERR_raise(lib, reason) ERR_raise_data((lib),(reason),NULL)
+# define ERR_raise_data \
+ (ERR_new(), \
+ ERR_set_debug(OPENSSL_FILE,OPENSSL_LINE,OPENSSL_FUNC), \
+ ERR_set_error)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* Backward compatibility */
+# define ERR_put_error(lib, func, reason, file, line) \
+ (ERR_new(), \
+ ERR_set_debug((file), (line), OPENSSL_FUNC), \
+ ERR_set_error((lib), (reason), NULL))
+# endif
+
+void ERR_set_error_data(char *data, int flags);
+
+unsigned long ERR_get_error(void);
+unsigned long ERR_get_error_all(const char **file, int *line,
+ const char **func,
+ const char **data, int *flags);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_get_error_line(const char **file, int *line);
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_get_error_line_data(const char **file, int *line,
+ const char **data, int *flags);
+#endif
+unsigned long ERR_peek_error(void);
+unsigned long ERR_peek_error_line(const char **file, int *line);
+unsigned long ERR_peek_error_func(const char **func);
+unsigned long ERR_peek_error_data(const char **data, int *flags);
+unsigned long ERR_peek_error_all(const char **file, int *line,
+ const char **func,
+ const char **data, int *flags);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_peek_error_line_data(const char **file, int *line,
+ const char **data, int *flags);
+# endif
+unsigned long ERR_peek_last_error(void);
+unsigned long ERR_peek_last_error_line(const char **file, int *line);
+unsigned long ERR_peek_last_error_func(const char **func);
+unsigned long ERR_peek_last_error_data(const char **data, int *flags);
+unsigned long ERR_peek_last_error_all(const char **file, int *line,
+ const char **func,
+ const char **data, int *flags);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
+ const char **data, int *flags);
+# endif
+
+void ERR_clear_error(void);
+
+char *ERR_error_string(unsigned long e, char *buf);
+void ERR_error_string_n(unsigned long e, char *buf, size_t len);
+const char *ERR_lib_error_string(unsigned long e);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *ERR_func_error_string(unsigned long e);
+# endif
+const char *ERR_reason_error_string(unsigned long e);
+
+void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u),
+ void *u);
+# ifndef OPENSSL_NO_STDIO
+void ERR_print_errors_fp(FILE *fp);
+# endif
+void ERR_print_errors(BIO *bp);
+
+void ERR_add_error_data(int num, ...);
+void ERR_add_error_vdata(int num, va_list args);
+void ERR_add_error_txt(const char *sepr, const char *txt);
+void ERR_add_error_mem_bio(const char *sep, BIO *bio);
+
+int ERR_load_strings(int lib, ERR_STRING_DATA *str);
+int ERR_load_strings_const(const ERR_STRING_DATA *str);
+int ERR_unload_strings(int lib, ERR_STRING_DATA *str);
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define ERR_load_crypto_strings() \
+ OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL)
+# define ERR_free_strings() while(0) continue
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void ERR_remove_thread_state(void *);
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_1_0_0
+OSSL_DEPRECATEDIN_1_0_0 void ERR_remove_state(unsigned long pid);
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ERR_STATE *ERR_get_state(void);
+#endif
+
+int ERR_get_next_error_library(void);
+
+int ERR_set_mark(void);
+int ERR_pop_to_mark(void);
+int ERR_clear_last_mark(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/err.h.in b/include/openssl/err.h.in
new file mode 100644
index 00000000..7ca0b970
--- /dev/null
+++ b/include/openssl/err.h.in
@@ -0,0 +1,481 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_lhash_macros);
+-}
+
+#ifndef OPENSSL_ERR_H
+# define OPENSSL_ERR_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ERR_H
+# endif
+
+# include <openssl/e_os2.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# include <stdlib.h>
+# endif
+
+# include <openssl/types.h>
+# include <openssl/bio.h>
+# include <openssl/lhash.h>
+# include <openssl/cryptoerr_legacy.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_FILENAMES
+# define ERR_PUT_error(l,f,r,fn,ln) ERR_put_error(l,f,r,fn,ln)
+# else
+# define ERR_PUT_error(l,f,r,fn,ln) ERR_put_error(l,f,r,NULL,0)
+# endif
+# endif
+
+# include <limits.h>
+# include <errno.h>
+
+# define ERR_TXT_MALLOCED 0x01
+# define ERR_TXT_STRING 0x02
+
+# if !defined(OPENSSL_NO_DEPRECATED_3_0) || defined(OSSL_FORCE_ERR_STATE)
+# define ERR_FLAG_MARK 0x01
+# define ERR_FLAG_CLEAR 0x02
+
+# define ERR_NUM_ERRORS 16
+struct err_state_st {
+ int err_flags[ERR_NUM_ERRORS];
+ int err_marks[ERR_NUM_ERRORS];
+ unsigned long err_buffer[ERR_NUM_ERRORS];
+ char *err_data[ERR_NUM_ERRORS];
+ size_t err_data_size[ERR_NUM_ERRORS];
+ int err_data_flags[ERR_NUM_ERRORS];
+ char *err_file[ERR_NUM_ERRORS];
+ int err_line[ERR_NUM_ERRORS];
+ char *err_func[ERR_NUM_ERRORS];
+ int top, bottom;
+};
+# endif
+
+/* library */
+# define ERR_LIB_NONE 1
+# define ERR_LIB_SYS 2
+# define ERR_LIB_BN 3
+# define ERR_LIB_RSA 4
+# define ERR_LIB_DH 5
+# define ERR_LIB_EVP 6
+# define ERR_LIB_BUF 7
+# define ERR_LIB_OBJ 8
+# define ERR_LIB_PEM 9
+# define ERR_LIB_DSA 10
+# define ERR_LIB_X509 11
+/* #define ERR_LIB_METH 12 */
+# define ERR_LIB_ASN1 13
+# define ERR_LIB_CONF 14
+# define ERR_LIB_CRYPTO 15
+# define ERR_LIB_EC 16
+# define ERR_LIB_SSL 20
+/* #define ERR_LIB_SSL23 21 */
+/* #define ERR_LIB_SSL2 22 */
+/* #define ERR_LIB_SSL3 23 */
+/* #define ERR_LIB_RSAREF 30 */
+/* #define ERR_LIB_PROXY 31 */
+# define ERR_LIB_BIO 32
+# define ERR_LIB_PKCS7 33
+# define ERR_LIB_X509V3 34
+# define ERR_LIB_PKCS12 35
+# define ERR_LIB_RAND 36
+# define ERR_LIB_DSO 37
+# define ERR_LIB_ENGINE 38
+# define ERR_LIB_OCSP 39
+# define ERR_LIB_UI 40
+# define ERR_LIB_COMP 41
+# define ERR_LIB_ECDSA 42
+# define ERR_LIB_ECDH 43
+# define ERR_LIB_OSSL_STORE 44
+# define ERR_LIB_FIPS 45
+# define ERR_LIB_CMS 46
+# define ERR_LIB_TS 47
+# define ERR_LIB_HMAC 48
+/* # define ERR_LIB_JPAKE 49 */
+# define ERR_LIB_CT 50
+# define ERR_LIB_ASYNC 51
+# define ERR_LIB_KDF 52
+# define ERR_LIB_SM2 53
+# define ERR_LIB_ESS 54
+# define ERR_LIB_PROP 55
+# define ERR_LIB_CRMF 56
+# define ERR_LIB_PROV 57
+# define ERR_LIB_CMP 58
+# define ERR_LIB_OSSL_ENCODER 59
+# define ERR_LIB_OSSL_DECODER 60
+# define ERR_LIB_HTTP 61
+
+# define ERR_LIB_USER 128
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define ASN1err(f, r) ERR_raise_data(ERR_LIB_ASN1, (r), NULL)
+# define ASYNCerr(f, r) ERR_raise_data(ERR_LIB_ASYNC, (r), NULL)
+# define BIOerr(f, r) ERR_raise_data(ERR_LIB_BIO, (r), NULL)
+# define BNerr(f, r) ERR_raise_data(ERR_LIB_BN, (r), NULL)
+# define BUFerr(f, r) ERR_raise_data(ERR_LIB_BUF, (r), NULL)
+# define CMPerr(f, r) ERR_raise_data(ERR_LIB_CMP, (r), NULL)
+# define CMSerr(f, r) ERR_raise_data(ERR_LIB_CMS, (r), NULL)
+# define COMPerr(f, r) ERR_raise_data(ERR_LIB_COMP, (r), NULL)
+# define CONFerr(f, r) ERR_raise_data(ERR_LIB_CONF, (r), NULL)
+# define CRMFerr(f, r) ERR_raise_data(ERR_LIB_CRMF, (r), NULL)
+# define CRYPTOerr(f, r) ERR_raise_data(ERR_LIB_CRYPTO, (r), NULL)
+# define CTerr(f, r) ERR_raise_data(ERR_LIB_CT, (r), NULL)
+# define DHerr(f, r) ERR_raise_data(ERR_LIB_DH, (r), NULL)
+# define DSAerr(f, r) ERR_raise_data(ERR_LIB_DSA, (r), NULL)
+# define DSOerr(f, r) ERR_raise_data(ERR_LIB_DSO, (r), NULL)
+# define ECDHerr(f, r) ERR_raise_data(ERR_LIB_ECDH, (r), NULL)
+# define ECDSAerr(f, r) ERR_raise_data(ERR_LIB_ECDSA, (r), NULL)
+# define ECerr(f, r) ERR_raise_data(ERR_LIB_EC, (r), NULL)
+# define ENGINEerr(f, r) ERR_raise_data(ERR_LIB_ENGINE, (r), NULL)
+# define ESSerr(f, r) ERR_raise_data(ERR_LIB_ESS, (r), NULL)
+# define EVPerr(f, r) ERR_raise_data(ERR_LIB_EVP, (r), NULL)
+# define FIPSerr(f, r) ERR_raise_data(ERR_LIB_FIPS, (r), NULL)
+# define HMACerr(f, r) ERR_raise_data(ERR_LIB_HMAC, (r), NULL)
+# define HTTPerr(f, r) ERR_raise_data(ERR_LIB_HTTP, (r), NULL)
+# define KDFerr(f, r) ERR_raise_data(ERR_LIB_KDF, (r), NULL)
+# define OBJerr(f, r) ERR_raise_data(ERR_LIB_OBJ, (r), NULL)
+# define OCSPerr(f, r) ERR_raise_data(ERR_LIB_OCSP, (r), NULL)
+# define OSSL_STOREerr(f, r) ERR_raise_data(ERR_LIB_OSSL_STORE, (r), NULL)
+# define PEMerr(f, r) ERR_raise_data(ERR_LIB_PEM, (r), NULL)
+# define PKCS12err(f, r) ERR_raise_data(ERR_LIB_PKCS12, (r), NULL)
+# define PKCS7err(f, r) ERR_raise_data(ERR_LIB_PKCS7, (r), NULL)
+# define PROPerr(f, r) ERR_raise_data(ERR_LIB_PROP, (r), NULL)
+# define PROVerr(f, r) ERR_raise_data(ERR_LIB_PROV, (r), NULL)
+# define RANDerr(f, r) ERR_raise_data(ERR_LIB_RAND, (r), NULL)
+# define RSAerr(f, r) ERR_raise_data(ERR_LIB_RSA, (r), NULL)
+# define KDFerr(f, r) ERR_raise_data(ERR_LIB_KDF, (r), NULL)
+# define SM2err(f, r) ERR_raise_data(ERR_LIB_SM2, (r), NULL)
+# define SSLerr(f, r) ERR_raise_data(ERR_LIB_SSL, (r), NULL)
+# define SYSerr(f, r) ERR_raise_data(ERR_LIB_SYS, (r), NULL)
+# define TSerr(f, r) ERR_raise_data(ERR_LIB_TS, (r), NULL)
+# define UIerr(f, r) ERR_raise_data(ERR_LIB_UI, (r), NULL)
+# define X509V3err(f, r) ERR_raise_data(ERR_LIB_X509V3, (r), NULL)
+# define X509err(f, r) ERR_raise_data(ERR_LIB_X509, (r), NULL)
+# endif
+
+/*-
+ * The error code packs differently depending on if it records a system
+ * error or an OpenSSL error.
+ *
+ * A system error packs like this (we follow POSIX and only allow positive
+ * numbers that fit in an |int|):
+ *
+ * +-+-------------------------------------------------------------+
+ * |1| system error number |
+ * +-+-------------------------------------------------------------+
+ *
+ * An OpenSSL error packs like this:
+ *
+ * <---------------------------- 32 bits -------------------------->
+ * <--- 8 bits ---><------------------ 23 bits ----------------->
+ * +-+---------------+---------------------------------------------+
+ * |0| library | reason |
+ * +-+---------------+---------------------------------------------+
+ *
+ * A few of the reason bits are reserved as flags with special meaning:
+ *
+ * <5 bits-<>--------- 19 bits ----------------->
+ * +-------+-+-----------------------------------+
+ * | rflags| | reason |
+ * +-------+-+-----------------------------------+
+ * ^
+ * |
+ * ERR_RFLAG_FATAL = ERR_R_FATAL
+ *
+ * The reason flags are part of the overall reason code for practical
+ * reasons, as they provide an easy way to place different types of
+ * reason codes in different numeric ranges.
+ *
+ * The currently known reason flags are:
+ *
+ * ERR_RFLAG_FATAL Flags that the reason code is considered fatal.
+ * For backward compatibility reasons, this flag
+ * is also the code for ERR_R_FATAL (that reason
+ * code served the dual purpose of flag and reason
+ * code in one in pre-3.0 OpenSSL).
+ * ERR_RFLAG_COMMON Flags that the reason code is common to all
+ * libraries. All ERR_R_ macros must use this flag,
+ * and no other _R_ macro is allowed to use it.
+ */
+
+/* Macros to help decode recorded system errors */
+# define ERR_SYSTEM_FLAG ((unsigned int)INT_MAX + 1)
+# define ERR_SYSTEM_MASK ((unsigned int)INT_MAX)
+
+/*
+ * Macros to help decode recorded OpenSSL errors
+ * As expressed above, RFLAGS and REASON overlap by one bit to allow
+ * ERR_R_FATAL to use ERR_RFLAG_FATAL as its reason code.
+ */
+# define ERR_LIB_OFFSET 23L
+# define ERR_LIB_MASK 0xFF
+# define ERR_RFLAGS_OFFSET 18L
+# define ERR_RFLAGS_MASK 0x1F
+# define ERR_REASON_MASK 0X7FFFFF
+
+/*
+ * Reason flags are defined pre-shifted to easily combine with the reason
+ * number.
+ */
+# define ERR_RFLAG_FATAL (0x1 << ERR_RFLAGS_OFFSET)
+# define ERR_RFLAG_COMMON (0x2 << ERR_RFLAGS_OFFSET)
+
+# define ERR_SYSTEM_ERROR(errcode) (((errcode) & ERR_SYSTEM_FLAG) != 0)
+
+static ossl_unused ossl_inline int ERR_GET_LIB(unsigned long errcode)
+{
+ if (ERR_SYSTEM_ERROR(errcode))
+ return ERR_LIB_SYS;
+ return (errcode >> ERR_LIB_OFFSET) & ERR_LIB_MASK;
+}
+
+static ossl_unused ossl_inline int ERR_GET_RFLAGS(unsigned long errcode)
+{
+ if (ERR_SYSTEM_ERROR(errcode))
+ return 0;
+ return errcode & (ERR_RFLAGS_MASK << ERR_RFLAGS_OFFSET);
+}
+
+static ossl_unused ossl_inline int ERR_GET_REASON(unsigned long errcode)
+{
+ if (ERR_SYSTEM_ERROR(errcode))
+ return errcode & ERR_SYSTEM_MASK;
+ return errcode & ERR_REASON_MASK;
+}
+
+static ossl_unused ossl_inline int ERR_FATAL_ERROR(unsigned long errcode)
+{
+ return (ERR_GET_RFLAGS(errcode) & ERR_RFLAG_FATAL) != 0;
+}
+
+static ossl_unused ossl_inline int ERR_COMMON_ERROR(unsigned long errcode)
+{
+ return (ERR_GET_RFLAGS(errcode) & ERR_RFLAG_COMMON) != 0;
+}
+
+/*
+ * ERR_PACK is a helper macro to properly pack OpenSSL error codes and may
+ * only be used for that purpose. System errors are packed internally.
+ * ERR_PACK takes reason flags and reason code combined in |reason|.
+ * ERR_PACK ignores |func|, that parameter is just legacy from pre-3.0 OpenSSL.
+ */
+# define ERR_PACK(lib,func,reason) \
+ ( (((unsigned long)(lib) & ERR_LIB_MASK ) << ERR_LIB_OFFSET) | \
+ (((unsigned long)(reason) & ERR_REASON_MASK)) )
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SYS_F_FOPEN 0
+# define SYS_F_CONNECT 0
+# define SYS_F_GETSERVBYNAME 0
+# define SYS_F_SOCKET 0
+# define SYS_F_IOCTLSOCKET 0
+# define SYS_F_BIND 0
+# define SYS_F_LISTEN 0
+# define SYS_F_ACCEPT 0
+# define SYS_F_WSASTARTUP 0
+# define SYS_F_OPENDIR 0
+# define SYS_F_FREAD 0
+# define SYS_F_GETADDRINFO 0
+# define SYS_F_GETNAMEINFO 0
+# define SYS_F_SETSOCKOPT 0
+# define SYS_F_GETSOCKOPT 0
+# define SYS_F_GETSOCKNAME 0
+# define SYS_F_GETHOSTBYNAME 0
+# define SYS_F_FFLUSH 0
+# define SYS_F_OPEN 0
+# define SYS_F_CLOSE 0
+# define SYS_F_IOCTL 0
+# define SYS_F_STAT 0
+# define SYS_F_FCNTL 0
+# define SYS_F_FSTAT 0
+# define SYS_F_SENDFILE 0
+# endif
+
+/*
+ * All ERR_R_ codes must be combined with ERR_RFLAG_COMMON.
+ */
+
+/* "we came from here" global reason codes, range 1..255 */
+# define ERR_R_SYS_LIB (ERR_LIB_SYS/* 2 */ | ERR_RFLAG_COMMON)
+# define ERR_R_BN_LIB (ERR_LIB_BN/* 3 */ | ERR_RFLAG_COMMON)
+# define ERR_R_RSA_LIB (ERR_LIB_RSA/* 4 */ | ERR_RFLAG_COMMON)
+# define ERR_R_DH_LIB (ERR_LIB_DH/* 5 */ | ERR_RFLAG_COMMON)
+# define ERR_R_EVP_LIB (ERR_LIB_EVP/* 6 */ | ERR_RFLAG_COMMON)
+# define ERR_R_BUF_LIB (ERR_LIB_BUF/* 7 */ | ERR_RFLAG_COMMON)
+# define ERR_R_OBJ_LIB (ERR_LIB_OBJ/* 8 */ | ERR_RFLAG_COMMON)
+# define ERR_R_PEM_LIB (ERR_LIB_PEM/* 9 */ | ERR_RFLAG_COMMON)
+# define ERR_R_DSA_LIB (ERR_LIB_DSA/* 10 */ | ERR_RFLAG_COMMON)
+# define ERR_R_X509_LIB (ERR_LIB_X509/* 11 */ | ERR_RFLAG_COMMON)
+# define ERR_R_ASN1_LIB (ERR_LIB_ASN1/* 13 */ | ERR_RFLAG_COMMON)
+# define ERR_R_CRYPTO_LIB (ERR_LIB_CRYPTO/* 15 */ | ERR_RFLAG_COMMON)
+# define ERR_R_EC_LIB (ERR_LIB_EC/* 16 */ | ERR_RFLAG_COMMON)
+# define ERR_R_BIO_LIB (ERR_LIB_BIO/* 32 */ | ERR_RFLAG_COMMON)
+# define ERR_R_PKCS7_LIB (ERR_LIB_PKCS7/* 33 */ | ERR_RFLAG_COMMON)
+# define ERR_R_X509V3_LIB (ERR_LIB_X509V3/* 34 */ | ERR_RFLAG_COMMON)
+# define ERR_R_ENGINE_LIB (ERR_LIB_ENGINE/* 38 */ | ERR_RFLAG_COMMON)
+# define ERR_R_UI_LIB (ERR_LIB_UI/* 40 */ | ERR_RFLAG_COMMON)
+# define ERR_R_ECDSA_LIB (ERR_LIB_ECDSA/* 42 */ | ERR_RFLAG_COMMON)
+# define ERR_R_OSSL_STORE_LIB (ERR_LIB_OSSL_STORE/* 44 */ | ERR_RFLAG_COMMON)
+# define ERR_R_OSSL_DECODER_LIB (ERR_LIB_OSSL_DECODER/* 60 */ | ERR_RFLAG_COMMON)
+
+/* Other common error codes, range 256..2^ERR_RFLAGS_OFFSET-1 */
+# define ERR_R_FATAL (ERR_RFLAG_FATAL|ERR_RFLAG_COMMON)
+# define ERR_R_MALLOC_FAILURE (256|ERR_R_FATAL)
+# define ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED (257|ERR_R_FATAL)
+# define ERR_R_PASSED_NULL_PARAMETER (258|ERR_R_FATAL)
+# define ERR_R_INTERNAL_ERROR (259|ERR_R_FATAL)
+# define ERR_R_DISABLED (260|ERR_R_FATAL)
+# define ERR_R_INIT_FAIL (261|ERR_R_FATAL)
+# define ERR_R_PASSED_INVALID_ARGUMENT (262|ERR_RFLAG_COMMON)
+# define ERR_R_OPERATION_FAIL (263|ERR_R_FATAL)
+# define ERR_R_INVALID_PROVIDER_FUNCTIONS (264|ERR_R_FATAL)
+# define ERR_R_INTERRUPTED_OR_CANCELLED (265|ERR_RFLAG_COMMON)
+# define ERR_R_NESTED_ASN1_ERROR (266|ERR_RFLAG_COMMON)
+# define ERR_R_MISSING_ASN1_EOS (267|ERR_RFLAG_COMMON)
+# define ERR_R_UNSUPPORTED (268|ERR_RFLAG_COMMON)
+# define ERR_R_FETCH_FAILED (269|ERR_RFLAG_COMMON)
+# define ERR_R_INVALID_PROPERTY_DEFINITION (270|ERR_RFLAG_COMMON)
+# define ERR_R_UNABLE_TO_GET_READ_LOCK (271|ERR_R_FATAL)
+# define ERR_R_UNABLE_TO_GET_WRITE_LOCK (272|ERR_R_FATAL)
+
+typedef struct ERR_string_data_st {
+ unsigned long error;
+ const char *string;
+} ERR_STRING_DATA;
+
+{-
+ generate_lhash_macros("ERR_STRING_DATA");
+-}
+
+/* 12 lines and some on an 80 column terminal */
+#define ERR_MAX_DATA_SIZE 1024
+
+/* Building blocks */
+void ERR_new(void);
+void ERR_set_debug(const char *file, int line, const char *func);
+void ERR_set_error(int lib, int reason, const char *fmt, ...);
+void ERR_vset_error(int lib, int reason, const char *fmt, va_list args);
+
+/* Main error raising functions */
+# define ERR_raise(lib, reason) ERR_raise_data((lib),(reason),NULL)
+# define ERR_raise_data \
+ (ERR_new(), \
+ ERR_set_debug(OPENSSL_FILE,OPENSSL_LINE,OPENSSL_FUNC), \
+ ERR_set_error)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* Backward compatibility */
+# define ERR_put_error(lib, func, reason, file, line) \
+ (ERR_new(), \
+ ERR_set_debug((file), (line), OPENSSL_FUNC), \
+ ERR_set_error((lib), (reason), NULL))
+# endif
+
+void ERR_set_error_data(char *data, int flags);
+
+unsigned long ERR_get_error(void);
+unsigned long ERR_get_error_all(const char **file, int *line,
+ const char **func,
+ const char **data, int *flags);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_get_error_line(const char **file, int *line);
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_get_error_line_data(const char **file, int *line,
+ const char **data, int *flags);
+#endif
+unsigned long ERR_peek_error(void);
+unsigned long ERR_peek_error_line(const char **file, int *line);
+unsigned long ERR_peek_error_func(const char **func);
+unsigned long ERR_peek_error_data(const char **data, int *flags);
+unsigned long ERR_peek_error_all(const char **file, int *line,
+ const char **func,
+ const char **data, int *flags);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_peek_error_line_data(const char **file, int *line,
+ const char **data, int *flags);
+# endif
+unsigned long ERR_peek_last_error(void);
+unsigned long ERR_peek_last_error_line(const char **file, int *line);
+unsigned long ERR_peek_last_error_func(const char **func);
+unsigned long ERR_peek_last_error_data(const char **data, int *flags);
+unsigned long ERR_peek_last_error_all(const char **file, int *line,
+ const char **func,
+ const char **data, int *flags);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+unsigned long ERR_peek_last_error_line_data(const char **file, int *line,
+ const char **data, int *flags);
+# endif
+
+void ERR_clear_error(void);
+
+char *ERR_error_string(unsigned long e, char *buf);
+void ERR_error_string_n(unsigned long e, char *buf, size_t len);
+const char *ERR_lib_error_string(unsigned long e);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *ERR_func_error_string(unsigned long e);
+# endif
+const char *ERR_reason_error_string(unsigned long e);
+
+void ERR_print_errors_cb(int (*cb) (const char *str, size_t len, void *u),
+ void *u);
+# ifndef OPENSSL_NO_STDIO
+void ERR_print_errors_fp(FILE *fp);
+# endif
+void ERR_print_errors(BIO *bp);
+
+void ERR_add_error_data(int num, ...);
+void ERR_add_error_vdata(int num, va_list args);
+void ERR_add_error_txt(const char *sepr, const char *txt);
+void ERR_add_error_mem_bio(const char *sep, BIO *bio);
+
+int ERR_load_strings(int lib, ERR_STRING_DATA *str);
+int ERR_load_strings_const(const ERR_STRING_DATA *str);
+int ERR_unload_strings(int lib, ERR_STRING_DATA *str);
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define ERR_load_crypto_strings() \
+ OPENSSL_init_crypto(OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL)
+# define ERR_free_strings() while(0) continue
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void ERR_remove_thread_state(void *);
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_1_0_0
+OSSL_DEPRECATEDIN_1_0_0 void ERR_remove_state(unsigned long pid);
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 ERR_STATE *ERR_get_state(void);
+#endif
+
+int ERR_get_next_error_library(void);
+
+int ERR_set_mark(void);
+int ERR_pop_to_mark(void);
+int ERR_clear_last_mark(void);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/ess.h b/include/openssl/ess.h
new file mode 100644
index 00000000..dad596a6
--- /dev/null
+++ b/include/openssl/ess.h
@@ -0,0 +1,128 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\ess.h.in
+ *
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_ESS_H
+# define OPENSSL_ESS_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# include <openssl/safestack.h>
+# include <openssl/x509.h>
+# include <openssl/esserr.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+
+typedef struct ESS_issuer_serial ESS_ISSUER_SERIAL;
+typedef struct ESS_cert_id ESS_CERT_ID;
+typedef struct ESS_signing_cert ESS_SIGNING_CERT;
+
+SKM_DEFINE_STACK_OF_INTERNAL(ESS_CERT_ID, ESS_CERT_ID, ESS_CERT_ID)
+#define sk_ESS_CERT_ID_num(sk) OPENSSL_sk_num(ossl_check_const_ESS_CERT_ID_sk_type(sk))
+#define sk_ESS_CERT_ID_value(sk, idx) ((ESS_CERT_ID *)OPENSSL_sk_value(ossl_check_const_ESS_CERT_ID_sk_type(sk), (idx)))
+#define sk_ESS_CERT_ID_new(cmp) ((STACK_OF(ESS_CERT_ID) *)OPENSSL_sk_new(ossl_check_ESS_CERT_ID_compfunc_type(cmp)))
+#define sk_ESS_CERT_ID_new_null() ((STACK_OF(ESS_CERT_ID) *)OPENSSL_sk_new_null())
+#define sk_ESS_CERT_ID_new_reserve(cmp, n) ((STACK_OF(ESS_CERT_ID) *)OPENSSL_sk_new_reserve(ossl_check_ESS_CERT_ID_compfunc_type(cmp), (n)))
+#define sk_ESS_CERT_ID_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ESS_CERT_ID_sk_type(sk), (n))
+#define sk_ESS_CERT_ID_free(sk) OPENSSL_sk_free(ossl_check_ESS_CERT_ID_sk_type(sk))
+#define sk_ESS_CERT_ID_zero(sk) OPENSSL_sk_zero(ossl_check_ESS_CERT_ID_sk_type(sk))
+#define sk_ESS_CERT_ID_delete(sk, i) ((ESS_CERT_ID *)OPENSSL_sk_delete(ossl_check_ESS_CERT_ID_sk_type(sk), (i)))
+#define sk_ESS_CERT_ID_delete_ptr(sk, ptr) ((ESS_CERT_ID *)OPENSSL_sk_delete_ptr(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_type(ptr)))
+#define sk_ESS_CERT_ID_push(sk, ptr) OPENSSL_sk_push(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_type(ptr))
+#define sk_ESS_CERT_ID_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_type(ptr))
+#define sk_ESS_CERT_ID_pop(sk) ((ESS_CERT_ID *)OPENSSL_sk_pop(ossl_check_ESS_CERT_ID_sk_type(sk)))
+#define sk_ESS_CERT_ID_shift(sk) ((ESS_CERT_ID *)OPENSSL_sk_shift(ossl_check_ESS_CERT_ID_sk_type(sk)))
+#define sk_ESS_CERT_ID_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ESS_CERT_ID_sk_type(sk),ossl_check_ESS_CERT_ID_freefunc_type(freefunc))
+#define sk_ESS_CERT_ID_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_type(ptr), (idx))
+#define sk_ESS_CERT_ID_set(sk, idx, ptr) ((ESS_CERT_ID *)OPENSSL_sk_set(ossl_check_ESS_CERT_ID_sk_type(sk), (idx), ossl_check_ESS_CERT_ID_type(ptr)))
+#define sk_ESS_CERT_ID_find(sk, ptr) OPENSSL_sk_find(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_type(ptr))
+#define sk_ESS_CERT_ID_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_type(ptr))
+#define sk_ESS_CERT_ID_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_type(ptr), pnum)
+#define sk_ESS_CERT_ID_sort(sk) OPENSSL_sk_sort(ossl_check_ESS_CERT_ID_sk_type(sk))
+#define sk_ESS_CERT_ID_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ESS_CERT_ID_sk_type(sk))
+#define sk_ESS_CERT_ID_dup(sk) ((STACK_OF(ESS_CERT_ID) *)OPENSSL_sk_dup(ossl_check_const_ESS_CERT_ID_sk_type(sk)))
+#define sk_ESS_CERT_ID_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ESS_CERT_ID) *)OPENSSL_sk_deep_copy(ossl_check_const_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_copyfunc_type(copyfunc), ossl_check_ESS_CERT_ID_freefunc_type(freefunc)))
+#define sk_ESS_CERT_ID_set_cmp_func(sk, cmp) ((sk_ESS_CERT_ID_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ESS_CERT_ID_sk_type(sk), ossl_check_ESS_CERT_ID_compfunc_type(cmp)))
+
+
+
+typedef struct ESS_signing_cert_v2_st ESS_SIGNING_CERT_V2;
+typedef struct ESS_cert_id_v2_st ESS_CERT_ID_V2;
+
+SKM_DEFINE_STACK_OF_INTERNAL(ESS_CERT_ID_V2, ESS_CERT_ID_V2, ESS_CERT_ID_V2)
+#define sk_ESS_CERT_ID_V2_num(sk) OPENSSL_sk_num(ossl_check_const_ESS_CERT_ID_V2_sk_type(sk))
+#define sk_ESS_CERT_ID_V2_value(sk, idx) ((ESS_CERT_ID_V2 *)OPENSSL_sk_value(ossl_check_const_ESS_CERT_ID_V2_sk_type(sk), (idx)))
+#define sk_ESS_CERT_ID_V2_new(cmp) ((STACK_OF(ESS_CERT_ID_V2) *)OPENSSL_sk_new(ossl_check_ESS_CERT_ID_V2_compfunc_type(cmp)))
+#define sk_ESS_CERT_ID_V2_new_null() ((STACK_OF(ESS_CERT_ID_V2) *)OPENSSL_sk_new_null())
+#define sk_ESS_CERT_ID_V2_new_reserve(cmp, n) ((STACK_OF(ESS_CERT_ID_V2) *)OPENSSL_sk_new_reserve(ossl_check_ESS_CERT_ID_V2_compfunc_type(cmp), (n)))
+#define sk_ESS_CERT_ID_V2_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ESS_CERT_ID_V2_sk_type(sk), (n))
+#define sk_ESS_CERT_ID_V2_free(sk) OPENSSL_sk_free(ossl_check_ESS_CERT_ID_V2_sk_type(sk))
+#define sk_ESS_CERT_ID_V2_zero(sk) OPENSSL_sk_zero(ossl_check_ESS_CERT_ID_V2_sk_type(sk))
+#define sk_ESS_CERT_ID_V2_delete(sk, i) ((ESS_CERT_ID_V2 *)OPENSSL_sk_delete(ossl_check_ESS_CERT_ID_V2_sk_type(sk), (i)))
+#define sk_ESS_CERT_ID_V2_delete_ptr(sk, ptr) ((ESS_CERT_ID_V2 *)OPENSSL_sk_delete_ptr(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_type(ptr)))
+#define sk_ESS_CERT_ID_V2_push(sk, ptr) OPENSSL_sk_push(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_type(ptr))
+#define sk_ESS_CERT_ID_V2_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_type(ptr))
+#define sk_ESS_CERT_ID_V2_pop(sk) ((ESS_CERT_ID_V2 *)OPENSSL_sk_pop(ossl_check_ESS_CERT_ID_V2_sk_type(sk)))
+#define sk_ESS_CERT_ID_V2_shift(sk) ((ESS_CERT_ID_V2 *)OPENSSL_sk_shift(ossl_check_ESS_CERT_ID_V2_sk_type(sk)))
+#define sk_ESS_CERT_ID_V2_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ESS_CERT_ID_V2_sk_type(sk),ossl_check_ESS_CERT_ID_V2_freefunc_type(freefunc))
+#define sk_ESS_CERT_ID_V2_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_type(ptr), (idx))
+#define sk_ESS_CERT_ID_V2_set(sk, idx, ptr) ((ESS_CERT_ID_V2 *)OPENSSL_sk_set(ossl_check_ESS_CERT_ID_V2_sk_type(sk), (idx), ossl_check_ESS_CERT_ID_V2_type(ptr)))
+#define sk_ESS_CERT_ID_V2_find(sk, ptr) OPENSSL_sk_find(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_type(ptr))
+#define sk_ESS_CERT_ID_V2_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_type(ptr))
+#define sk_ESS_CERT_ID_V2_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_type(ptr), pnum)
+#define sk_ESS_CERT_ID_V2_sort(sk) OPENSSL_sk_sort(ossl_check_ESS_CERT_ID_V2_sk_type(sk))
+#define sk_ESS_CERT_ID_V2_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ESS_CERT_ID_V2_sk_type(sk))
+#define sk_ESS_CERT_ID_V2_dup(sk) ((STACK_OF(ESS_CERT_ID_V2) *)OPENSSL_sk_dup(ossl_check_const_ESS_CERT_ID_V2_sk_type(sk)))
+#define sk_ESS_CERT_ID_V2_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ESS_CERT_ID_V2) *)OPENSSL_sk_deep_copy(ossl_check_const_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_copyfunc_type(copyfunc), ossl_check_ESS_CERT_ID_V2_freefunc_type(freefunc)))
+#define sk_ESS_CERT_ID_V2_set_cmp_func(sk, cmp) ((sk_ESS_CERT_ID_V2_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ESS_CERT_ID_V2_sk_type(sk), ossl_check_ESS_CERT_ID_V2_compfunc_type(cmp)))
+
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(ESS_ISSUER_SERIAL)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(ESS_ISSUER_SERIAL, ESS_ISSUER_SERIAL)
+DECLARE_ASN1_DUP_FUNCTION(ESS_ISSUER_SERIAL)
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(ESS_CERT_ID)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(ESS_CERT_ID, ESS_CERT_ID)
+DECLARE_ASN1_DUP_FUNCTION(ESS_CERT_ID)
+
+DECLARE_ASN1_FUNCTIONS(ESS_SIGNING_CERT)
+DECLARE_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT)
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(ESS_CERT_ID_V2)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(ESS_CERT_ID_V2, ESS_CERT_ID_V2)
+DECLARE_ASN1_DUP_FUNCTION(ESS_CERT_ID_V2)
+
+DECLARE_ASN1_FUNCTIONS(ESS_SIGNING_CERT_V2)
+DECLARE_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT_V2)
+
+ESS_SIGNING_CERT *OSSL_ESS_signing_cert_new_init(const X509 *signcert,
+ const STACK_OF(X509) *certs,
+ int set_issuer_serial);
+ESS_SIGNING_CERT_V2 *OSSL_ESS_signing_cert_v2_new_init(const EVP_MD *hash_alg,
+ const X509 *signcert,
+ const
+ STACK_OF(X509) *certs,
+ int set_issuer_serial);
+int OSSL_ESS_check_signing_certs(const ESS_SIGNING_CERT *ss,
+ const ESS_SIGNING_CERT_V2 *ssv2,
+ const STACK_OF(X509) *chain,
+ int require_signing_cert);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/ess.h.in b/include/openssl/ess.h.in
new file mode 100644
index 00000000..d1a685b9
--- /dev/null
+++ b/include/openssl/ess.h.in
@@ -0,0 +1,81 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_ESS_H
+# define OPENSSL_ESS_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# include <openssl/safestack.h>
+# include <openssl/x509.h>
+# include <openssl/esserr.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+
+typedef struct ESS_issuer_serial ESS_ISSUER_SERIAL;
+typedef struct ESS_cert_id ESS_CERT_ID;
+typedef struct ESS_signing_cert ESS_SIGNING_CERT;
+
+{-
+ generate_stack_macros("ESS_CERT_ID");
+-}
+
+
+typedef struct ESS_signing_cert_v2_st ESS_SIGNING_CERT_V2;
+typedef struct ESS_cert_id_v2_st ESS_CERT_ID_V2;
+
+{-
+ generate_stack_macros("ESS_CERT_ID_V2");
+-}
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(ESS_ISSUER_SERIAL)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(ESS_ISSUER_SERIAL, ESS_ISSUER_SERIAL)
+DECLARE_ASN1_DUP_FUNCTION(ESS_ISSUER_SERIAL)
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(ESS_CERT_ID)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(ESS_CERT_ID, ESS_CERT_ID)
+DECLARE_ASN1_DUP_FUNCTION(ESS_CERT_ID)
+
+DECLARE_ASN1_FUNCTIONS(ESS_SIGNING_CERT)
+DECLARE_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT)
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(ESS_CERT_ID_V2)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(ESS_CERT_ID_V2, ESS_CERT_ID_V2)
+DECLARE_ASN1_DUP_FUNCTION(ESS_CERT_ID_V2)
+
+DECLARE_ASN1_FUNCTIONS(ESS_SIGNING_CERT_V2)
+DECLARE_ASN1_DUP_FUNCTION(ESS_SIGNING_CERT_V2)
+
+ESS_SIGNING_CERT *OSSL_ESS_signing_cert_new_init(const X509 *signcert,
+ const STACK_OF(X509) *certs,
+ int set_issuer_serial);
+ESS_SIGNING_CERT_V2 *OSSL_ESS_signing_cert_v2_new_init(const EVP_MD *hash_alg,
+ const X509 *signcert,
+ const
+ STACK_OF(X509) *certs,
+ int set_issuer_serial);
+int OSSL_ESS_check_signing_certs(const ESS_SIGNING_CERT *ss,
+ const ESS_SIGNING_CERT_V2 *ssv2,
+ const STACK_OF(X509) *chain,
+ int require_signing_cert);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/esserr.h b/include/openssl/esserr.h
new file mode 100644
index 00000000..165ce7c4
--- /dev/null
+++ b/include/openssl/esserr.h
@@ -0,0 +1,32 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_ESSERR_H
+# define OPENSSL_ESSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+/*
+ * ESS reason codes.
+ */
+# define ESS_R_EMPTY_ESS_CERT_ID_LIST 107
+# define ESS_R_ESS_CERT_DIGEST_ERROR 103
+# define ESS_R_ESS_CERT_ID_NOT_FOUND 104
+# define ESS_R_ESS_CERT_ID_WRONG_ORDER 105
+# define ESS_R_ESS_DIGEST_ALG_UNKNOWN 106
+# define ESS_R_ESS_SIGNING_CERTIFICATE_ERROR 102
+# define ESS_R_ESS_SIGNING_CERT_ADD_ERROR 100
+# define ESS_R_ESS_SIGNING_CERT_V2_ADD_ERROR 101
+# define ESS_R_MISSING_SIGNING_CERTIFICATE_ATTRIBUTE 108
+
+#endif
diff --git a/include/openssl/evp.h b/include/openssl/evp.h
new file mode 100644
index 00000000..18503817
--- /dev/null
+++ b/include/openssl/evp.h
@@ -0,0 +1,2170 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_EVP_H
+# define OPENSSL_EVP_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_ENVELOPE_H
+# endif
+
+# include <stdarg.h>
+
+# ifndef OPENSSL_NO_STDIO
+# include <stdio.h>
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/types.h>
+# include <openssl/core.h>
+# include <openssl/core_dispatch.h>
+# include <openssl/symhacks.h>
+# include <openssl/bio.h>
+# include <openssl/evperr.h>
+# include <openssl/params.h>
+
+# define EVP_MAX_MD_SIZE 64/* longest known is SHA512 */
+# define EVP_MAX_KEY_LENGTH 64
+# define EVP_MAX_IV_LENGTH 16
+# define EVP_MAX_BLOCK_LENGTH 32
+
+# define PKCS5_SALT_LEN 8
+/* Default PKCS#5 iteration count */
+# define PKCS5_DEFAULT_ITER 2048
+
+# include <openssl/objects.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define EVP_PK_RSA 0x0001
+# define EVP_PK_DSA 0x0002
+# define EVP_PK_DH 0x0004
+# define EVP_PK_EC 0x0008
+# define EVP_PKT_SIGN 0x0010
+# define EVP_PKT_ENC 0x0020
+# define EVP_PKT_EXCH 0x0040
+# define EVP_PKS_RSA 0x0100
+# define EVP_PKS_DSA 0x0200
+# define EVP_PKS_EC 0x0400
+# endif
+
+# define EVP_PKEY_NONE NID_undef
+# define EVP_PKEY_RSA NID_rsaEncryption
+# define EVP_PKEY_RSA2 NID_rsa
+# define EVP_PKEY_RSA_PSS NID_rsassaPss
+# define EVP_PKEY_DSA NID_dsa
+# define EVP_PKEY_DSA1 NID_dsa_2
+# define EVP_PKEY_DSA2 NID_dsaWithSHA
+# define EVP_PKEY_DSA3 NID_dsaWithSHA1
+# define EVP_PKEY_DSA4 NID_dsaWithSHA1_2
+# define EVP_PKEY_DH NID_dhKeyAgreement
+# define EVP_PKEY_DHX NID_dhpublicnumber
+# define EVP_PKEY_EC NID_X9_62_id_ecPublicKey
+# define EVP_PKEY_SM2 NID_sm2
+# define EVP_PKEY_HMAC NID_hmac
+# define EVP_PKEY_CMAC NID_cmac
+# define EVP_PKEY_SCRYPT NID_id_scrypt
+# define EVP_PKEY_TLS1_PRF NID_tls1_prf
+# define EVP_PKEY_HKDF NID_hkdf
+# define EVP_PKEY_POLY1305 NID_poly1305
+# define EVP_PKEY_SIPHASH NID_siphash
+# define EVP_PKEY_X25519 NID_X25519
+# define EVP_PKEY_ED25519 NID_ED25519
+# define EVP_PKEY_X448 NID_X448
+# define EVP_PKEY_ED448 NID_ED448
+/* Special indicator that the object is uniquely provider side */
+# define EVP_PKEY_KEYMGMT -1
+
+/* Easy to use macros for EVP_PKEY related selections */
+# define EVP_PKEY_KEY_PARAMETERS \
+ ( OSSL_KEYMGMT_SELECT_ALL_PARAMETERS )
+# define EVP_PKEY_PUBLIC_KEY \
+ ( EVP_PKEY_KEY_PARAMETERS | OSSL_KEYMGMT_SELECT_PUBLIC_KEY )
+# define EVP_PKEY_KEYPAIR \
+ ( EVP_PKEY_PUBLIC_KEY | OSSL_KEYMGMT_SELECT_PRIVATE_KEY )
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+int EVP_set_default_properties(OSSL_LIB_CTX *libctx, const char *propq);
+int EVP_default_properties_is_fips_enabled(OSSL_LIB_CTX *libctx);
+int EVP_default_properties_enable_fips(OSSL_LIB_CTX *libctx, int enable);
+
+# define EVP_PKEY_MO_SIGN 0x0001
+# define EVP_PKEY_MO_VERIFY 0x0002
+# define EVP_PKEY_MO_ENCRYPT 0x0004
+# define EVP_PKEY_MO_DECRYPT 0x0008
+
+# ifndef EVP_MD
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 EVP_MD *EVP_MD_meth_new(int md_type, int pkey_type);
+OSSL_DEPRECATEDIN_3_0 EVP_MD *EVP_MD_meth_dup(const EVP_MD *md);
+OSSL_DEPRECATEDIN_3_0 void EVP_MD_meth_free(EVP_MD *md);
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_input_blocksize(EVP_MD *md, int blocksize);
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_result_size(EVP_MD *md, int resultsize);
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_app_datasize(EVP_MD *md, int datasize);
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_flags(EVP_MD *md, unsigned long flags);
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_init(EVP_MD *md, int (*init)(EVP_MD_CTX *ctx));
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_update(EVP_MD *md, int (*update)(EVP_MD_CTX *ctx,
+ const void *data,
+ size_t count));
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_final(EVP_MD *md, int (*final)(EVP_MD_CTX *ctx,
+ unsigned char *md));
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_copy(EVP_MD *md, int (*copy)(EVP_MD_CTX *to,
+ const EVP_MD_CTX *from));
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_cleanup(EVP_MD *md, int (*cleanup)(EVP_MD_CTX *ctx));
+OSSL_DEPRECATEDIN_3_0
+int EVP_MD_meth_set_ctrl(EVP_MD *md, int (*ctrl)(EVP_MD_CTX *ctx, int cmd,
+ int p1, void *p2));
+OSSL_DEPRECATEDIN_3_0 int EVP_MD_meth_get_input_blocksize(const EVP_MD *md);
+OSSL_DEPRECATEDIN_3_0 int EVP_MD_meth_get_result_size(const EVP_MD *md);
+OSSL_DEPRECATEDIN_3_0 int EVP_MD_meth_get_app_datasize(const EVP_MD *md);
+OSSL_DEPRECATEDIN_3_0 unsigned long EVP_MD_meth_get_flags(const EVP_MD *md);
+OSSL_DEPRECATEDIN_3_0
+int (*EVP_MD_meth_get_init(const EVP_MD *md))(EVP_MD_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0
+int (*EVP_MD_meth_get_update(const EVP_MD *md))(EVP_MD_CTX *ctx,
+ const void *data, size_t count);
+OSSL_DEPRECATEDIN_3_0
+int (*EVP_MD_meth_get_final(const EVP_MD *md))(EVP_MD_CTX *ctx,
+ unsigned char *md);
+OSSL_DEPRECATEDIN_3_0
+int (*EVP_MD_meth_get_copy(const EVP_MD *md))(EVP_MD_CTX *to,
+ const EVP_MD_CTX *from);
+OSSL_DEPRECATEDIN_3_0
+int (*EVP_MD_meth_get_cleanup(const EVP_MD *md))(EVP_MD_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0
+int (*EVP_MD_meth_get_ctrl(const EVP_MD *md))(EVP_MD_CTX *ctx, int cmd,
+ int p1, void *p2);
+# endif
+/* digest can only handle a single block */
+# define EVP_MD_FLAG_ONESHOT 0x0001
+
+/* digest is extensible-output function, XOF */
+# define EVP_MD_FLAG_XOF 0x0002
+
+/* DigestAlgorithmIdentifier flags... */
+
+# define EVP_MD_FLAG_DIGALGID_MASK 0x0018
+
+/* NULL or absent parameter accepted. Use NULL */
+
+# define EVP_MD_FLAG_DIGALGID_NULL 0x0000
+
+/* NULL or absent parameter accepted. Use NULL for PKCS#1 otherwise absent */
+
+# define EVP_MD_FLAG_DIGALGID_ABSENT 0x0008
+
+/* Custom handling via ctrl */
+
+# define EVP_MD_FLAG_DIGALGID_CUSTOM 0x0018
+
+/* Note if suitable for use in FIPS mode */
+# define EVP_MD_FLAG_FIPS 0x0400
+
+/* Digest ctrls */
+
+# define EVP_MD_CTRL_DIGALGID 0x1
+# define EVP_MD_CTRL_MICALG 0x2
+# define EVP_MD_CTRL_XOF_LEN 0x3
+# define EVP_MD_CTRL_TLSTREE 0x4
+
+/* Minimum Algorithm specific ctrl value */
+
+# define EVP_MD_CTRL_ALG_CTRL 0x1000
+
+# endif /* !EVP_MD */
+
+/* values for EVP_MD_CTX flags */
+
+# define EVP_MD_CTX_FLAG_ONESHOT 0x0001/* digest update will be
+ * called once only */
+# define EVP_MD_CTX_FLAG_CLEANED 0x0002/* context has already been
+ * cleaned */
+# define EVP_MD_CTX_FLAG_REUSE 0x0004/* Don't free up ctx->md_data
+ * in EVP_MD_CTX_reset */
+/*
+ * FIPS and pad options are ignored in 1.0.0, definitions are here so we
+ * don't accidentally reuse the values for other purposes.
+ */
+
+# define EVP_MD_CTX_FLAG_NON_FIPS_ALLOW 0x0008/* Allow use of non FIPS
+ * digest in FIPS mode */
+
+/*
+ * The following PAD options are also currently ignored in 1.0.0, digest
+ * parameters are handled through EVP_DigestSign*() and EVP_DigestVerify*()
+ * instead.
+ */
+# define EVP_MD_CTX_FLAG_PAD_MASK 0xF0/* RSA mode to use */
+# define EVP_MD_CTX_FLAG_PAD_PKCS1 0x00/* PKCS#1 v1.5 mode */
+# define EVP_MD_CTX_FLAG_PAD_X931 0x10/* X9.31 mode */
+# define EVP_MD_CTX_FLAG_PAD_PSS 0x20/* PSS mode */
+
+# define EVP_MD_CTX_FLAG_NO_INIT 0x0100/* Don't initialize md_data */
+/*
+ * Some functions such as EVP_DigestSign only finalise copies of internal
+ * contexts so additional data can be included after the finalisation call.
+ * This is inefficient if this functionality is not required: it is disabled
+ * if the following flag is set.
+ */
+# define EVP_MD_CTX_FLAG_FINALISE 0x0200
+/* NOTE: 0x0400 is reserved for internal usage */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+EVP_CIPHER *EVP_CIPHER_meth_new(int cipher_type, int block_size, int key_len);
+OSSL_DEPRECATEDIN_3_0
+EVP_CIPHER *EVP_CIPHER_meth_dup(const EVP_CIPHER *cipher);
+OSSL_DEPRECATEDIN_3_0
+void EVP_CIPHER_meth_free(EVP_CIPHER *cipher);
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_iv_length(EVP_CIPHER *cipher, int iv_len);
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_flags(EVP_CIPHER *cipher, unsigned long flags);
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_impl_ctx_size(EVP_CIPHER *cipher, int ctx_size);
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_init(EVP_CIPHER *cipher,
+ int (*init) (EVP_CIPHER_CTX *ctx,
+ const unsigned char *key,
+ const unsigned char *iv,
+ int enc));
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_do_cipher(EVP_CIPHER *cipher,
+ int (*do_cipher) (EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ size_t inl));
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_cleanup(EVP_CIPHER *cipher,
+ int (*cleanup) (EVP_CIPHER_CTX *));
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_set_asn1_params(EVP_CIPHER *cipher,
+ int (*set_asn1_parameters) (EVP_CIPHER_CTX *,
+ ASN1_TYPE *));
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_get_asn1_params(EVP_CIPHER *cipher,
+ int (*get_asn1_parameters) (EVP_CIPHER_CTX *,
+ ASN1_TYPE *));
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_meth_set_ctrl(EVP_CIPHER *cipher,
+ int (*ctrl) (EVP_CIPHER_CTX *, int type,
+ int arg, void *ptr));
+OSSL_DEPRECATEDIN_3_0 int
+(*EVP_CIPHER_meth_get_init(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx,
+ const unsigned char *key,
+ const unsigned char *iv,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 int
+(*EVP_CIPHER_meth_get_do_cipher(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *ctx,
+ unsigned char *out,
+ const unsigned char *in,
+ size_t inl);
+OSSL_DEPRECATEDIN_3_0 int
+(*EVP_CIPHER_meth_get_cleanup(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *);
+OSSL_DEPRECATEDIN_3_0 int
+(*EVP_CIPHER_meth_get_set_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *,
+ ASN1_TYPE *);
+OSSL_DEPRECATEDIN_3_0 int
+(*EVP_CIPHER_meth_get_get_asn1_params(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *,
+ ASN1_TYPE *);
+OSSL_DEPRECATEDIN_3_0 int
+(*EVP_CIPHER_meth_get_ctrl(const EVP_CIPHER *cipher))(EVP_CIPHER_CTX *, int type,
+ int arg, void *ptr);
+# endif
+
+/* Values for cipher flags */
+
+/* Modes for ciphers */
+
+# define EVP_CIPH_STREAM_CIPHER 0x0
+# define EVP_CIPH_ECB_MODE 0x1
+# define EVP_CIPH_CBC_MODE 0x2
+# define EVP_CIPH_CFB_MODE 0x3
+# define EVP_CIPH_OFB_MODE 0x4
+# define EVP_CIPH_CTR_MODE 0x5
+# define EVP_CIPH_GCM_MODE 0x6
+# define EVP_CIPH_CCM_MODE 0x7
+# define EVP_CIPH_XTS_MODE 0x10001
+# define EVP_CIPH_WRAP_MODE 0x10002
+# define EVP_CIPH_OCB_MODE 0x10003
+# define EVP_CIPH_SIV_MODE 0x10004
+# define EVP_CIPH_MODE 0xF0007
+/* Set if variable length cipher */
+# define EVP_CIPH_VARIABLE_LENGTH 0x8
+/* Set if the iv handling should be done by the cipher itself */
+# define EVP_CIPH_CUSTOM_IV 0x10
+/* Set if the cipher's init() function should be called if key is NULL */
+# define EVP_CIPH_ALWAYS_CALL_INIT 0x20
+/* Call ctrl() to init cipher parameters */
+# define EVP_CIPH_CTRL_INIT 0x40
+/* Don't use standard key length function */
+# define EVP_CIPH_CUSTOM_KEY_LENGTH 0x80
+/* Don't use standard block padding */
+# define EVP_CIPH_NO_PADDING 0x100
+/* cipher handles random key generation */
+# define EVP_CIPH_RAND_KEY 0x200
+/* cipher has its own additional copying logic */
+# define EVP_CIPH_CUSTOM_COPY 0x400
+/* Don't use standard iv length function */
+# define EVP_CIPH_CUSTOM_IV_LENGTH 0x800
+/* Legacy and no longer relevant: Allow use default ASN1 get/set iv */
+# define EVP_CIPH_FLAG_DEFAULT_ASN1 0
+/* Free: 0x1000 */
+/* Buffer length in bits not bytes: CFB1 mode only */
+# define EVP_CIPH_FLAG_LENGTH_BITS 0x2000
+/* Deprecated FIPS flag: was 0x4000 */
+# define EVP_CIPH_FLAG_FIPS 0
+/* Deprecated FIPS flag: was 0x8000 */
+# define EVP_CIPH_FLAG_NON_FIPS_ALLOW 0
+
+/*
+ * Cipher handles any and all padding logic as well as finalisation.
+ */
+# define EVP_CIPH_FLAG_CTS 0x4000
+# define EVP_CIPH_FLAG_CUSTOM_CIPHER 0x100000
+# define EVP_CIPH_FLAG_AEAD_CIPHER 0x200000
+# define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0x400000
+/* Cipher can handle pipeline operations */
+# define EVP_CIPH_FLAG_PIPELINE 0X800000
+/* For provider implementations that handle ASN1 get/set param themselves */
+# define EVP_CIPH_FLAG_CUSTOM_ASN1 0x1000000
+/* For ciphers generating unprotected CMS attributes */
+# define EVP_CIPH_FLAG_CIPHER_WITH_MAC 0x2000000
+/* For supplementary wrap cipher support */
+# define EVP_CIPH_FLAG_GET_WRAP_CIPHER 0x4000000
+# define EVP_CIPH_FLAG_INVERSE_CIPHER 0x8000000
+
+/*
+ * Cipher context flag to indicate we can handle wrap mode: if allowed in
+ * older applications it could overflow buffers.
+ */
+
+# define EVP_CIPHER_CTX_FLAG_WRAP_ALLOW 0x1
+
+/* ctrl() values */
+
+# define EVP_CTRL_INIT 0x0
+# define EVP_CTRL_SET_KEY_LENGTH 0x1
+# define EVP_CTRL_GET_RC2_KEY_BITS 0x2
+# define EVP_CTRL_SET_RC2_KEY_BITS 0x3
+# define EVP_CTRL_GET_RC5_ROUNDS 0x4
+# define EVP_CTRL_SET_RC5_ROUNDS 0x5
+# define EVP_CTRL_RAND_KEY 0x6
+# define EVP_CTRL_PBE_PRF_NID 0x7
+# define EVP_CTRL_COPY 0x8
+# define EVP_CTRL_AEAD_SET_IVLEN 0x9
+# define EVP_CTRL_AEAD_GET_TAG 0x10
+# define EVP_CTRL_AEAD_SET_TAG 0x11
+# define EVP_CTRL_AEAD_SET_IV_FIXED 0x12
+# define EVP_CTRL_GCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN
+# define EVP_CTRL_GCM_GET_TAG EVP_CTRL_AEAD_GET_TAG
+# define EVP_CTRL_GCM_SET_TAG EVP_CTRL_AEAD_SET_TAG
+# define EVP_CTRL_GCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED
+# define EVP_CTRL_GCM_IV_GEN 0x13
+# define EVP_CTRL_CCM_SET_IVLEN EVP_CTRL_AEAD_SET_IVLEN
+# define EVP_CTRL_CCM_GET_TAG EVP_CTRL_AEAD_GET_TAG
+# define EVP_CTRL_CCM_SET_TAG EVP_CTRL_AEAD_SET_TAG
+# define EVP_CTRL_CCM_SET_IV_FIXED EVP_CTRL_AEAD_SET_IV_FIXED
+# define EVP_CTRL_CCM_SET_L 0x14
+# define EVP_CTRL_CCM_SET_MSGLEN 0x15
+/*
+ * AEAD cipher deduces payload length and returns number of bytes required to
+ * store MAC and eventual padding. Subsequent call to EVP_Cipher even
+ * appends/verifies MAC.
+ */
+# define EVP_CTRL_AEAD_TLS1_AAD 0x16
+/* Used by composite AEAD ciphers, no-op in GCM, CCM... */
+# define EVP_CTRL_AEAD_SET_MAC_KEY 0x17
+/* Set the GCM invocation field, decrypt only */
+# define EVP_CTRL_GCM_SET_IV_INV 0x18
+
+# define EVP_CTRL_TLS1_1_MULTIBLOCK_AAD 0x19
+# define EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT 0x1a
+# define EVP_CTRL_TLS1_1_MULTIBLOCK_DECRYPT 0x1b
+# define EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE 0x1c
+
+# define EVP_CTRL_SSL3_MASTER_SECRET 0x1d
+
+/* EVP_CTRL_SET_SBOX takes the char * specifying S-boxes */
+# define EVP_CTRL_SET_SBOX 0x1e
+/*
+ * EVP_CTRL_SBOX_USED takes a 'size_t' and 'char *', pointing at a
+ * pre-allocated buffer with specified size
+ */
+# define EVP_CTRL_SBOX_USED 0x1f
+/* EVP_CTRL_KEY_MESH takes 'size_t' number of bytes to mesh the key after,
+ * 0 switches meshing off
+ */
+# define EVP_CTRL_KEY_MESH 0x20
+/* EVP_CTRL_BLOCK_PADDING_MODE takes the padding mode */
+# define EVP_CTRL_BLOCK_PADDING_MODE 0x21
+
+/* Set the output buffers to use for a pipelined operation */
+# define EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS 0x22
+/* Set the input buffers to use for a pipelined operation */
+# define EVP_CTRL_SET_PIPELINE_INPUT_BUFS 0x23
+/* Set the input buffer lengths to use for a pipelined operation */
+# define EVP_CTRL_SET_PIPELINE_INPUT_LENS 0x24
+/* Get the IV length used by the cipher */
+# define EVP_CTRL_GET_IVLEN 0x25
+/* 0x26 is unused */
+/* Tell the cipher it's doing a speed test (SIV disallows multiple ops) */
+# define EVP_CTRL_SET_SPEED 0x27
+/* Get the unprotectedAttrs from cipher ctx */
+# define EVP_CTRL_PROCESS_UNPROTECTED 0x28
+/* Get the supplementary wrap cipher */
+#define EVP_CTRL_GET_WRAP_CIPHER 0x29
+/* TLSTREE key diversification */
+#define EVP_CTRL_TLSTREE 0x2A
+
+/* Padding modes */
+#define EVP_PADDING_PKCS7 1
+#define EVP_PADDING_ISO7816_4 2
+#define EVP_PADDING_ANSI923 3
+#define EVP_PADDING_ISO10126 4
+#define EVP_PADDING_ZERO 5
+
+/* RFC 5246 defines additional data to be 13 bytes in length */
+# define EVP_AEAD_TLS1_AAD_LEN 13
+
+typedef struct {
+ unsigned char *out;
+ const unsigned char *inp;
+ size_t len;
+ unsigned int interleave;
+} EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM;
+
+/* GCM TLS constants */
+/* Length of fixed part of IV derived from PRF */
+# define EVP_GCM_TLS_FIXED_IV_LEN 4
+/* Length of explicit part of IV part of TLS records */
+# define EVP_GCM_TLS_EXPLICIT_IV_LEN 8
+/* Length of tag for TLS */
+# define EVP_GCM_TLS_TAG_LEN 16
+
+/* CCM TLS constants */
+/* Length of fixed part of IV derived from PRF */
+# define EVP_CCM_TLS_FIXED_IV_LEN 4
+/* Length of explicit part of IV part of TLS records */
+# define EVP_CCM_TLS_EXPLICIT_IV_LEN 8
+/* Total length of CCM IV length for TLS */
+# define EVP_CCM_TLS_IV_LEN 12
+/* Length of tag for TLS */
+# define EVP_CCM_TLS_TAG_LEN 16
+/* Length of CCM8 tag for TLS */
+# define EVP_CCM8_TLS_TAG_LEN 8
+
+/* Length of tag for TLS */
+# define EVP_CHACHAPOLY_TLS_TAG_LEN 16
+
+typedef struct evp_cipher_info_st {
+ const EVP_CIPHER *cipher;
+ unsigned char iv[EVP_MAX_IV_LENGTH];
+} EVP_CIPHER_INFO;
+
+
+/* Password based encryption function */
+typedef int (EVP_PBE_KEYGEN) (EVP_CIPHER_CTX *ctx, const char *pass,
+ int passlen, ASN1_TYPE *param,
+ const EVP_CIPHER *cipher, const EVP_MD *md,
+ int en_de);
+
+typedef int (EVP_PBE_KEYGEN_EX) (EVP_CIPHER_CTX *ctx, const char *pass,
+ int passlen, ASN1_TYPE *param,
+ const EVP_CIPHER *cipher, const EVP_MD *md,
+ int en_de, OSSL_LIB_CTX *libctx, const char *propq);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define EVP_PKEY_assign_RSA(pkey,rsa) EVP_PKEY_assign((pkey),EVP_PKEY_RSA,\
+ (rsa))
+# endif
+
+# ifndef OPENSSL_NO_DSA
+# define EVP_PKEY_assign_DSA(pkey,dsa) EVP_PKEY_assign((pkey),EVP_PKEY_DSA,\
+ (dsa))
+# endif
+
+# if !defined(OPENSSL_NO_DH) && !defined(OPENSSL_NO_DEPRECATED_3_0)
+# define EVP_PKEY_assign_DH(pkey,dh) EVP_PKEY_assign((pkey),EVP_PKEY_DH,(dh))
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+# define EVP_PKEY_assign_EC_KEY(pkey,eckey) \
+ EVP_PKEY_assign((pkey), EVP_PKEY_EC, (eckey))
+# endif
+# endif
+# ifndef OPENSSL_NO_SIPHASH
+# define EVP_PKEY_assign_SIPHASH(pkey,shkey) EVP_PKEY_assign((pkey),\
+ EVP_PKEY_SIPHASH,(shkey))
+# endif
+
+# ifndef OPENSSL_NO_POLY1305
+# define EVP_PKEY_assign_POLY1305(pkey,polykey) EVP_PKEY_assign((pkey),\
+ EVP_PKEY_POLY1305,(polykey))
+# endif
+
+/* Add some extra combinations */
+# define EVP_get_digestbynid(a) EVP_get_digestbyname(OBJ_nid2sn(a))
+# define EVP_get_digestbyobj(a) EVP_get_digestbynid(OBJ_obj2nid(a))
+# define EVP_get_cipherbynid(a) EVP_get_cipherbyname(OBJ_nid2sn(a))
+# define EVP_get_cipherbyobj(a) EVP_get_cipherbynid(OBJ_obj2nid(a))
+
+int EVP_MD_get_type(const EVP_MD *md);
+# define EVP_MD_type EVP_MD_get_type
+# define EVP_MD_nid EVP_MD_get_type
+const char *EVP_MD_get0_name(const EVP_MD *md);
+# define EVP_MD_name EVP_MD_get0_name
+const char *EVP_MD_get0_description(const EVP_MD *md);
+int EVP_MD_is_a(const EVP_MD *md, const char *name);
+int EVP_MD_names_do_all(const EVP_MD *md,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PROVIDER *EVP_MD_get0_provider(const EVP_MD *md);
+int EVP_MD_get_pkey_type(const EVP_MD *md);
+# define EVP_MD_pkey_type EVP_MD_get_pkey_type
+int EVP_MD_get_size(const EVP_MD *md);
+# define EVP_MD_size EVP_MD_get_size
+int EVP_MD_get_block_size(const EVP_MD *md);
+# define EVP_MD_block_size EVP_MD_get_block_size
+unsigned long EVP_MD_get_flags(const EVP_MD *md);
+# define EVP_MD_flags EVP_MD_get_flags
+
+const EVP_MD *EVP_MD_CTX_get0_md(const EVP_MD_CTX *ctx);
+EVP_MD *EVP_MD_CTX_get1_md(EVP_MD_CTX *ctx);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+const EVP_MD *EVP_MD_CTX_md(const EVP_MD_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0
+int (*EVP_MD_CTX_update_fn(EVP_MD_CTX *ctx))(EVP_MD_CTX *ctx,
+ const void *data, size_t count);
+OSSL_DEPRECATEDIN_3_0
+void EVP_MD_CTX_set_update_fn(EVP_MD_CTX *ctx,
+ int (*update) (EVP_MD_CTX *ctx,
+ const void *data, size_t count));
+# endif
+# define EVP_MD_CTX_get0_name(e) EVP_MD_get0_name(EVP_MD_CTX_get0_md(e))
+# define EVP_MD_CTX_get_size(e) EVP_MD_get_size(EVP_MD_CTX_get0_md(e))
+# define EVP_MD_CTX_size EVP_MD_CTX_get_size
+# define EVP_MD_CTX_get_block_size(e) EVP_MD_get_block_size(EVP_MD_CTX_get0_md(e))
+# define EVP_MD_CTX_block_size EVP_MD_CTX_get_block_size
+# define EVP_MD_CTX_get_type(e) EVP_MD_get_type(EVP_MD_CTX_get0_md(e))
+# define EVP_MD_CTX_type EVP_MD_CTX_get_type
+EVP_PKEY_CTX *EVP_MD_CTX_get_pkey_ctx(const EVP_MD_CTX *ctx);
+# define EVP_MD_CTX_pkey_ctx EVP_MD_CTX_get_pkey_ctx
+void EVP_MD_CTX_set_pkey_ctx(EVP_MD_CTX *ctx, EVP_PKEY_CTX *pctx);
+void *EVP_MD_CTX_get0_md_data(const EVP_MD_CTX *ctx);
+# define EVP_MD_CTX_md_data EVP_MD_CTX_get0_md_data
+
+int EVP_CIPHER_get_nid(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_nid EVP_CIPHER_get_nid
+const char *EVP_CIPHER_get0_name(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_name EVP_CIPHER_get0_name
+const char *EVP_CIPHER_get0_description(const EVP_CIPHER *cipher);
+int EVP_CIPHER_is_a(const EVP_CIPHER *cipher, const char *name);
+int EVP_CIPHER_names_do_all(const EVP_CIPHER *cipher,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PROVIDER *EVP_CIPHER_get0_provider(const EVP_CIPHER *cipher);
+int EVP_CIPHER_get_block_size(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_block_size EVP_CIPHER_get_block_size
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int EVP_CIPHER_impl_ctx_size(const EVP_CIPHER *cipher);
+# endif
+int EVP_CIPHER_get_key_length(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_key_length EVP_CIPHER_get_key_length
+int EVP_CIPHER_get_iv_length(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_iv_length EVP_CIPHER_get_iv_length
+unsigned long EVP_CIPHER_get_flags(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_flags EVP_CIPHER_get_flags
+int EVP_CIPHER_get_mode(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_mode EVP_CIPHER_get_mode
+int EVP_CIPHER_get_type(const EVP_CIPHER *cipher);
+# define EVP_CIPHER_type EVP_CIPHER_get_type
+EVP_CIPHER *EVP_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
+ const char *properties);
+int EVP_CIPHER_up_ref(EVP_CIPHER *cipher);
+void EVP_CIPHER_free(EVP_CIPHER *cipher);
+
+const EVP_CIPHER *EVP_CIPHER_CTX_get0_cipher(const EVP_CIPHER_CTX *ctx);
+EVP_CIPHER *EVP_CIPHER_CTX_get1_cipher(EVP_CIPHER_CTX *ctx);
+int EVP_CIPHER_CTX_is_encrypting(const EVP_CIPHER_CTX *ctx);
+# define EVP_CIPHER_CTX_encrypting EVP_CIPHER_CTX_is_encrypting
+int EVP_CIPHER_CTX_get_nid(const EVP_CIPHER_CTX *ctx);
+# define EVP_CIPHER_CTX_nid EVP_CIPHER_CTX_get_nid
+int EVP_CIPHER_CTX_get_block_size(const EVP_CIPHER_CTX *ctx);
+# define EVP_CIPHER_CTX_block_size EVP_CIPHER_CTX_get_block_size
+int EVP_CIPHER_CTX_get_key_length(const EVP_CIPHER_CTX *ctx);
+# define EVP_CIPHER_CTX_key_length EVP_CIPHER_CTX_get_key_length
+int EVP_CIPHER_CTX_get_iv_length(const EVP_CIPHER_CTX *ctx);
+# define EVP_CIPHER_CTX_iv_length EVP_CIPHER_CTX_get_iv_length
+int EVP_CIPHER_CTX_get_tag_length(const EVP_CIPHER_CTX *ctx);
+# define EVP_CIPHER_CTX_tag_length EVP_CIPHER_CTX_get_tag_length
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+const EVP_CIPHER *EVP_CIPHER_CTX_cipher(const EVP_CIPHER_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 const unsigned char *EVP_CIPHER_CTX_iv(const EVP_CIPHER_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 const unsigned char *EVP_CIPHER_CTX_original_iv(const EVP_CIPHER_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 unsigned char *EVP_CIPHER_CTX_iv_noconst(EVP_CIPHER_CTX *ctx);
+# endif
+int EVP_CIPHER_CTX_get_updated_iv(EVP_CIPHER_CTX *ctx, void *buf, size_t len);
+int EVP_CIPHER_CTX_get_original_iv(EVP_CIPHER_CTX *ctx, void *buf, size_t len);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+unsigned char *EVP_CIPHER_CTX_buf_noconst(EVP_CIPHER_CTX *ctx);
+# endif
+int EVP_CIPHER_CTX_get_num(const EVP_CIPHER_CTX *ctx);
+# define EVP_CIPHER_CTX_num EVP_CIPHER_CTX_get_num
+int EVP_CIPHER_CTX_set_num(EVP_CIPHER_CTX *ctx, int num);
+int EVP_CIPHER_CTX_copy(EVP_CIPHER_CTX *out, const EVP_CIPHER_CTX *in);
+void *EVP_CIPHER_CTX_get_app_data(const EVP_CIPHER_CTX *ctx);
+void EVP_CIPHER_CTX_set_app_data(EVP_CIPHER_CTX *ctx, void *data);
+void *EVP_CIPHER_CTX_get_cipher_data(const EVP_CIPHER_CTX *ctx);
+void *EVP_CIPHER_CTX_set_cipher_data(EVP_CIPHER_CTX *ctx, void *cipher_data);
+# define EVP_CIPHER_CTX_get0_name(c) EVP_CIPHER_get0_name(EVP_CIPHER_CTX_get0_cipher(c))
+# define EVP_CIPHER_CTX_get_type(c) EVP_CIPHER_get_type(EVP_CIPHER_CTX_get0_cipher(c))
+# define EVP_CIPHER_CTX_type EVP_CIPHER_CTX_get_type
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define EVP_CIPHER_CTX_flags(c) EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(c))
+# endif
+# define EVP_CIPHER_CTX_get_mode(c) EVP_CIPHER_get_mode(EVP_CIPHER_CTX_get0_cipher(c))
+# define EVP_CIPHER_CTX_mode EVP_CIPHER_CTX_get_mode
+
+# define EVP_ENCODE_LENGTH(l) ((((l)+2)/3*4)+((l)/48+1)*2+80)
+# define EVP_DECODE_LENGTH(l) (((l)+3)/4*3+80)
+
+# define EVP_SignInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c)
+# define EVP_SignInit(a,b) EVP_DigestInit(a,b)
+# define EVP_SignUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
+# define EVP_VerifyInit_ex(a,b,c) EVP_DigestInit_ex(a,b,c)
+# define EVP_VerifyInit(a,b) EVP_DigestInit(a,b)
+# define EVP_VerifyUpdate(a,b,c) EVP_DigestUpdate(a,b,c)
+# define EVP_OpenUpdate(a,b,c,d,e) EVP_DecryptUpdate(a,b,c,d,e)
+# define EVP_SealUpdate(a,b,c,d,e) EVP_EncryptUpdate(a,b,c,d,e)
+
+# ifdef CONST_STRICT
+void BIO_set_md(BIO *, const EVP_MD *md);
+# else
+# define BIO_set_md(b,md) BIO_ctrl(b,BIO_C_SET_MD,0,(void *)(md))
+# endif
+# define BIO_get_md(b,mdp) BIO_ctrl(b,BIO_C_GET_MD,0,(mdp))
+# define BIO_get_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_GET_MD_CTX,0,(mdcp))
+# define BIO_set_md_ctx(b,mdcp) BIO_ctrl(b,BIO_C_SET_MD_CTX,0,(mdcp))
+# define BIO_get_cipher_status(b) BIO_ctrl(b,BIO_C_GET_CIPHER_STATUS,0,NULL)
+# define BIO_get_cipher_ctx(b,c_pp) BIO_ctrl(b,BIO_C_GET_CIPHER_CTX,0,(c_pp))
+
+/*__owur*/ int EVP_Cipher(EVP_CIPHER_CTX *c,
+ unsigned char *out,
+ const unsigned char *in, unsigned int inl);
+
+# define EVP_add_cipher_alias(n,alias) \
+ OBJ_NAME_add((alias),OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS,(n))
+# define EVP_add_digest_alias(n,alias) \
+ OBJ_NAME_add((alias),OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS,(n))
+# define EVP_delete_cipher_alias(alias) \
+ OBJ_NAME_remove(alias,OBJ_NAME_TYPE_CIPHER_METH|OBJ_NAME_ALIAS);
+# define EVP_delete_digest_alias(alias) \
+ OBJ_NAME_remove(alias,OBJ_NAME_TYPE_MD_METH|OBJ_NAME_ALIAS);
+
+int EVP_MD_get_params(const EVP_MD *digest, OSSL_PARAM params[]);
+int EVP_MD_CTX_set_params(EVP_MD_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_MD_CTX_get_params(EVP_MD_CTX *ctx, OSSL_PARAM params[]);
+const OSSL_PARAM *EVP_MD_gettable_params(const EVP_MD *digest);
+const OSSL_PARAM *EVP_MD_settable_ctx_params(const EVP_MD *md);
+const OSSL_PARAM *EVP_MD_gettable_ctx_params(const EVP_MD *md);
+const OSSL_PARAM *EVP_MD_CTX_settable_params(EVP_MD_CTX *ctx);
+const OSSL_PARAM *EVP_MD_CTX_gettable_params(EVP_MD_CTX *ctx);
+int EVP_MD_CTX_ctrl(EVP_MD_CTX *ctx, int cmd, int p1, void *p2);
+EVP_MD_CTX *EVP_MD_CTX_new(void);
+int EVP_MD_CTX_reset(EVP_MD_CTX *ctx);
+void EVP_MD_CTX_free(EVP_MD_CTX *ctx);
+# define EVP_MD_CTX_create() EVP_MD_CTX_new()
+# define EVP_MD_CTX_init(ctx) EVP_MD_CTX_reset((ctx))
+# define EVP_MD_CTX_destroy(ctx) EVP_MD_CTX_free((ctx))
+__owur int EVP_MD_CTX_copy_ex(EVP_MD_CTX *out, const EVP_MD_CTX *in);
+void EVP_MD_CTX_set_flags(EVP_MD_CTX *ctx, int flags);
+void EVP_MD_CTX_clear_flags(EVP_MD_CTX *ctx, int flags);
+int EVP_MD_CTX_test_flags(const EVP_MD_CTX *ctx, int flags);
+__owur int EVP_DigestInit_ex2(EVP_MD_CTX *ctx, const EVP_MD *type,
+ const OSSL_PARAM params[]);
+__owur int EVP_DigestInit_ex(EVP_MD_CTX *ctx, const EVP_MD *type,
+ ENGINE *impl);
+__owur int EVP_DigestUpdate(EVP_MD_CTX *ctx, const void *d,
+ size_t cnt);
+__owur int EVP_DigestFinal_ex(EVP_MD_CTX *ctx, unsigned char *md,
+ unsigned int *s);
+__owur int EVP_Digest(const void *data, size_t count,
+ unsigned char *md, unsigned int *size,
+ const EVP_MD *type, ENGINE *impl);
+__owur int EVP_Q_digest(OSSL_LIB_CTX *libctx, const char *name,
+ const char *propq, const void *data, size_t datalen,
+ unsigned char *md, size_t *mdlen);
+
+__owur int EVP_MD_CTX_copy(EVP_MD_CTX *out, const EVP_MD_CTX *in);
+__owur int EVP_DigestInit(EVP_MD_CTX *ctx, const EVP_MD *type);
+__owur int EVP_DigestFinal(EVP_MD_CTX *ctx, unsigned char *md,
+ unsigned int *s);
+__owur int EVP_DigestFinalXOF(EVP_MD_CTX *ctx, unsigned char *md,
+ size_t len);
+
+__owur EVP_MD *EVP_MD_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
+ const char *properties);
+
+int EVP_MD_up_ref(EVP_MD *md);
+void EVP_MD_free(EVP_MD *md);
+
+int EVP_read_pw_string(char *buf, int length, const char *prompt, int verify);
+int EVP_read_pw_string_min(char *buf, int minlen, int maxlen,
+ const char *prompt, int verify);
+void EVP_set_pw_prompt(const char *prompt);
+char *EVP_get_pw_prompt(void);
+
+__owur int EVP_BytesToKey(const EVP_CIPHER *type, const EVP_MD *md,
+ const unsigned char *salt,
+ const unsigned char *data, int datal, int count,
+ unsigned char *key, unsigned char *iv);
+
+void EVP_CIPHER_CTX_set_flags(EVP_CIPHER_CTX *ctx, int flags);
+void EVP_CIPHER_CTX_clear_flags(EVP_CIPHER_CTX *ctx, int flags);
+int EVP_CIPHER_CTX_test_flags(const EVP_CIPHER_CTX *ctx, int flags);
+
+__owur int EVP_EncryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
+ const unsigned char *key, const unsigned char *iv);
+/*__owur*/ int EVP_EncryptInit_ex(EVP_CIPHER_CTX *ctx,
+ const EVP_CIPHER *cipher, ENGINE *impl,
+ const unsigned char *key,
+ const unsigned char *iv);
+__owur int EVP_EncryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
+ const unsigned char *key,
+ const unsigned char *iv,
+ const OSSL_PARAM params[]);
+/*__owur*/ int EVP_EncryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ int *outl, const unsigned char *in, int inl);
+/*__owur*/ int EVP_EncryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ int *outl);
+/*__owur*/ int EVP_EncryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ int *outl);
+
+__owur int EVP_DecryptInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
+ const unsigned char *key, const unsigned char *iv);
+/*__owur*/ int EVP_DecryptInit_ex(EVP_CIPHER_CTX *ctx,
+ const EVP_CIPHER *cipher, ENGINE *impl,
+ const unsigned char *key,
+ const unsigned char *iv);
+__owur int EVP_DecryptInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
+ const unsigned char *key,
+ const unsigned char *iv,
+ const OSSL_PARAM params[]);
+/*__owur*/ int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ int *outl, const unsigned char *in, int inl);
+__owur int EVP_DecryptFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm,
+ int *outl);
+/*__owur*/ int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm,
+ int *outl);
+
+__owur int EVP_CipherInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
+ const unsigned char *key, const unsigned char *iv,
+ int enc);
+/*__owur*/ int EVP_CipherInit_ex(EVP_CIPHER_CTX *ctx,
+ const EVP_CIPHER *cipher, ENGINE *impl,
+ const unsigned char *key,
+ const unsigned char *iv, int enc);
+__owur int EVP_CipherInit_ex2(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *cipher,
+ const unsigned char *key, const unsigned char *iv,
+ int enc, const OSSL_PARAM params[]);
+__owur int EVP_CipherUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
+ int *outl, const unsigned char *in, int inl);
+__owur int EVP_CipherFinal(EVP_CIPHER_CTX *ctx, unsigned char *outm,
+ int *outl);
+__owur int EVP_CipherFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm,
+ int *outl);
+
+__owur int EVP_SignFinal(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s,
+ EVP_PKEY *pkey);
+__owur int EVP_SignFinal_ex(EVP_MD_CTX *ctx, unsigned char *md, unsigned int *s,
+ EVP_PKEY *pkey, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+__owur int EVP_DigestSign(EVP_MD_CTX *ctx, unsigned char *sigret,
+ size_t *siglen, const unsigned char *tbs,
+ size_t tbslen);
+
+__owur int EVP_VerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sigbuf,
+ unsigned int siglen, EVP_PKEY *pkey);
+__owur int EVP_VerifyFinal_ex(EVP_MD_CTX *ctx, const unsigned char *sigbuf,
+ unsigned int siglen, EVP_PKEY *pkey,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+__owur int EVP_DigestVerify(EVP_MD_CTX *ctx, const unsigned char *sigret,
+ size_t siglen, const unsigned char *tbs,
+ size_t tbslen);
+
+int EVP_DigestSignInit_ex(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
+ const char *mdname, OSSL_LIB_CTX *libctx,
+ const char *props, EVP_PKEY *pkey,
+ const OSSL_PARAM params[]);
+/*__owur*/ int EVP_DigestSignInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
+ const EVP_MD *type, ENGINE *e,
+ EVP_PKEY *pkey);
+int EVP_DigestSignUpdate(EVP_MD_CTX *ctx, const void *data, size_t dsize);
+__owur int EVP_DigestSignFinal(EVP_MD_CTX *ctx, unsigned char *sigret,
+ size_t *siglen);
+
+int EVP_DigestVerifyInit_ex(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
+ const char *mdname, OSSL_LIB_CTX *libctx,
+ const char *props, EVP_PKEY *pkey,
+ const OSSL_PARAM params[]);
+__owur int EVP_DigestVerifyInit(EVP_MD_CTX *ctx, EVP_PKEY_CTX **pctx,
+ const EVP_MD *type, ENGINE *e,
+ EVP_PKEY *pkey);
+int EVP_DigestVerifyUpdate(EVP_MD_CTX *ctx, const void *data, size_t dsize);
+__owur int EVP_DigestVerifyFinal(EVP_MD_CTX *ctx, const unsigned char *sig,
+ size_t siglen);
+
+__owur int EVP_OpenInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
+ const unsigned char *ek, int ekl,
+ const unsigned char *iv, EVP_PKEY *priv);
+__owur int EVP_OpenFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
+
+__owur int EVP_SealInit(EVP_CIPHER_CTX *ctx, const EVP_CIPHER *type,
+ unsigned char **ek, int *ekl, unsigned char *iv,
+ EVP_PKEY **pubk, int npubk);
+__owur int EVP_SealFinal(EVP_CIPHER_CTX *ctx, unsigned char *out, int *outl);
+
+EVP_ENCODE_CTX *EVP_ENCODE_CTX_new(void);
+void EVP_ENCODE_CTX_free(EVP_ENCODE_CTX *ctx);
+int EVP_ENCODE_CTX_copy(EVP_ENCODE_CTX *dctx, const EVP_ENCODE_CTX *sctx);
+int EVP_ENCODE_CTX_num(EVP_ENCODE_CTX *ctx);
+void EVP_EncodeInit(EVP_ENCODE_CTX *ctx);
+int EVP_EncodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
+ const unsigned char *in, int inl);
+void EVP_EncodeFinal(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl);
+int EVP_EncodeBlock(unsigned char *t, const unsigned char *f, int n);
+
+void EVP_DecodeInit(EVP_ENCODE_CTX *ctx);
+int EVP_DecodeUpdate(EVP_ENCODE_CTX *ctx, unsigned char *out, int *outl,
+ const unsigned char *in, int inl);
+int EVP_DecodeFinal(EVP_ENCODE_CTX *ctx, unsigned
+ char *out, int *outl);
+int EVP_DecodeBlock(unsigned char *t, const unsigned char *f, int n);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define EVP_CIPHER_CTX_init(c) EVP_CIPHER_CTX_reset(c)
+# define EVP_CIPHER_CTX_cleanup(c) EVP_CIPHER_CTX_reset(c)
+# endif
+EVP_CIPHER_CTX *EVP_CIPHER_CTX_new(void);
+int EVP_CIPHER_CTX_reset(EVP_CIPHER_CTX *c);
+void EVP_CIPHER_CTX_free(EVP_CIPHER_CTX *c);
+int EVP_CIPHER_CTX_set_key_length(EVP_CIPHER_CTX *x, int keylen);
+int EVP_CIPHER_CTX_set_padding(EVP_CIPHER_CTX *c, int pad);
+int EVP_CIPHER_CTX_ctrl(EVP_CIPHER_CTX *ctx, int type, int arg, void *ptr);
+int EVP_CIPHER_CTX_rand_key(EVP_CIPHER_CTX *ctx, unsigned char *key);
+int EVP_CIPHER_get_params(EVP_CIPHER *cipher, OSSL_PARAM params[]);
+int EVP_CIPHER_CTX_set_params(EVP_CIPHER_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_CIPHER_CTX_get_params(EVP_CIPHER_CTX *ctx, OSSL_PARAM params[]);
+const OSSL_PARAM *EVP_CIPHER_gettable_params(const EVP_CIPHER *cipher);
+const OSSL_PARAM *EVP_CIPHER_settable_ctx_params(const EVP_CIPHER *cipher);
+const OSSL_PARAM *EVP_CIPHER_gettable_ctx_params(const EVP_CIPHER *cipher);
+const OSSL_PARAM *EVP_CIPHER_CTX_settable_params(EVP_CIPHER_CTX *ctx);
+const OSSL_PARAM *EVP_CIPHER_CTX_gettable_params(EVP_CIPHER_CTX *ctx);
+
+const BIO_METHOD *BIO_f_md(void);
+const BIO_METHOD *BIO_f_base64(void);
+const BIO_METHOD *BIO_f_cipher(void);
+const BIO_METHOD *BIO_f_reliable(void);
+__owur int BIO_set_cipher(BIO *b, const EVP_CIPHER *c, const unsigned char *k,
+ const unsigned char *i, int enc);
+
+const EVP_MD *EVP_md_null(void);
+# ifndef OPENSSL_NO_MD2
+const EVP_MD *EVP_md2(void);
+# endif
+# ifndef OPENSSL_NO_MD4
+const EVP_MD *EVP_md4(void);
+# endif
+# ifndef OPENSSL_NO_MD5
+const EVP_MD *EVP_md5(void);
+const EVP_MD *EVP_md5_sha1(void);
+# endif
+# ifndef OPENSSL_NO_BLAKE2
+const EVP_MD *EVP_blake2b512(void);
+const EVP_MD *EVP_blake2s256(void);
+# endif
+const EVP_MD *EVP_sha1(void);
+const EVP_MD *EVP_sha224(void);
+const EVP_MD *EVP_sha256(void);
+const EVP_MD *EVP_sha384(void);
+const EVP_MD *EVP_sha512(void);
+const EVP_MD *EVP_sha512_224(void);
+const EVP_MD *EVP_sha512_256(void);
+const EVP_MD *EVP_sha3_224(void);
+const EVP_MD *EVP_sha3_256(void);
+const EVP_MD *EVP_sha3_384(void);
+const EVP_MD *EVP_sha3_512(void);
+const EVP_MD *EVP_shake128(void);
+const EVP_MD *EVP_shake256(void);
+
+# ifndef OPENSSL_NO_MDC2
+const EVP_MD *EVP_mdc2(void);
+# endif
+# ifndef OPENSSL_NO_RMD160
+const EVP_MD *EVP_ripemd160(void);
+# endif
+# ifndef OPENSSL_NO_WHIRLPOOL
+const EVP_MD *EVP_whirlpool(void);
+# endif
+# ifndef OPENSSL_NO_SM3
+const EVP_MD *EVP_sm3(void);
+# endif
+const EVP_CIPHER *EVP_enc_null(void); /* does nothing :-) */
+# ifndef OPENSSL_NO_DES
+const EVP_CIPHER *EVP_des_ecb(void);
+const EVP_CIPHER *EVP_des_ede(void);
+const EVP_CIPHER *EVP_des_ede3(void);
+const EVP_CIPHER *EVP_des_ede_ecb(void);
+const EVP_CIPHER *EVP_des_ede3_ecb(void);
+const EVP_CIPHER *EVP_des_cfb64(void);
+# define EVP_des_cfb EVP_des_cfb64
+const EVP_CIPHER *EVP_des_cfb1(void);
+const EVP_CIPHER *EVP_des_cfb8(void);
+const EVP_CIPHER *EVP_des_ede_cfb64(void);
+# define EVP_des_ede_cfb EVP_des_ede_cfb64
+const EVP_CIPHER *EVP_des_ede3_cfb64(void);
+# define EVP_des_ede3_cfb EVP_des_ede3_cfb64
+const EVP_CIPHER *EVP_des_ede3_cfb1(void);
+const EVP_CIPHER *EVP_des_ede3_cfb8(void);
+const EVP_CIPHER *EVP_des_ofb(void);
+const EVP_CIPHER *EVP_des_ede_ofb(void);
+const EVP_CIPHER *EVP_des_ede3_ofb(void);
+const EVP_CIPHER *EVP_des_cbc(void);
+const EVP_CIPHER *EVP_des_ede_cbc(void);
+const EVP_CIPHER *EVP_des_ede3_cbc(void);
+const EVP_CIPHER *EVP_desx_cbc(void);
+const EVP_CIPHER *EVP_des_ede3_wrap(void);
+/*
+ * This should now be supported through the dev_crypto ENGINE. But also, why
+ * are rc4 and md5 declarations made here inside a "NO_DES" precompiler
+ * branch?
+ */
+# endif
+# ifndef OPENSSL_NO_RC4
+const EVP_CIPHER *EVP_rc4(void);
+const EVP_CIPHER *EVP_rc4_40(void);
+# ifndef OPENSSL_NO_MD5
+const EVP_CIPHER *EVP_rc4_hmac_md5(void);
+# endif
+# endif
+# ifndef OPENSSL_NO_IDEA
+const EVP_CIPHER *EVP_idea_ecb(void);
+const EVP_CIPHER *EVP_idea_cfb64(void);
+# define EVP_idea_cfb EVP_idea_cfb64
+const EVP_CIPHER *EVP_idea_ofb(void);
+const EVP_CIPHER *EVP_idea_cbc(void);
+# endif
+# ifndef OPENSSL_NO_RC2
+const EVP_CIPHER *EVP_rc2_ecb(void);
+const EVP_CIPHER *EVP_rc2_cbc(void);
+const EVP_CIPHER *EVP_rc2_40_cbc(void);
+const EVP_CIPHER *EVP_rc2_64_cbc(void);
+const EVP_CIPHER *EVP_rc2_cfb64(void);
+# define EVP_rc2_cfb EVP_rc2_cfb64
+const EVP_CIPHER *EVP_rc2_ofb(void);
+# endif
+# ifndef OPENSSL_NO_BF
+const EVP_CIPHER *EVP_bf_ecb(void);
+const EVP_CIPHER *EVP_bf_cbc(void);
+const EVP_CIPHER *EVP_bf_cfb64(void);
+# define EVP_bf_cfb EVP_bf_cfb64
+const EVP_CIPHER *EVP_bf_ofb(void);
+# endif
+# ifndef OPENSSL_NO_CAST
+const EVP_CIPHER *EVP_cast5_ecb(void);
+const EVP_CIPHER *EVP_cast5_cbc(void);
+const EVP_CIPHER *EVP_cast5_cfb64(void);
+# define EVP_cast5_cfb EVP_cast5_cfb64
+const EVP_CIPHER *EVP_cast5_ofb(void);
+# endif
+# ifndef OPENSSL_NO_RC5
+const EVP_CIPHER *EVP_rc5_32_12_16_cbc(void);
+const EVP_CIPHER *EVP_rc5_32_12_16_ecb(void);
+const EVP_CIPHER *EVP_rc5_32_12_16_cfb64(void);
+# define EVP_rc5_32_12_16_cfb EVP_rc5_32_12_16_cfb64
+const EVP_CIPHER *EVP_rc5_32_12_16_ofb(void);
+# endif
+const EVP_CIPHER *EVP_aes_128_ecb(void);
+const EVP_CIPHER *EVP_aes_128_cbc(void);
+const EVP_CIPHER *EVP_aes_128_cfb1(void);
+const EVP_CIPHER *EVP_aes_128_cfb8(void);
+const EVP_CIPHER *EVP_aes_128_cfb128(void);
+# define EVP_aes_128_cfb EVP_aes_128_cfb128
+const EVP_CIPHER *EVP_aes_128_ofb(void);
+const EVP_CIPHER *EVP_aes_128_ctr(void);
+const EVP_CIPHER *EVP_aes_128_ccm(void);
+const EVP_CIPHER *EVP_aes_128_gcm(void);
+const EVP_CIPHER *EVP_aes_128_xts(void);
+const EVP_CIPHER *EVP_aes_128_wrap(void);
+const EVP_CIPHER *EVP_aes_128_wrap_pad(void);
+# ifndef OPENSSL_NO_OCB
+const EVP_CIPHER *EVP_aes_128_ocb(void);
+# endif
+const EVP_CIPHER *EVP_aes_192_ecb(void);
+const EVP_CIPHER *EVP_aes_192_cbc(void);
+const EVP_CIPHER *EVP_aes_192_cfb1(void);
+const EVP_CIPHER *EVP_aes_192_cfb8(void);
+const EVP_CIPHER *EVP_aes_192_cfb128(void);
+# define EVP_aes_192_cfb EVP_aes_192_cfb128
+const EVP_CIPHER *EVP_aes_192_ofb(void);
+const EVP_CIPHER *EVP_aes_192_ctr(void);
+const EVP_CIPHER *EVP_aes_192_ccm(void);
+const EVP_CIPHER *EVP_aes_192_gcm(void);
+const EVP_CIPHER *EVP_aes_192_wrap(void);
+const EVP_CIPHER *EVP_aes_192_wrap_pad(void);
+# ifndef OPENSSL_NO_OCB
+const EVP_CIPHER *EVP_aes_192_ocb(void);
+# endif
+const EVP_CIPHER *EVP_aes_256_ecb(void);
+const EVP_CIPHER *EVP_aes_256_cbc(void);
+const EVP_CIPHER *EVP_aes_256_cfb1(void);
+const EVP_CIPHER *EVP_aes_256_cfb8(void);
+const EVP_CIPHER *EVP_aes_256_cfb128(void);
+# define EVP_aes_256_cfb EVP_aes_256_cfb128
+const EVP_CIPHER *EVP_aes_256_ofb(void);
+const EVP_CIPHER *EVP_aes_256_ctr(void);
+const EVP_CIPHER *EVP_aes_256_ccm(void);
+const EVP_CIPHER *EVP_aes_256_gcm(void);
+const EVP_CIPHER *EVP_aes_256_xts(void);
+const EVP_CIPHER *EVP_aes_256_wrap(void);
+const EVP_CIPHER *EVP_aes_256_wrap_pad(void);
+# ifndef OPENSSL_NO_OCB
+const EVP_CIPHER *EVP_aes_256_ocb(void);
+# endif
+const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha1(void);
+const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha1(void);
+const EVP_CIPHER *EVP_aes_128_cbc_hmac_sha256(void);
+const EVP_CIPHER *EVP_aes_256_cbc_hmac_sha256(void);
+# ifndef OPENSSL_NO_ARIA
+const EVP_CIPHER *EVP_aria_128_ecb(void);
+const EVP_CIPHER *EVP_aria_128_cbc(void);
+const EVP_CIPHER *EVP_aria_128_cfb1(void);
+const EVP_CIPHER *EVP_aria_128_cfb8(void);
+const EVP_CIPHER *EVP_aria_128_cfb128(void);
+# define EVP_aria_128_cfb EVP_aria_128_cfb128
+const EVP_CIPHER *EVP_aria_128_ctr(void);
+const EVP_CIPHER *EVP_aria_128_ofb(void);
+const EVP_CIPHER *EVP_aria_128_gcm(void);
+const EVP_CIPHER *EVP_aria_128_ccm(void);
+const EVP_CIPHER *EVP_aria_192_ecb(void);
+const EVP_CIPHER *EVP_aria_192_cbc(void);
+const EVP_CIPHER *EVP_aria_192_cfb1(void);
+const EVP_CIPHER *EVP_aria_192_cfb8(void);
+const EVP_CIPHER *EVP_aria_192_cfb128(void);
+# define EVP_aria_192_cfb EVP_aria_192_cfb128
+const EVP_CIPHER *EVP_aria_192_ctr(void);
+const EVP_CIPHER *EVP_aria_192_ofb(void);
+const EVP_CIPHER *EVP_aria_192_gcm(void);
+const EVP_CIPHER *EVP_aria_192_ccm(void);
+const EVP_CIPHER *EVP_aria_256_ecb(void);
+const EVP_CIPHER *EVP_aria_256_cbc(void);
+const EVP_CIPHER *EVP_aria_256_cfb1(void);
+const EVP_CIPHER *EVP_aria_256_cfb8(void);
+const EVP_CIPHER *EVP_aria_256_cfb128(void);
+# define EVP_aria_256_cfb EVP_aria_256_cfb128
+const EVP_CIPHER *EVP_aria_256_ctr(void);
+const EVP_CIPHER *EVP_aria_256_ofb(void);
+const EVP_CIPHER *EVP_aria_256_gcm(void);
+const EVP_CIPHER *EVP_aria_256_ccm(void);
+# endif
+# ifndef OPENSSL_NO_CAMELLIA
+const EVP_CIPHER *EVP_camellia_128_ecb(void);
+const EVP_CIPHER *EVP_camellia_128_cbc(void);
+const EVP_CIPHER *EVP_camellia_128_cfb1(void);
+const EVP_CIPHER *EVP_camellia_128_cfb8(void);
+const EVP_CIPHER *EVP_camellia_128_cfb128(void);
+# define EVP_camellia_128_cfb EVP_camellia_128_cfb128
+const EVP_CIPHER *EVP_camellia_128_ofb(void);
+const EVP_CIPHER *EVP_camellia_128_ctr(void);
+const EVP_CIPHER *EVP_camellia_192_ecb(void);
+const EVP_CIPHER *EVP_camellia_192_cbc(void);
+const EVP_CIPHER *EVP_camellia_192_cfb1(void);
+const EVP_CIPHER *EVP_camellia_192_cfb8(void);
+const EVP_CIPHER *EVP_camellia_192_cfb128(void);
+# define EVP_camellia_192_cfb EVP_camellia_192_cfb128
+const EVP_CIPHER *EVP_camellia_192_ofb(void);
+const EVP_CIPHER *EVP_camellia_192_ctr(void);
+const EVP_CIPHER *EVP_camellia_256_ecb(void);
+const EVP_CIPHER *EVP_camellia_256_cbc(void);
+const EVP_CIPHER *EVP_camellia_256_cfb1(void);
+const EVP_CIPHER *EVP_camellia_256_cfb8(void);
+const EVP_CIPHER *EVP_camellia_256_cfb128(void);
+# define EVP_camellia_256_cfb EVP_camellia_256_cfb128
+const EVP_CIPHER *EVP_camellia_256_ofb(void);
+const EVP_CIPHER *EVP_camellia_256_ctr(void);
+# endif
+# ifndef OPENSSL_NO_CHACHA
+const EVP_CIPHER *EVP_chacha20(void);
+# ifndef OPENSSL_NO_POLY1305
+const EVP_CIPHER *EVP_chacha20_poly1305(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_SEED
+const EVP_CIPHER *EVP_seed_ecb(void);
+const EVP_CIPHER *EVP_seed_cbc(void);
+const EVP_CIPHER *EVP_seed_cfb128(void);
+# define EVP_seed_cfb EVP_seed_cfb128
+const EVP_CIPHER *EVP_seed_ofb(void);
+# endif
+
+# ifndef OPENSSL_NO_SM4
+const EVP_CIPHER *EVP_sm4_ecb(void);
+const EVP_CIPHER *EVP_sm4_cbc(void);
+const EVP_CIPHER *EVP_sm4_cfb128(void);
+# define EVP_sm4_cfb EVP_sm4_cfb128
+const EVP_CIPHER *EVP_sm4_ofb(void);
+const EVP_CIPHER *EVP_sm4_ctr(void);
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OPENSSL_add_all_algorithms_conf() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \
+ | OPENSSL_INIT_ADD_ALL_DIGESTS \
+ | OPENSSL_INIT_LOAD_CONFIG, NULL)
+# define OPENSSL_add_all_algorithms_noconf() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS \
+ | OPENSSL_INIT_ADD_ALL_DIGESTS, NULL)
+
+# ifdef OPENSSL_LOAD_CONF
+# define OpenSSL_add_all_algorithms() OPENSSL_add_all_algorithms_conf()
+# else
+# define OpenSSL_add_all_algorithms() OPENSSL_add_all_algorithms_noconf()
+# endif
+
+# define OpenSSL_add_all_ciphers() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_CIPHERS, NULL)
+# define OpenSSL_add_all_digests() \
+ OPENSSL_init_crypto(OPENSSL_INIT_ADD_ALL_DIGESTS, NULL)
+
+# define EVP_cleanup() while(0) continue
+# endif
+
+int EVP_add_cipher(const EVP_CIPHER *cipher);
+int EVP_add_digest(const EVP_MD *digest);
+
+const EVP_CIPHER *EVP_get_cipherbyname(const char *name);
+const EVP_MD *EVP_get_digestbyname(const char *name);
+
+void EVP_CIPHER_do_all(void (*fn) (const EVP_CIPHER *ciph,
+ const char *from, const char *to, void *x),
+ void *arg);
+void EVP_CIPHER_do_all_sorted(void (*fn)
+ (const EVP_CIPHER *ciph, const char *from,
+ const char *to, void *x), void *arg);
+void EVP_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_CIPHER *cipher, void *arg),
+ void *arg);
+
+void EVP_MD_do_all(void (*fn) (const EVP_MD *ciph,
+ const char *from, const char *to, void *x),
+ void *arg);
+void EVP_MD_do_all_sorted(void (*fn)
+ (const EVP_MD *ciph, const char *from,
+ const char *to, void *x), void *arg);
+void EVP_MD_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_MD *md, void *arg),
+ void *arg);
+
+/* MAC stuff */
+
+EVP_MAC *EVP_MAC_fetch(OSSL_LIB_CTX *libctx, const char *algorithm,
+ const char *properties);
+int EVP_MAC_up_ref(EVP_MAC *mac);
+void EVP_MAC_free(EVP_MAC *mac);
+const char *EVP_MAC_get0_name(const EVP_MAC *mac);
+const char *EVP_MAC_get0_description(const EVP_MAC *mac);
+int EVP_MAC_is_a(const EVP_MAC *mac, const char *name);
+const OSSL_PROVIDER *EVP_MAC_get0_provider(const EVP_MAC *mac);
+int EVP_MAC_get_params(EVP_MAC *mac, OSSL_PARAM params[]);
+
+EVP_MAC_CTX *EVP_MAC_CTX_new(EVP_MAC *mac);
+void EVP_MAC_CTX_free(EVP_MAC_CTX *ctx);
+EVP_MAC_CTX *EVP_MAC_CTX_dup(const EVP_MAC_CTX *src);
+EVP_MAC *EVP_MAC_CTX_get0_mac(EVP_MAC_CTX *ctx);
+int EVP_MAC_CTX_get_params(EVP_MAC_CTX *ctx, OSSL_PARAM params[]);
+int EVP_MAC_CTX_set_params(EVP_MAC_CTX *ctx, const OSSL_PARAM params[]);
+
+size_t EVP_MAC_CTX_get_mac_size(EVP_MAC_CTX *ctx);
+size_t EVP_MAC_CTX_get_block_size(EVP_MAC_CTX *ctx);
+unsigned char *EVP_Q_mac(OSSL_LIB_CTX *libctx, const char *name, const char *propq,
+ const char *subalg, const OSSL_PARAM *params,
+ const void *key, size_t keylen,
+ const unsigned char *data, size_t datalen,
+ unsigned char *out, size_t outsize, size_t *outlen);
+int EVP_MAC_init(EVP_MAC_CTX *ctx, const unsigned char *key, size_t keylen,
+ const OSSL_PARAM params[]);
+int EVP_MAC_update(EVP_MAC_CTX *ctx, const unsigned char *data, size_t datalen);
+int EVP_MAC_final(EVP_MAC_CTX *ctx,
+ unsigned char *out, size_t *outl, size_t outsize);
+int EVP_MAC_finalXOF(EVP_MAC_CTX *ctx, unsigned char *out, size_t outsize);
+const OSSL_PARAM *EVP_MAC_gettable_params(const EVP_MAC *mac);
+const OSSL_PARAM *EVP_MAC_gettable_ctx_params(const EVP_MAC *mac);
+const OSSL_PARAM *EVP_MAC_settable_ctx_params(const EVP_MAC *mac);
+const OSSL_PARAM *EVP_MAC_CTX_gettable_params(EVP_MAC_CTX *ctx);
+const OSSL_PARAM *EVP_MAC_CTX_settable_params(EVP_MAC_CTX *ctx);
+
+void EVP_MAC_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_MAC *mac, void *arg),
+ void *arg);
+int EVP_MAC_names_do_all(const EVP_MAC *mac,
+ void (*fn)(const char *name, void *data),
+ void *data);
+
+/* RAND stuff */
+EVP_RAND *EVP_RAND_fetch(OSSL_LIB_CTX *libctx, const char *algorithm,
+ const char *properties);
+int EVP_RAND_up_ref(EVP_RAND *rand);
+void EVP_RAND_free(EVP_RAND *rand);
+const char *EVP_RAND_get0_name(const EVP_RAND *rand);
+const char *EVP_RAND_get0_description(const EVP_RAND *md);
+int EVP_RAND_is_a(const EVP_RAND *rand, const char *name);
+const OSSL_PROVIDER *EVP_RAND_get0_provider(const EVP_RAND *rand);
+int EVP_RAND_get_params(EVP_RAND *rand, OSSL_PARAM params[]);
+
+EVP_RAND_CTX *EVP_RAND_CTX_new(EVP_RAND *rand, EVP_RAND_CTX *parent);
+void EVP_RAND_CTX_free(EVP_RAND_CTX *ctx);
+EVP_RAND *EVP_RAND_CTX_get0_rand(EVP_RAND_CTX *ctx);
+int EVP_RAND_CTX_get_params(EVP_RAND_CTX *ctx, OSSL_PARAM params[]);
+int EVP_RAND_CTX_set_params(EVP_RAND_CTX *ctx, const OSSL_PARAM params[]);
+const OSSL_PARAM *EVP_RAND_gettable_params(const EVP_RAND *rand);
+const OSSL_PARAM *EVP_RAND_gettable_ctx_params(const EVP_RAND *rand);
+const OSSL_PARAM *EVP_RAND_settable_ctx_params(const EVP_RAND *rand);
+const OSSL_PARAM *EVP_RAND_CTX_gettable_params(EVP_RAND_CTX *ctx);
+const OSSL_PARAM *EVP_RAND_CTX_settable_params(EVP_RAND_CTX *ctx);
+
+void EVP_RAND_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_RAND *rand, void *arg),
+ void *arg);
+int EVP_RAND_names_do_all(const EVP_RAND *rand,
+ void (*fn)(const char *name, void *data),
+ void *data);
+
+__owur int EVP_RAND_instantiate(EVP_RAND_CTX *ctx, unsigned int strength,
+ int prediction_resistance,
+ const unsigned char *pstr, size_t pstr_len,
+ const OSSL_PARAM params[]);
+int EVP_RAND_uninstantiate(EVP_RAND_CTX *ctx);
+__owur int EVP_RAND_generate(EVP_RAND_CTX *ctx, unsigned char *out,
+ size_t outlen, unsigned int strength,
+ int prediction_resistance,
+ const unsigned char *addin, size_t addin_len);
+int EVP_RAND_reseed(EVP_RAND_CTX *ctx, int prediction_resistance,
+ const unsigned char *ent, size_t ent_len,
+ const unsigned char *addin, size_t addin_len);
+__owur int EVP_RAND_nonce(EVP_RAND_CTX *ctx, unsigned char *out, size_t outlen);
+__owur int EVP_RAND_enable_locking(EVP_RAND_CTX *ctx);
+
+int EVP_RAND_verify_zeroization(EVP_RAND_CTX *ctx);
+unsigned int EVP_RAND_get_strength(EVP_RAND_CTX *ctx);
+int EVP_RAND_get_state(EVP_RAND_CTX *ctx);
+
+# define EVP_RAND_STATE_UNINITIALISED 0
+# define EVP_RAND_STATE_READY 1
+# define EVP_RAND_STATE_ERROR 2
+
+/* PKEY stuff */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int EVP_PKEY_decrypt_old(unsigned char *dec_key,
+ const unsigned char *enc_key,
+ int enc_key_len,
+ EVP_PKEY *private_key);
+OSSL_DEPRECATEDIN_3_0 int EVP_PKEY_encrypt_old(unsigned char *enc_key,
+ const unsigned char *key,
+ int key_len, EVP_PKEY *pub_key);
+# endif
+int EVP_PKEY_is_a(const EVP_PKEY *pkey, const char *name);
+int EVP_PKEY_type_names_do_all(const EVP_PKEY *pkey,
+ void (*fn)(const char *name, void *data),
+ void *data);
+int EVP_PKEY_type(int type);
+int EVP_PKEY_get_id(const EVP_PKEY *pkey);
+# define EVP_PKEY_id EVP_PKEY_get_id
+int EVP_PKEY_get_base_id(const EVP_PKEY *pkey);
+# define EVP_PKEY_base_id EVP_PKEY_get_base_id
+int EVP_PKEY_get_bits(const EVP_PKEY *pkey);
+# define EVP_PKEY_bits EVP_PKEY_get_bits
+int EVP_PKEY_get_security_bits(const EVP_PKEY *pkey);
+# define EVP_PKEY_security_bits EVP_PKEY_get_security_bits
+int EVP_PKEY_get_size(const EVP_PKEY *pkey);
+# define EVP_PKEY_size EVP_PKEY_get_size
+int EVP_PKEY_can_sign(const EVP_PKEY *pkey);
+int EVP_PKEY_set_type(EVP_PKEY *pkey, int type);
+int EVP_PKEY_set_type_str(EVP_PKEY *pkey, const char *str, int len);
+int EVP_PKEY_set_type_by_keymgmt(EVP_PKEY *pkey, EVP_KEYMGMT *keymgmt);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_ENGINE
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_set1_engine(EVP_PKEY *pkey, ENGINE *e);
+OSSL_DEPRECATEDIN_3_0
+ENGINE *EVP_PKEY_get0_engine(const EVP_PKEY *pkey);
+# endif
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_assign(EVP_PKEY *pkey, int type, void *key);
+OSSL_DEPRECATEDIN_3_0
+void *EVP_PKEY_get0(const EVP_PKEY *pkey);
+OSSL_DEPRECATEDIN_3_0
+const unsigned char *EVP_PKEY_get0_hmac(const EVP_PKEY *pkey, size_t *len);
+# ifndef OPENSSL_NO_POLY1305
+OSSL_DEPRECATEDIN_3_0
+const unsigned char *EVP_PKEY_get0_poly1305(const EVP_PKEY *pkey, size_t *len);
+# endif
+# ifndef OPENSSL_NO_SIPHASH
+OSSL_DEPRECATEDIN_3_0
+const unsigned char *EVP_PKEY_get0_siphash(const EVP_PKEY *pkey, size_t *len);
+# endif
+
+struct rsa_st;
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_set1_RSA(EVP_PKEY *pkey, struct rsa_st *key);
+OSSL_DEPRECATEDIN_3_0
+const struct rsa_st *EVP_PKEY_get0_RSA(const EVP_PKEY *pkey);
+OSSL_DEPRECATEDIN_3_0
+struct rsa_st *EVP_PKEY_get1_RSA(EVP_PKEY *pkey);
+
+# ifndef OPENSSL_NO_DSA
+struct dsa_st;
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_set1_DSA(EVP_PKEY *pkey, struct dsa_st *key);
+OSSL_DEPRECATEDIN_3_0
+const struct dsa_st *EVP_PKEY_get0_DSA(const EVP_PKEY *pkey);
+OSSL_DEPRECATEDIN_3_0
+struct dsa_st *EVP_PKEY_get1_DSA(EVP_PKEY *pkey);
+# endif
+
+# ifndef OPENSSL_NO_DH
+struct dh_st;
+OSSL_DEPRECATEDIN_3_0 int EVP_PKEY_set1_DH(EVP_PKEY *pkey, struct dh_st *key);
+OSSL_DEPRECATEDIN_3_0 const struct dh_st *EVP_PKEY_get0_DH(const EVP_PKEY *pkey);
+OSSL_DEPRECATEDIN_3_0 struct dh_st *EVP_PKEY_get1_DH(EVP_PKEY *pkey);
+# endif
+
+# ifndef OPENSSL_NO_EC
+struct ec_key_st;
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_set1_EC_KEY(EVP_PKEY *pkey, struct ec_key_st *key);
+OSSL_DEPRECATEDIN_3_0
+const struct ec_key_st *EVP_PKEY_get0_EC_KEY(const EVP_PKEY *pkey);
+OSSL_DEPRECATEDIN_3_0
+struct ec_key_st *EVP_PKEY_get1_EC_KEY(EVP_PKEY *pkey);
+# endif
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+EVP_PKEY *EVP_PKEY_new(void);
+int EVP_PKEY_up_ref(EVP_PKEY *pkey);
+EVP_PKEY *EVP_PKEY_dup(EVP_PKEY *pkey);
+void EVP_PKEY_free(EVP_PKEY *pkey);
+const char *EVP_PKEY_get0_description(const EVP_PKEY *pkey);
+const OSSL_PROVIDER *EVP_PKEY_get0_provider(const EVP_PKEY *key);
+
+EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, const unsigned char **pp,
+ long length);
+int i2d_PublicKey(const EVP_PKEY *a, unsigned char **pp);
+
+
+EVP_PKEY *d2i_PrivateKey_ex(int type, EVP_PKEY **a, const unsigned char **pp,
+ long length, OSSL_LIB_CTX *libctx,
+ const char *propq);
+EVP_PKEY *d2i_PrivateKey(int type, EVP_PKEY **a, const unsigned char **pp,
+ long length);
+EVP_PKEY *d2i_AutoPrivateKey_ex(EVP_PKEY **a, const unsigned char **pp,
+ long length, OSSL_LIB_CTX *libctx,
+ const char *propq);
+EVP_PKEY *d2i_AutoPrivateKey(EVP_PKEY **a, const unsigned char **pp,
+ long length);
+int i2d_PrivateKey(const EVP_PKEY *a, unsigned char **pp);
+
+int i2d_KeyParams(const EVP_PKEY *a, unsigned char **pp);
+EVP_PKEY *d2i_KeyParams(int type, EVP_PKEY **a, const unsigned char **pp,
+ long length);
+int i2d_KeyParams_bio(BIO *bp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_KeyParams_bio(int type, EVP_PKEY **a, BIO *in);
+
+int EVP_PKEY_copy_parameters(EVP_PKEY *to, const EVP_PKEY *from);
+int EVP_PKEY_missing_parameters(const EVP_PKEY *pkey);
+int EVP_PKEY_save_parameters(EVP_PKEY *pkey, int mode);
+int EVP_PKEY_parameters_eq(const EVP_PKEY *a, const EVP_PKEY *b);
+int EVP_PKEY_eq(const EVP_PKEY *a, const EVP_PKEY *b);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_cmp_parameters(const EVP_PKEY *a, const EVP_PKEY *b);
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_cmp(const EVP_PKEY *a, const EVP_PKEY *b);
+# endif
+
+int EVP_PKEY_print_public(BIO *out, const EVP_PKEY *pkey,
+ int indent, ASN1_PCTX *pctx);
+int EVP_PKEY_print_private(BIO *out, const EVP_PKEY *pkey,
+ int indent, ASN1_PCTX *pctx);
+int EVP_PKEY_print_params(BIO *out, const EVP_PKEY *pkey,
+ int indent, ASN1_PCTX *pctx);
+# ifndef OPENSSL_NO_STDIO
+int EVP_PKEY_print_public_fp(FILE *fp, const EVP_PKEY *pkey,
+ int indent, ASN1_PCTX *pctx);
+int EVP_PKEY_print_private_fp(FILE *fp, const EVP_PKEY *pkey,
+ int indent, ASN1_PCTX *pctx);
+int EVP_PKEY_print_params_fp(FILE *fp, const EVP_PKEY *pkey,
+ int indent, ASN1_PCTX *pctx);
+# endif
+
+int EVP_PKEY_get_default_digest_nid(EVP_PKEY *pkey, int *pnid);
+int EVP_PKEY_get_default_digest_name(EVP_PKEY *pkey,
+ char *mdname, size_t mdname_sz);
+int EVP_PKEY_digestsign_supports_digest(EVP_PKEY *pkey, OSSL_LIB_CTX *libctx,
+ const char *name, const char *propq);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/*
+ * For backwards compatibility. Use EVP_PKEY_set1_encoded_public_key in
+ * preference
+ */
+# define EVP_PKEY_set1_tls_encodedpoint(pkey, pt, ptlen) \
+ EVP_PKEY_set1_encoded_public_key((pkey), (pt), (ptlen))
+# endif
+
+int EVP_PKEY_set1_encoded_public_key(EVP_PKEY *pkey,
+ const unsigned char *pub, size_t publen);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/*
+ * For backwards compatibility. Use EVP_PKEY_get1_encoded_public_key in
+ * preference
+ */
+# define EVP_PKEY_get1_tls_encodedpoint(pkey, ppt) \
+ EVP_PKEY_get1_encoded_public_key((pkey), (ppt))
+# endif
+
+size_t EVP_PKEY_get1_encoded_public_key(EVP_PKEY *pkey, unsigned char **ppub);
+
+/* calls methods */
+int EVP_CIPHER_param_to_asn1(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
+int EVP_CIPHER_asn1_to_param(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
+
+/* These are used by EVP_CIPHER methods */
+int EVP_CIPHER_set_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
+int EVP_CIPHER_get_asn1_iv(EVP_CIPHER_CTX *c, ASN1_TYPE *type);
+
+/* PKCS5 password based encryption */
+int PKCS5_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md, int en_de);
+int PKCS5_PBE_keyivgen_ex(EVP_CIPHER_CTX *cctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md, int en_de, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int PKCS5_PBKDF2_HMAC_SHA1(const char *pass, int passlen,
+ const unsigned char *salt, int saltlen, int iter,
+ int keylen, unsigned char *out);
+int PKCS5_PBKDF2_HMAC(const char *pass, int passlen,
+ const unsigned char *salt, int saltlen, int iter,
+ const EVP_MD *digest, int keylen, unsigned char *out);
+int PKCS5_v2_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md, int en_de);
+int PKCS5_v2_PBE_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md, int en_de,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+#ifndef OPENSSL_NO_SCRYPT
+int EVP_PBE_scrypt(const char *pass, size_t passlen,
+ const unsigned char *salt, size_t saltlen,
+ uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
+ unsigned char *key, size_t keylen);
+int EVP_PBE_scrypt_ex(const char *pass, size_t passlen,
+ const unsigned char *salt, size_t saltlen,
+ uint64_t N, uint64_t r, uint64_t p, uint64_t maxmem,
+ unsigned char *key, size_t keylen,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int PKCS5_v2_scrypt_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass,
+ int passlen, ASN1_TYPE *param,
+ const EVP_CIPHER *c, const EVP_MD *md, int en_de);
+int PKCS5_v2_scrypt_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass,
+ int passlen, ASN1_TYPE *param,
+ const EVP_CIPHER *c, const EVP_MD *md, int en_de,
+ OSSL_LIB_CTX *libctx, const char *propq);
+#endif
+
+void PKCS5_PBE_add(void);
+
+int EVP_PBE_CipherInit(ASN1_OBJECT *pbe_obj, const char *pass, int passlen,
+ ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de);
+
+int EVP_PBE_CipherInit_ex(ASN1_OBJECT *pbe_obj, const char *pass, int passlen,
+ ASN1_TYPE *param, EVP_CIPHER_CTX *ctx, int en_de,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+/* PBE type */
+
+/* Can appear as the outermost AlgorithmIdentifier */
+# define EVP_PBE_TYPE_OUTER 0x0
+/* Is an PRF type OID */
+# define EVP_PBE_TYPE_PRF 0x1
+/* Is a PKCS#5 v2.0 KDF */
+# define EVP_PBE_TYPE_KDF 0x2
+
+int EVP_PBE_alg_add_type(int pbe_type, int pbe_nid, int cipher_nid,
+ int md_nid, EVP_PBE_KEYGEN *keygen);
+int EVP_PBE_alg_add(int nid, const EVP_CIPHER *cipher, const EVP_MD *md,
+ EVP_PBE_KEYGEN *keygen);
+int EVP_PBE_find(int type, int pbe_nid, int *pcnid, int *pmnid,
+ EVP_PBE_KEYGEN **pkeygen);
+int EVP_PBE_find_ex(int type, int pbe_nid, int *pcnid, int *pmnid,
+ EVP_PBE_KEYGEN **pkeygen, EVP_PBE_KEYGEN_EX **pkeygen_ex);
+void EVP_PBE_cleanup(void);
+int EVP_PBE_get(int *ptype, int *ppbe_nid, size_t num);
+
+# define ASN1_PKEY_ALIAS 0x1
+# define ASN1_PKEY_DYNAMIC 0x2
+# define ASN1_PKEY_SIGPARAM_NULL 0x4
+
+# define ASN1_PKEY_CTRL_PKCS7_SIGN 0x1
+# define ASN1_PKEY_CTRL_PKCS7_ENCRYPT 0x2
+# define ASN1_PKEY_CTRL_DEFAULT_MD_NID 0x3
+# define ASN1_PKEY_CTRL_CMS_SIGN 0x5
+# define ASN1_PKEY_CTRL_CMS_ENVELOPE 0x7
+# define ASN1_PKEY_CTRL_CMS_RI_TYPE 0x8
+
+# define ASN1_PKEY_CTRL_SET1_TLS_ENCPT 0x9
+# define ASN1_PKEY_CTRL_GET1_TLS_ENCPT 0xa
+# define ASN1_PKEY_CTRL_CMS_IS_RI_TYPE_SUPPORTED 0xb
+
+int EVP_PKEY_asn1_get_count(void);
+const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_get0(int idx);
+const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find(ENGINE **pe, int type);
+const EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_find_str(ENGINE **pe,
+ const char *str, int len);
+int EVP_PKEY_asn1_add0(const EVP_PKEY_ASN1_METHOD *ameth);
+int EVP_PKEY_asn1_add_alias(int to, int from);
+int EVP_PKEY_asn1_get0_info(int *ppkey_id, int *pkey_base_id,
+ int *ppkey_flags, const char **pinfo,
+ const char **ppem_str,
+ const EVP_PKEY_ASN1_METHOD *ameth);
+
+const EVP_PKEY_ASN1_METHOD *EVP_PKEY_get0_asn1(const EVP_PKEY *pkey);
+EVP_PKEY_ASN1_METHOD *EVP_PKEY_asn1_new(int id, int flags,
+ const char *pem_str,
+ const char *info);
+void EVP_PKEY_asn1_copy(EVP_PKEY_ASN1_METHOD *dst,
+ const EVP_PKEY_ASN1_METHOD *src);
+void EVP_PKEY_asn1_free(EVP_PKEY_ASN1_METHOD *ameth);
+void EVP_PKEY_asn1_set_public(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*pub_decode) (EVP_PKEY *pk,
+ const X509_PUBKEY *pub),
+ int (*pub_encode) (X509_PUBKEY *pub,
+ const EVP_PKEY *pk),
+ int (*pub_cmp) (const EVP_PKEY *a,
+ const EVP_PKEY *b),
+ int (*pub_print) (BIO *out,
+ const EVP_PKEY *pkey,
+ int indent, ASN1_PCTX *pctx),
+ int (*pkey_size) (const EVP_PKEY *pk),
+ int (*pkey_bits) (const EVP_PKEY *pk));
+void EVP_PKEY_asn1_set_private(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*priv_decode) (EVP_PKEY *pk,
+ const PKCS8_PRIV_KEY_INFO
+ *p8inf),
+ int (*priv_encode) (PKCS8_PRIV_KEY_INFO *p8,
+ const EVP_PKEY *pk),
+ int (*priv_print) (BIO *out,
+ const EVP_PKEY *pkey,
+ int indent,
+ ASN1_PCTX *pctx));
+void EVP_PKEY_asn1_set_param(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*param_decode) (EVP_PKEY *pkey,
+ const unsigned char **pder,
+ int derlen),
+ int (*param_encode) (const EVP_PKEY *pkey,
+ unsigned char **pder),
+ int (*param_missing) (const EVP_PKEY *pk),
+ int (*param_copy) (EVP_PKEY *to,
+ const EVP_PKEY *from),
+ int (*param_cmp) (const EVP_PKEY *a,
+ const EVP_PKEY *b),
+ int (*param_print) (BIO *out,
+ const EVP_PKEY *pkey,
+ int indent,
+ ASN1_PCTX *pctx));
+
+void EVP_PKEY_asn1_set_free(EVP_PKEY_ASN1_METHOD *ameth,
+ void (*pkey_free) (EVP_PKEY *pkey));
+void EVP_PKEY_asn1_set_ctrl(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*pkey_ctrl) (EVP_PKEY *pkey, int op,
+ long arg1, void *arg2));
+void EVP_PKEY_asn1_set_item(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*item_verify) (EVP_MD_CTX *ctx,
+ const ASN1_ITEM *it,
+ const void *data,
+ const X509_ALGOR *a,
+ const ASN1_BIT_STRING *sig,
+ EVP_PKEY *pkey),
+ int (*item_sign) (EVP_MD_CTX *ctx,
+ const ASN1_ITEM *it,
+ const void *data,
+ X509_ALGOR *alg1,
+ X509_ALGOR *alg2,
+ ASN1_BIT_STRING *sig));
+
+void EVP_PKEY_asn1_set_siginf(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*siginf_set) (X509_SIG_INFO *siginf,
+ const X509_ALGOR *alg,
+ const ASN1_STRING *sig));
+
+void EVP_PKEY_asn1_set_check(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*pkey_check) (const EVP_PKEY *pk));
+
+void EVP_PKEY_asn1_set_public_check(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*pkey_pub_check) (const EVP_PKEY *pk));
+
+void EVP_PKEY_asn1_set_param_check(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*pkey_param_check) (const EVP_PKEY *pk));
+
+void EVP_PKEY_asn1_set_set_priv_key(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*set_priv_key) (EVP_PKEY *pk,
+ const unsigned char
+ *priv,
+ size_t len));
+void EVP_PKEY_asn1_set_set_pub_key(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*set_pub_key) (EVP_PKEY *pk,
+ const unsigned char *pub,
+ size_t len));
+void EVP_PKEY_asn1_set_get_priv_key(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*get_priv_key) (const EVP_PKEY *pk,
+ unsigned char *priv,
+ size_t *len));
+void EVP_PKEY_asn1_set_get_pub_key(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*get_pub_key) (const EVP_PKEY *pk,
+ unsigned char *pub,
+ size_t *len));
+
+void EVP_PKEY_asn1_set_security_bits(EVP_PKEY_ASN1_METHOD *ameth,
+ int (*pkey_security_bits) (const EVP_PKEY
+ *pk));
+
+int EVP_PKEY_CTX_get_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD **md);
+int EVP_PKEY_CTX_set_signature_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+
+int EVP_PKEY_CTX_set1_id(EVP_PKEY_CTX *ctx, const void *id, int len);
+int EVP_PKEY_CTX_get1_id(EVP_PKEY_CTX *ctx, void *id);
+int EVP_PKEY_CTX_get1_id_len(EVP_PKEY_CTX *ctx, size_t *id_len);
+
+int EVP_PKEY_CTX_set_kem_op(EVP_PKEY_CTX *ctx, const char *op);
+
+const char *EVP_PKEY_get0_type_name(const EVP_PKEY *key);
+
+# define EVP_PKEY_OP_UNDEFINED 0
+# define EVP_PKEY_OP_PARAMGEN (1<<1)
+# define EVP_PKEY_OP_KEYGEN (1<<2)
+# define EVP_PKEY_OP_FROMDATA (1<<3)
+# define EVP_PKEY_OP_SIGN (1<<4)
+# define EVP_PKEY_OP_VERIFY (1<<5)
+# define EVP_PKEY_OP_VERIFYRECOVER (1<<6)
+# define EVP_PKEY_OP_SIGNCTX (1<<7)
+# define EVP_PKEY_OP_VERIFYCTX (1<<8)
+# define EVP_PKEY_OP_ENCRYPT (1<<9)
+# define EVP_PKEY_OP_DECRYPT (1<<10)
+# define EVP_PKEY_OP_DERIVE (1<<11)
+# define EVP_PKEY_OP_ENCAPSULATE (1<<12)
+# define EVP_PKEY_OP_DECAPSULATE (1<<13)
+
+# define EVP_PKEY_OP_TYPE_SIG \
+ (EVP_PKEY_OP_SIGN | EVP_PKEY_OP_VERIFY | EVP_PKEY_OP_VERIFYRECOVER \
+ | EVP_PKEY_OP_SIGNCTX | EVP_PKEY_OP_VERIFYCTX)
+
+# define EVP_PKEY_OP_TYPE_CRYPT \
+ (EVP_PKEY_OP_ENCRYPT | EVP_PKEY_OP_DECRYPT)
+
+# define EVP_PKEY_OP_TYPE_NOGEN \
+ (EVP_PKEY_OP_TYPE_SIG | EVP_PKEY_OP_TYPE_CRYPT | EVP_PKEY_OP_DERIVE)
+
+# define EVP_PKEY_OP_TYPE_GEN \
+ (EVP_PKEY_OP_PARAMGEN | EVP_PKEY_OP_KEYGEN)
+
+
+int EVP_PKEY_CTX_set_mac_key(EVP_PKEY_CTX *ctx, const unsigned char *key,
+ int keylen);
+
+# define EVP_PKEY_CTRL_MD 1
+# define EVP_PKEY_CTRL_PEER_KEY 2
+# define EVP_PKEY_CTRL_SET_MAC_KEY 6
+# define EVP_PKEY_CTRL_DIGESTINIT 7
+/* Used by GOST key encryption in TLS */
+# define EVP_PKEY_CTRL_SET_IV 8
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define EVP_PKEY_CTRL_PKCS7_ENCRYPT 3
+# define EVP_PKEY_CTRL_PKCS7_DECRYPT 4
+# define EVP_PKEY_CTRL_PKCS7_SIGN 5
+# define EVP_PKEY_CTRL_CMS_ENCRYPT 9
+# define EVP_PKEY_CTRL_CMS_DECRYPT 10
+# define EVP_PKEY_CTRL_CMS_SIGN 11
+# endif
+# define EVP_PKEY_CTRL_CIPHER 12
+# define EVP_PKEY_CTRL_GET_MD 13
+# define EVP_PKEY_CTRL_SET_DIGEST_SIZE 14
+# define EVP_PKEY_CTRL_SET1_ID 15
+# define EVP_PKEY_CTRL_GET1_ID 16
+# define EVP_PKEY_CTRL_GET1_ID_LEN 17
+
+# define EVP_PKEY_ALG_CTRL 0x1000
+
+# define EVP_PKEY_FLAG_AUTOARGLEN 2
+/*
+ * Method handles all operations: don't assume any digest related defaults.
+ */
+# define EVP_PKEY_FLAG_SIGCTX_CUSTOM 4
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const EVP_PKEY_METHOD *EVP_PKEY_meth_find(int type);
+OSSL_DEPRECATEDIN_3_0 EVP_PKEY_METHOD *EVP_PKEY_meth_new(int id, int flags);
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get0_info(int *ppkey_id, int *pflags,
+ const EVP_PKEY_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_copy(EVP_PKEY_METHOD *dst,
+ const EVP_PKEY_METHOD *src);
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_free(EVP_PKEY_METHOD *pmeth);
+OSSL_DEPRECATEDIN_3_0 int EVP_PKEY_meth_add0(const EVP_PKEY_METHOD *pmeth);
+OSSL_DEPRECATEDIN_3_0 int EVP_PKEY_meth_remove(const EVP_PKEY_METHOD *pmeth);
+OSSL_DEPRECATEDIN_3_0 size_t EVP_PKEY_meth_get_count(void);
+OSSL_DEPRECATEDIN_3_0 const EVP_PKEY_METHOD *EVP_PKEY_meth_get0(size_t idx);
+# endif
+
+EVP_KEYMGMT *EVP_KEYMGMT_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
+ const char *properties);
+int EVP_KEYMGMT_up_ref(EVP_KEYMGMT *keymgmt);
+void EVP_KEYMGMT_free(EVP_KEYMGMT *keymgmt);
+const OSSL_PROVIDER *EVP_KEYMGMT_get0_provider(const EVP_KEYMGMT *keymgmt);
+const char *EVP_KEYMGMT_get0_name(const EVP_KEYMGMT *keymgmt);
+const char *EVP_KEYMGMT_get0_description(const EVP_KEYMGMT *keymgmt);
+int EVP_KEYMGMT_is_a(const EVP_KEYMGMT *keymgmt, const char *name);
+void EVP_KEYMGMT_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_KEYMGMT *keymgmt, void *arg),
+ void *arg);
+int EVP_KEYMGMT_names_do_all(const EVP_KEYMGMT *keymgmt,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PARAM *EVP_KEYMGMT_gettable_params(const EVP_KEYMGMT *keymgmt);
+const OSSL_PARAM *EVP_KEYMGMT_settable_params(const EVP_KEYMGMT *keymgmt);
+const OSSL_PARAM *EVP_KEYMGMT_gen_settable_params(const EVP_KEYMGMT *keymgmt);
+
+EVP_PKEY_CTX *EVP_PKEY_CTX_new(EVP_PKEY *pkey, ENGINE *e);
+EVP_PKEY_CTX *EVP_PKEY_CTX_new_id(int id, ENGINE *e);
+EVP_PKEY_CTX *EVP_PKEY_CTX_new_from_name(OSSL_LIB_CTX *libctx,
+ const char *name,
+ const char *propquery);
+EVP_PKEY_CTX *EVP_PKEY_CTX_new_from_pkey(OSSL_LIB_CTX *libctx,
+ EVP_PKEY *pkey, const char *propquery);
+EVP_PKEY_CTX *EVP_PKEY_CTX_dup(const EVP_PKEY_CTX *ctx);
+void EVP_PKEY_CTX_free(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_CTX_is_a(EVP_PKEY_CTX *ctx, const char *keytype);
+
+int EVP_PKEY_CTX_get_params(EVP_PKEY_CTX *ctx, OSSL_PARAM *params);
+const OSSL_PARAM *EVP_PKEY_CTX_gettable_params(const EVP_PKEY_CTX *ctx);
+int EVP_PKEY_CTX_set_params(EVP_PKEY_CTX *ctx, const OSSL_PARAM *params);
+const OSSL_PARAM *EVP_PKEY_CTX_settable_params(const EVP_PKEY_CTX *ctx);
+int EVP_PKEY_CTX_ctrl(EVP_PKEY_CTX *ctx, int keytype, int optype,
+ int cmd, int p1, void *p2);
+int EVP_PKEY_CTX_ctrl_str(EVP_PKEY_CTX *ctx, const char *type,
+ const char *value);
+int EVP_PKEY_CTX_ctrl_uint64(EVP_PKEY_CTX *ctx, int keytype, int optype,
+ int cmd, uint64_t value);
+
+int EVP_PKEY_CTX_str2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *str);
+int EVP_PKEY_CTX_hex2ctrl(EVP_PKEY_CTX *ctx, int cmd, const char *hex);
+
+int EVP_PKEY_CTX_md(EVP_PKEY_CTX *ctx, int optype, int cmd, const char *md);
+
+int EVP_PKEY_CTX_get_operation(EVP_PKEY_CTX *ctx);
+void EVP_PKEY_CTX_set0_keygen_info(EVP_PKEY_CTX *ctx, int *dat, int datlen);
+
+EVP_PKEY *EVP_PKEY_new_mac_key(int type, ENGINE *e,
+ const unsigned char *key, int keylen);
+EVP_PKEY *EVP_PKEY_new_raw_private_key_ex(OSSL_LIB_CTX *libctx,
+ const char *keytype,
+ const char *propq,
+ const unsigned char *priv, size_t len);
+EVP_PKEY *EVP_PKEY_new_raw_private_key(int type, ENGINE *e,
+ const unsigned char *priv,
+ size_t len);
+EVP_PKEY *EVP_PKEY_new_raw_public_key_ex(OSSL_LIB_CTX *libctx,
+ const char *keytype, const char *propq,
+ const unsigned char *pub, size_t len);
+EVP_PKEY *EVP_PKEY_new_raw_public_key(int type, ENGINE *e,
+ const unsigned char *pub,
+ size_t len);
+int EVP_PKEY_get_raw_private_key(const EVP_PKEY *pkey, unsigned char *priv,
+ size_t *len);
+int EVP_PKEY_get_raw_public_key(const EVP_PKEY *pkey, unsigned char *pub,
+ size_t *len);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+EVP_PKEY *EVP_PKEY_new_CMAC_key(ENGINE *e, const unsigned char *priv,
+ size_t len, const EVP_CIPHER *cipher);
+# endif
+
+void EVP_PKEY_CTX_set_data(EVP_PKEY_CTX *ctx, void *data);
+void *EVP_PKEY_CTX_get_data(const EVP_PKEY_CTX *ctx);
+EVP_PKEY *EVP_PKEY_CTX_get0_pkey(EVP_PKEY_CTX *ctx);
+
+EVP_PKEY *EVP_PKEY_CTX_get0_peerkey(EVP_PKEY_CTX *ctx);
+
+void EVP_PKEY_CTX_set_app_data(EVP_PKEY_CTX *ctx, void *data);
+void *EVP_PKEY_CTX_get_app_data(EVP_PKEY_CTX *ctx);
+
+void EVP_SIGNATURE_free(EVP_SIGNATURE *signature);
+int EVP_SIGNATURE_up_ref(EVP_SIGNATURE *signature);
+OSSL_PROVIDER *EVP_SIGNATURE_get0_provider(const EVP_SIGNATURE *signature);
+EVP_SIGNATURE *EVP_SIGNATURE_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
+ const char *properties);
+int EVP_SIGNATURE_is_a(const EVP_SIGNATURE *signature, const char *name);
+const char *EVP_SIGNATURE_get0_name(const EVP_SIGNATURE *signature);
+const char *EVP_SIGNATURE_get0_description(const EVP_SIGNATURE *signature);
+void EVP_SIGNATURE_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_SIGNATURE *signature,
+ void *data),
+ void *data);
+int EVP_SIGNATURE_names_do_all(const EVP_SIGNATURE *signature,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PARAM *EVP_SIGNATURE_gettable_ctx_params(const EVP_SIGNATURE *sig);
+const OSSL_PARAM *EVP_SIGNATURE_settable_ctx_params(const EVP_SIGNATURE *sig);
+
+void EVP_ASYM_CIPHER_free(EVP_ASYM_CIPHER *cipher);
+int EVP_ASYM_CIPHER_up_ref(EVP_ASYM_CIPHER *cipher);
+OSSL_PROVIDER *EVP_ASYM_CIPHER_get0_provider(const EVP_ASYM_CIPHER *cipher);
+EVP_ASYM_CIPHER *EVP_ASYM_CIPHER_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
+ const char *properties);
+int EVP_ASYM_CIPHER_is_a(const EVP_ASYM_CIPHER *cipher, const char *name);
+const char *EVP_ASYM_CIPHER_get0_name(const EVP_ASYM_CIPHER *cipher);
+const char *EVP_ASYM_CIPHER_get0_description(const EVP_ASYM_CIPHER *cipher);
+void EVP_ASYM_CIPHER_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_ASYM_CIPHER *cipher,
+ void *arg),
+ void *arg);
+int EVP_ASYM_CIPHER_names_do_all(const EVP_ASYM_CIPHER *cipher,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PARAM *EVP_ASYM_CIPHER_gettable_ctx_params(const EVP_ASYM_CIPHER *ciph);
+const OSSL_PARAM *EVP_ASYM_CIPHER_settable_ctx_params(const EVP_ASYM_CIPHER *ciph);
+
+void EVP_KEM_free(EVP_KEM *wrap);
+int EVP_KEM_up_ref(EVP_KEM *wrap);
+OSSL_PROVIDER *EVP_KEM_get0_provider(const EVP_KEM *wrap);
+EVP_KEM *EVP_KEM_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
+ const char *properties);
+int EVP_KEM_is_a(const EVP_KEM *wrap, const char *name);
+const char *EVP_KEM_get0_name(const EVP_KEM *wrap);
+const char *EVP_KEM_get0_description(const EVP_KEM *wrap);
+void EVP_KEM_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_KEM *wrap, void *arg), void *arg);
+int EVP_KEM_names_do_all(const EVP_KEM *wrap,
+ void (*fn)(const char *name, void *data), void *data);
+const OSSL_PARAM *EVP_KEM_gettable_ctx_params(const EVP_KEM *kem);
+const OSSL_PARAM *EVP_KEM_settable_ctx_params(const EVP_KEM *kem);
+
+int EVP_PKEY_sign_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_sign_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_PKEY_sign(EVP_PKEY_CTX *ctx,
+ unsigned char *sig, size_t *siglen,
+ const unsigned char *tbs, size_t tbslen);
+int EVP_PKEY_verify_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_verify_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_PKEY_verify(EVP_PKEY_CTX *ctx,
+ const unsigned char *sig, size_t siglen,
+ const unsigned char *tbs, size_t tbslen);
+int EVP_PKEY_verify_recover_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_verify_recover_init_ex(EVP_PKEY_CTX *ctx,
+ const OSSL_PARAM params[]);
+int EVP_PKEY_verify_recover(EVP_PKEY_CTX *ctx,
+ unsigned char *rout, size_t *routlen,
+ const unsigned char *sig, size_t siglen);
+int EVP_PKEY_encrypt_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_encrypt_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_PKEY_encrypt(EVP_PKEY_CTX *ctx,
+ unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen);
+int EVP_PKEY_decrypt_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_decrypt_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_PKEY_decrypt(EVP_PKEY_CTX *ctx,
+ unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen);
+
+int EVP_PKEY_derive_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_derive_init_ex(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_PKEY_derive_set_peer_ex(EVP_PKEY_CTX *ctx, EVP_PKEY *peer,
+ int validate_peer);
+int EVP_PKEY_derive_set_peer(EVP_PKEY_CTX *ctx, EVP_PKEY *peer);
+int EVP_PKEY_derive(EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen);
+
+int EVP_PKEY_encapsulate_init(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_PKEY_encapsulate(EVP_PKEY_CTX *ctx,
+ unsigned char *wrappedkey, size_t *wrappedkeylen,
+ unsigned char *genkey, size_t *genkeylen);
+int EVP_PKEY_decapsulate_init(EVP_PKEY_CTX *ctx, const OSSL_PARAM params[]);
+int EVP_PKEY_decapsulate(EVP_PKEY_CTX *ctx,
+ unsigned char *unwrapped, size_t *unwrappedlen,
+ const unsigned char *wrapped, size_t wrappedlen);
+
+typedef int EVP_PKEY_gen_cb(EVP_PKEY_CTX *ctx);
+
+int EVP_PKEY_fromdata_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_fromdata(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey, int selection,
+ OSSL_PARAM param[]);
+const OSSL_PARAM *EVP_PKEY_fromdata_settable(EVP_PKEY_CTX *ctx, int selection);
+
+int EVP_PKEY_todata(const EVP_PKEY *pkey, int selection, OSSL_PARAM **params);
+int EVP_PKEY_export(const EVP_PKEY *pkey, int selection,
+ OSSL_CALLBACK *export_cb, void *export_cbarg);
+
+const OSSL_PARAM *EVP_PKEY_gettable_params(const EVP_PKEY *pkey);
+int EVP_PKEY_get_params(const EVP_PKEY *pkey, OSSL_PARAM params[]);
+int EVP_PKEY_get_int_param(const EVP_PKEY *pkey, const char *key_name,
+ int *out);
+int EVP_PKEY_get_size_t_param(const EVP_PKEY *pkey, const char *key_name,
+ size_t *out);
+int EVP_PKEY_get_bn_param(const EVP_PKEY *pkey, const char *key_name,
+ BIGNUM **bn);
+int EVP_PKEY_get_utf8_string_param(const EVP_PKEY *pkey, const char *key_name,
+ char *str, size_t max_buf_sz, size_t *out_sz);
+int EVP_PKEY_get_octet_string_param(const EVP_PKEY *pkey, const char *key_name,
+ unsigned char *buf, size_t max_buf_sz,
+ size_t *out_sz);
+
+const OSSL_PARAM *EVP_PKEY_settable_params(const EVP_PKEY *pkey);
+int EVP_PKEY_set_params(EVP_PKEY *pkey, OSSL_PARAM params[]);
+int EVP_PKEY_set_int_param(EVP_PKEY *pkey, const char *key_name, int in);
+int EVP_PKEY_set_size_t_param(EVP_PKEY *pkey, const char *key_name, size_t in);
+int EVP_PKEY_set_bn_param(EVP_PKEY *pkey, const char *key_name,
+ const BIGNUM *bn);
+int EVP_PKEY_set_utf8_string_param(EVP_PKEY *pkey, const char *key_name,
+ const char *str);
+int EVP_PKEY_set_octet_string_param(EVP_PKEY *pkey, const char *key_name,
+ const unsigned char *buf, size_t bsize);
+
+int EVP_PKEY_get_ec_point_conv_form(const EVP_PKEY *pkey);
+int EVP_PKEY_get_field_type(const EVP_PKEY *pkey);
+
+EVP_PKEY *EVP_PKEY_Q_keygen(OSSL_LIB_CTX *libctx, const char *propq,
+ const char *type, ...);
+int EVP_PKEY_paramgen_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_paramgen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey);
+int EVP_PKEY_keygen_init(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_keygen(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey);
+int EVP_PKEY_generate(EVP_PKEY_CTX *ctx, EVP_PKEY **ppkey);
+int EVP_PKEY_check(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_public_check(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_public_check_quick(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_param_check(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_param_check_quick(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_private_check(EVP_PKEY_CTX *ctx);
+int EVP_PKEY_pairwise_check(EVP_PKEY_CTX *ctx);
+
+# define EVP_PKEY_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_EVP_PKEY, l, p, newf, dupf, freef)
+int EVP_PKEY_set_ex_data(EVP_PKEY *key, int idx, void *arg);
+void *EVP_PKEY_get_ex_data(const EVP_PKEY *key, int idx);
+
+void EVP_PKEY_CTX_set_cb(EVP_PKEY_CTX *ctx, EVP_PKEY_gen_cb *cb);
+EVP_PKEY_gen_cb *EVP_PKEY_CTX_get_cb(EVP_PKEY_CTX *ctx);
+
+int EVP_PKEY_CTX_get_keygen_info(EVP_PKEY_CTX *ctx, int idx);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_init(EVP_PKEY_METHOD *pmeth,
+ int (*init) (EVP_PKEY_CTX *ctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_copy
+ (EVP_PKEY_METHOD *pmeth, int (*copy) (EVP_PKEY_CTX *dst,
+ const EVP_PKEY_CTX *src));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_cleanup
+ (EVP_PKEY_METHOD *pmeth, void (*cleanup) (EVP_PKEY_CTX *ctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_paramgen
+ (EVP_PKEY_METHOD *pmeth, int (*paramgen_init) (EVP_PKEY_CTX *ctx),
+ int (*paramgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_keygen
+ (EVP_PKEY_METHOD *pmeth, int (*keygen_init) (EVP_PKEY_CTX *ctx),
+ int (*keygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_sign
+ (EVP_PKEY_METHOD *pmeth, int (*sign_init) (EVP_PKEY_CTX *ctx),
+ int (*sign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
+ const unsigned char *tbs, size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_verify
+ (EVP_PKEY_METHOD *pmeth, int (*verify_init) (EVP_PKEY_CTX *ctx),
+ int (*verify) (EVP_PKEY_CTX *ctx, const unsigned char *sig, size_t siglen,
+ const unsigned char *tbs, size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_verify_recover
+ (EVP_PKEY_METHOD *pmeth, int (*verify_recover_init) (EVP_PKEY_CTX *ctx),
+ int (*verify_recover) (EVP_PKEY_CTX *ctx, unsigned char *sig,
+ size_t *siglen, const unsigned char *tbs,
+ size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_signctx
+ (EVP_PKEY_METHOD *pmeth, int (*signctx_init) (EVP_PKEY_CTX *ctx,
+ EVP_MD_CTX *mctx),
+ int (*signctx) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
+ EVP_MD_CTX *mctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_verifyctx
+ (EVP_PKEY_METHOD *pmeth, int (*verifyctx_init) (EVP_PKEY_CTX *ctx,
+ EVP_MD_CTX *mctx),
+ int (*verifyctx) (EVP_PKEY_CTX *ctx, const unsigned char *sig, int siglen,
+ EVP_MD_CTX *mctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_encrypt
+ (EVP_PKEY_METHOD *pmeth, int (*encrypt_init) (EVP_PKEY_CTX *ctx),
+ int (*encryptfn) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_decrypt
+ (EVP_PKEY_METHOD *pmeth, int (*decrypt_init) (EVP_PKEY_CTX *ctx),
+ int (*decrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_derive
+ (EVP_PKEY_METHOD *pmeth, int (*derive_init) (EVP_PKEY_CTX *ctx),
+ int (*derive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_ctrl
+ (EVP_PKEY_METHOD *pmeth, int (*ctrl) (EVP_PKEY_CTX *ctx, int type, int p1,
+ void *p2),
+ int (*ctrl_str) (EVP_PKEY_CTX *ctx, const char *type, const char *value));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_digestsign
+ (EVP_PKEY_METHOD *pmeth,
+ int (*digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen,
+ const unsigned char *tbs, size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_digestverify
+ (EVP_PKEY_METHOD *pmeth,
+ int (*digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig,
+ size_t siglen, const unsigned char *tbs,
+ size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_check
+ (EVP_PKEY_METHOD *pmeth, int (*check) (EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_public_check
+ (EVP_PKEY_METHOD *pmeth, int (*check) (EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_param_check
+ (EVP_PKEY_METHOD *pmeth, int (*check) (EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_set_digest_custom
+ (EVP_PKEY_METHOD *pmeth, int (*digest_custom) (EVP_PKEY_CTX *ctx,
+ EVP_MD_CTX *mctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_init
+ (const EVP_PKEY_METHOD *pmeth, int (**pinit) (EVP_PKEY_CTX *ctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_copy
+ (const EVP_PKEY_METHOD *pmeth, int (**pcopy) (EVP_PKEY_CTX *dst,
+ const EVP_PKEY_CTX *src));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_cleanup
+ (const EVP_PKEY_METHOD *pmeth, void (**pcleanup) (EVP_PKEY_CTX *ctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_paramgen
+ (const EVP_PKEY_METHOD *pmeth, int (**pparamgen_init) (EVP_PKEY_CTX *ctx),
+ int (**pparamgen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_keygen
+ (const EVP_PKEY_METHOD *pmeth, int (**pkeygen_init) (EVP_PKEY_CTX *ctx),
+ int (**pkeygen) (EVP_PKEY_CTX *ctx, EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_sign
+ (const EVP_PKEY_METHOD *pmeth, int (**psign_init) (EVP_PKEY_CTX *ctx),
+ int (**psign) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
+ const unsigned char *tbs, size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_verify
+ (const EVP_PKEY_METHOD *pmeth, int (**pverify_init) (EVP_PKEY_CTX *ctx),
+ int (**pverify) (EVP_PKEY_CTX *ctx, const unsigned char *sig,
+ size_t siglen, const unsigned char *tbs, size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_verify_recover
+ (const EVP_PKEY_METHOD *pmeth,
+ int (**pverify_recover_init) (EVP_PKEY_CTX *ctx),
+ int (**pverify_recover) (EVP_PKEY_CTX *ctx, unsigned char *sig,
+ size_t *siglen, const unsigned char *tbs,
+ size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_signctx
+ (const EVP_PKEY_METHOD *pmeth,
+ int (**psignctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx),
+ int (**psignctx) (EVP_PKEY_CTX *ctx, unsigned char *sig, size_t *siglen,
+ EVP_MD_CTX *mctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_verifyctx
+ (const EVP_PKEY_METHOD *pmeth,
+ int (**pverifyctx_init) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx),
+ int (**pverifyctx) (EVP_PKEY_CTX *ctx, const unsigned char *sig,
+ int siglen, EVP_MD_CTX *mctx));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_encrypt
+ (const EVP_PKEY_METHOD *pmeth, int (**pencrypt_init) (EVP_PKEY_CTX *ctx),
+ int (**pencryptfn) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_decrypt
+ (const EVP_PKEY_METHOD *pmeth, int (**pdecrypt_init) (EVP_PKEY_CTX *ctx),
+ int (**pdecrypt) (EVP_PKEY_CTX *ctx, unsigned char *out, size_t *outlen,
+ const unsigned char *in, size_t inlen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_derive
+ (const EVP_PKEY_METHOD *pmeth, int (**pderive_init) (EVP_PKEY_CTX *ctx),
+ int (**pderive) (EVP_PKEY_CTX *ctx, unsigned char *key, size_t *keylen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_ctrl
+ (const EVP_PKEY_METHOD *pmeth,
+ int (**pctrl) (EVP_PKEY_CTX *ctx, int type, int p1, void *p2),
+ int (**pctrl_str) (EVP_PKEY_CTX *ctx, const char *type,
+ const char *value));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_digestsign
+ (const EVP_PKEY_METHOD *pmeth,
+ int (**digestsign) (EVP_MD_CTX *ctx, unsigned char *sig, size_t *siglen,
+ const unsigned char *tbs, size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_digestverify
+ (const EVP_PKEY_METHOD *pmeth,
+ int (**digestverify) (EVP_MD_CTX *ctx, const unsigned char *sig,
+ size_t siglen, const unsigned char *tbs,
+ size_t tbslen));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_check
+ (const EVP_PKEY_METHOD *pmeth, int (**pcheck) (EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_public_check
+ (const EVP_PKEY_METHOD *pmeth, int (**pcheck) (EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_param_check
+ (const EVP_PKEY_METHOD *pmeth, int (**pcheck) (EVP_PKEY *pkey));
+OSSL_DEPRECATEDIN_3_0 void EVP_PKEY_meth_get_digest_custom
+ (const EVP_PKEY_METHOD *pmeth,
+ int (**pdigest_custom) (EVP_PKEY_CTX *ctx, EVP_MD_CTX *mctx));
+# endif
+
+void EVP_KEYEXCH_free(EVP_KEYEXCH *exchange);
+int EVP_KEYEXCH_up_ref(EVP_KEYEXCH *exchange);
+EVP_KEYEXCH *EVP_KEYEXCH_fetch(OSSL_LIB_CTX *ctx, const char *algorithm,
+ const char *properties);
+OSSL_PROVIDER *EVP_KEYEXCH_get0_provider(const EVP_KEYEXCH *exchange);
+int EVP_KEYEXCH_is_a(const EVP_KEYEXCH *keyexch, const char *name);
+const char *EVP_KEYEXCH_get0_name(const EVP_KEYEXCH *keyexch);
+const char *EVP_KEYEXCH_get0_description(const EVP_KEYEXCH *keyexch);
+void EVP_KEYEXCH_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_KEYEXCH *keyexch, void *data),
+ void *data);
+int EVP_KEYEXCH_names_do_all(const EVP_KEYEXCH *keyexch,
+ void (*fn)(const char *name, void *data),
+ void *data);
+const OSSL_PARAM *EVP_KEYEXCH_gettable_ctx_params(const EVP_KEYEXCH *keyexch);
+const OSSL_PARAM *EVP_KEYEXCH_settable_ctx_params(const EVP_KEYEXCH *keyexch);
+
+void EVP_add_alg_module(void);
+
+int EVP_PKEY_CTX_set_group_name(EVP_PKEY_CTX *ctx, const char *name);
+int EVP_PKEY_CTX_get_group_name(EVP_PKEY_CTX *ctx, char *name, size_t namelen);
+int EVP_PKEY_get_group_name(const EVP_PKEY *pkey, char *name, size_t name_sz,
+ size_t *gname_len);
+
+OSSL_LIB_CTX *EVP_PKEY_CTX_get0_libctx(EVP_PKEY_CTX *ctx);
+const char *EVP_PKEY_CTX_get0_propq(const EVP_PKEY_CTX *ctx);
+const OSSL_PROVIDER *EVP_PKEY_CTX_get0_provider(const EVP_PKEY_CTX *ctx);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/evperr.h b/include/openssl/evperr.h
new file mode 100644
index 00000000..a5053f6c
--- /dev/null
+++ b/include/openssl/evperr.h
@@ -0,0 +1,134 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_EVPERR_H
+# define OPENSSL_EVPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * EVP reason codes.
+ */
+# define EVP_R_AES_KEY_SETUP_FAILED 143
+# define EVP_R_ARIA_KEY_SETUP_FAILED 176
+# define EVP_R_BAD_ALGORITHM_NAME 200
+# define EVP_R_BAD_DECRYPT 100
+# define EVP_R_BAD_KEY_LENGTH 195
+# define EVP_R_BUFFER_TOO_SMALL 155
+# define EVP_R_CACHE_CONSTANTS_FAILED 225
+# define EVP_R_CAMELLIA_KEY_SETUP_FAILED 157
+# define EVP_R_CANNOT_GET_PARAMETERS 197
+# define EVP_R_CANNOT_SET_PARAMETERS 198
+# define EVP_R_CIPHER_NOT_GCM_MODE 184
+# define EVP_R_CIPHER_PARAMETER_ERROR 122
+# define EVP_R_COMMAND_NOT_SUPPORTED 147
+# define EVP_R_CONFLICTING_ALGORITHM_NAME 201
+# define EVP_R_COPY_ERROR 173
+# define EVP_R_CTRL_NOT_IMPLEMENTED 132
+# define EVP_R_CTRL_OPERATION_NOT_IMPLEMENTED 133
+# define EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH 138
+# define EVP_R_DECODE_ERROR 114
+# define EVP_R_DEFAULT_QUERY_PARSE_ERROR 210
+# define EVP_R_DIFFERENT_KEY_TYPES 101
+# define EVP_R_DIFFERENT_PARAMETERS 153
+# define EVP_R_ERROR_LOADING_SECTION 165
+# define EVP_R_EXPECTING_AN_HMAC_KEY 174
+# define EVP_R_EXPECTING_AN_RSA_KEY 127
+# define EVP_R_EXPECTING_A_DH_KEY 128
+# define EVP_R_EXPECTING_A_DSA_KEY 129
+# define EVP_R_EXPECTING_A_ECX_KEY 219
+# define EVP_R_EXPECTING_A_EC_KEY 142
+# define EVP_R_EXPECTING_A_POLY1305_KEY 164
+# define EVP_R_EXPECTING_A_SIPHASH_KEY 175
+# define EVP_R_FINAL_ERROR 188
+# define EVP_R_GENERATE_ERROR 214
+# define EVP_R_GET_RAW_KEY_FAILED 182
+# define EVP_R_ILLEGAL_SCRYPT_PARAMETERS 171
+# define EVP_R_INACCESSIBLE_DOMAIN_PARAMETERS 204
+# define EVP_R_INACCESSIBLE_KEY 203
+# define EVP_R_INITIALIZATION_ERROR 134
+# define EVP_R_INPUT_NOT_INITIALIZED 111
+# define EVP_R_INVALID_CUSTOM_LENGTH 185
+# define EVP_R_INVALID_DIGEST 152
+# define EVP_R_INVALID_IV_LENGTH 194
+# define EVP_R_INVALID_KEY 163
+# define EVP_R_INVALID_KEY_LENGTH 130
+# define EVP_R_INVALID_LENGTH 221
+# define EVP_R_INVALID_NULL_ALGORITHM 218
+# define EVP_R_INVALID_OPERATION 148
+# define EVP_R_INVALID_PROVIDER_FUNCTIONS 193
+# define EVP_R_INVALID_SALT_LENGTH 186
+# define EVP_R_INVALID_SECRET_LENGTH 223
+# define EVP_R_INVALID_SEED_LENGTH 220
+# define EVP_R_INVALID_VALUE 222
+# define EVP_R_KEYMGMT_EXPORT_FAILURE 205
+# define EVP_R_KEY_SETUP_FAILED 180
+# define EVP_R_LOCKING_NOT_SUPPORTED 213
+# define EVP_R_MEMORY_LIMIT_EXCEEDED 172
+# define EVP_R_MESSAGE_DIGEST_IS_NULL 159
+# define EVP_R_METHOD_NOT_SUPPORTED 144
+# define EVP_R_MISSING_PARAMETERS 103
+# define EVP_R_NOT_ABLE_TO_COPY_CTX 190
+# define EVP_R_NOT_XOF_OR_INVALID_LENGTH 178
+# define EVP_R_NO_CIPHER_SET 131
+# define EVP_R_NO_DEFAULT_DIGEST 158
+# define EVP_R_NO_DIGEST_SET 139
+# define EVP_R_NO_IMPORT_FUNCTION 206
+# define EVP_R_NO_KEYMGMT_AVAILABLE 199
+# define EVP_R_NO_KEYMGMT_PRESENT 196
+# define EVP_R_NO_KEY_SET 154
+# define EVP_R_NO_OPERATION_SET 149
+# define EVP_R_NULL_MAC_PKEY_CTX 208
+# define EVP_R_ONLY_ONESHOT_SUPPORTED 177
+# define EVP_R_OPERATION_NOT_INITIALIZED 151
+# define EVP_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 150
+# define EVP_R_OUTPUT_WOULD_OVERFLOW 202
+# define EVP_R_PARAMETER_TOO_LARGE 187
+# define EVP_R_PARTIALLY_OVERLAPPING 162
+# define EVP_R_PBKDF2_ERROR 181
+# define EVP_R_PKEY_APPLICATION_ASN1_METHOD_ALREADY_REGISTERED 179
+# define EVP_R_PRIVATE_KEY_DECODE_ERROR 145
+# define EVP_R_PRIVATE_KEY_ENCODE_ERROR 146
+# define EVP_R_PUBLIC_KEY_NOT_RSA 106
+# define EVP_R_SETTING_XOF_FAILED 227
+# define EVP_R_SET_DEFAULT_PROPERTY_FAILURE 209
+# define EVP_R_TOO_MANY_RECORDS 183
+# define EVP_R_UNABLE_TO_ENABLE_LOCKING 212
+# define EVP_R_UNABLE_TO_GET_MAXIMUM_REQUEST_SIZE 215
+# define EVP_R_UNABLE_TO_GET_RANDOM_STRENGTH 216
+# define EVP_R_UNABLE_TO_LOCK_CONTEXT 211
+# define EVP_R_UNABLE_TO_SET_CALLBACKS 217
+# define EVP_R_UNKNOWN_CIPHER 160
+# define EVP_R_UNKNOWN_DIGEST 161
+# define EVP_R_UNKNOWN_KEY_TYPE 207
+# define EVP_R_UNKNOWN_OPTION 169
+# define EVP_R_UNKNOWN_PBE_ALGORITHM 121
+# define EVP_R_UNSUPPORTED_ALGORITHM 156
+# define EVP_R_UNSUPPORTED_CIPHER 107
+# define EVP_R_UNSUPPORTED_KEYLENGTH 123
+# define EVP_R_UNSUPPORTED_KEY_DERIVATION_FUNCTION 124
+# define EVP_R_UNSUPPORTED_KEY_SIZE 108
+# define EVP_R_UNSUPPORTED_KEY_TYPE 224
+# define EVP_R_UNSUPPORTED_NUMBER_OF_ROUNDS 135
+# define EVP_R_UNSUPPORTED_PRF 125
+# define EVP_R_UNSUPPORTED_PRIVATE_KEY_ALGORITHM 118
+# define EVP_R_UNSUPPORTED_SALT_TYPE 126
+# define EVP_R_UPDATE_ERROR 189
+# define EVP_R_WRAP_MODE_NOT_ALLOWED 170
+# define EVP_R_WRONG_FINAL_BLOCK_LENGTH 109
+# define EVP_R_XTS_DATA_UNIT_IS_TOO_LARGE 191
+# define EVP_R_XTS_DUPLICATED_KEYS 192
+
+#endif
diff --git a/include/openssl/fips_names.h b/include/openssl/fips_names.h
new file mode 100644
index 00000000..0fdf5440
--- /dev/null
+++ b/include/openssl/fips_names.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_FIPS_NAMES_H
+# define OPENSSL_FIPS_NAMES_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * Parameter names that the FIPS Provider defines
+ */
+
+/*
+ * The calculated MAC of the module file (Used for FIPS Self Testing)
+ * Type: OSSL_PARAM_UTF8_STRING
+ */
+# define OSSL_PROV_FIPS_PARAM_MODULE_MAC "module-mac"
+/*
+ * A version number for the fips install process (Used for FIPS Self Testing)
+ * Type: OSSL_PARAM_UTF8_STRING
+ */
+# define OSSL_PROV_FIPS_PARAM_INSTALL_VERSION "install-version"
+/*
+ * The calculated MAC of the install status indicator (Used for FIPS Self Testing)
+ * Type: OSSL_PARAM_UTF8_STRING
+ */
+# define OSSL_PROV_FIPS_PARAM_INSTALL_MAC "install-mac"
+/*
+ * The install status indicator (Used for FIPS Self Testing)
+ * Type: OSSL_PARAM_UTF8_STRING
+ */
+# define OSSL_PROV_FIPS_PARAM_INSTALL_STATUS "install-status"
+
+/*
+ * A boolean that determines if the FIPS conditional test errors result in
+ * the module entering an error state.
+ * Type: OSSL_PARAM_UTF8_STRING
+ */
+# define OSSL_PROV_FIPS_PARAM_CONDITIONAL_ERRORS "conditional-errors"
+
+/*
+ * A boolean that determines if the runtime FIPS security checks are performed.
+ * Type: OSSL_PARAM_UTF8_STRING
+ */
+# define OSSL_PROV_FIPS_PARAM_SECURITY_CHECKS "security-checks"
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif /* OPENSSL_FIPS_NAMES_H */
diff --git a/include/openssl/fipskey.h b/include/openssl/fipskey.h
new file mode 100644
index 00000000..ccc1d2f4
--- /dev/null
+++ b/include/openssl/fipskey.h
@@ -0,0 +1,36 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\fipskey.h.in
+ *
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_FIPSKEY_H
+# define OPENSSL_FIPSKEY_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * The FIPS validation HMAC key, usable as an array initializer.
+ */
+#define FIPS_KEY_ELEMENTS \
+ 0xf4, 0x55, 0x66, 0x50, 0xac, 0x31, 0xd3, 0x54, 0x61, 0x61, 0x0b, 0xac, 0x4e, 0xd8, 0x1b, 0x1a, 0x18, 0x1b, 0x2d, 0x8a, 0x43, 0xea, 0x28, 0x54, 0xcb, 0xae, 0x22, 0xca, 0x74, 0x56, 0x08, 0x13
+
+/*
+ * The FIPS validation key, as a string.
+ */
+#define FIPS_KEY_STRING "f4556650ac31d35461610bac4ed81b1a181b2d8a43ea2854cbae22ca74560813"
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/fipskey.h.in b/include/openssl/fipskey.h.in
new file mode 100644
index 00000000..56b947e8
--- /dev/null
+++ b/include/openssl/fipskey.h.in
@@ -0,0 +1,35 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_FIPSKEY_H
+# define OPENSSL_FIPSKEY_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * The FIPS validation HMAC key, usable as an array initializer.
+ */
+#define FIPS_KEY_ELEMENTS \
+ {- join(', ', map { "0x$_" } unpack("(A2)*", $config{FIPSKEY})) -}
+
+/*
+ * The FIPS validation key, as a string.
+ */
+#define FIPS_KEY_STRING "{- $config{FIPSKEY} -}"
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/hmac.h b/include/openssl/hmac.h
new file mode 100644
index 00000000..f9e1bff3
--- /dev/null
+++ b/include/openssl/hmac.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_HMAC_H
+# define OPENSSL_HMAC_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_HMAC_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# include <openssl/evp.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HMAC_MAX_MD_CBLOCK 200 /* Deprecated */
+# endif
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 size_t HMAC_size(const HMAC_CTX *e);
+OSSL_DEPRECATEDIN_3_0 HMAC_CTX *HMAC_CTX_new(void);
+OSSL_DEPRECATEDIN_3_0 int HMAC_CTX_reset(HMAC_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 void HMAC_CTX_free(HMAC_CTX *ctx);
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur int HMAC_Init(HMAC_CTX *ctx,
+ const void *key, int len,
+ const EVP_MD *md);
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int HMAC_Init_ex(HMAC_CTX *ctx, const void *key, int len,
+ const EVP_MD *md, ENGINE *impl);
+OSSL_DEPRECATEDIN_3_0 int HMAC_Update(HMAC_CTX *ctx, const unsigned char *data,
+ size_t len);
+OSSL_DEPRECATEDIN_3_0 int HMAC_Final(HMAC_CTX *ctx, unsigned char *md,
+ unsigned int *len);
+OSSL_DEPRECATEDIN_3_0 __owur int HMAC_CTX_copy(HMAC_CTX *dctx, HMAC_CTX *sctx);
+OSSL_DEPRECATEDIN_3_0 void HMAC_CTX_set_flags(HMAC_CTX *ctx, unsigned long flags);
+OSSL_DEPRECATEDIN_3_0 const EVP_MD *HMAC_CTX_get_md(const HMAC_CTX *ctx);
+# endif
+
+unsigned char *HMAC(const EVP_MD *evp_md, const void *key, int key_len,
+ const unsigned char *data, size_t data_len,
+ unsigned char *md, unsigned int *md_len);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/http.h b/include/openssl/http.h
new file mode 100644
index 00000000..f7ab2142
--- /dev/null
+++ b/include/openssl/http.h
@@ -0,0 +1,109 @@
+/*
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright Siemens AG 2018-2020
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_HTTP_H
+# define OPENSSL_HTTP_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+
+# include <openssl/bio.h>
+# include <openssl/asn1.h>
+# include <openssl/conf.h>
+
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define OSSL_HTTP_NAME "http"
+# define OSSL_HTTPS_NAME "https"
+# define OSSL_HTTP_PREFIX OSSL_HTTP_NAME"://"
+# define OSSL_HTTPS_PREFIX OSSL_HTTPS_NAME"://"
+# define OSSL_HTTP_PORT "80"
+# define OSSL_HTTPS_PORT "443"
+# define OPENSSL_NO_PROXY "NO_PROXY"
+# define OPENSSL_HTTP_PROXY "HTTP_PROXY"
+# define OPENSSL_HTTPS_PROXY "HTTPS_PROXY"
+
+#define OSSL_HTTP_DEFAULT_MAX_LINE_LEN (4 * 1024)
+#define OSSL_HTTP_DEFAULT_MAX_RESP_LEN (100 * 1024)
+
+/* Low-level HTTP API */
+OSSL_HTTP_REQ_CTX *OSSL_HTTP_REQ_CTX_new(BIO *wbio, BIO *rbio, int buf_size);
+void OSSL_HTTP_REQ_CTX_free(OSSL_HTTP_REQ_CTX *rctx);
+int OSSL_HTTP_REQ_CTX_set_request_line(OSSL_HTTP_REQ_CTX *rctx, int method_POST,
+ const char *server, const char *port,
+ const char *path);
+int OSSL_HTTP_REQ_CTX_add1_header(OSSL_HTTP_REQ_CTX *rctx,
+ const char *name, const char *value);
+int OSSL_HTTP_REQ_CTX_set_expected(OSSL_HTTP_REQ_CTX *rctx,
+ const char *content_type, int asn1,
+ int timeout, int keep_alive);
+int OSSL_HTTP_REQ_CTX_set1_req(OSSL_HTTP_REQ_CTX *rctx, const char *content_type,
+ const ASN1_ITEM *it, const ASN1_VALUE *req);
+int OSSL_HTTP_REQ_CTX_nbio(OSSL_HTTP_REQ_CTX *rctx);
+int OSSL_HTTP_REQ_CTX_nbio_d2i(OSSL_HTTP_REQ_CTX *rctx,
+ ASN1_VALUE **pval, const ASN1_ITEM *it);
+BIO *OSSL_HTTP_REQ_CTX_exchange(OSSL_HTTP_REQ_CTX *rctx);
+BIO *OSSL_HTTP_REQ_CTX_get0_mem_bio(const OSSL_HTTP_REQ_CTX *rctx);
+size_t OSSL_HTTP_REQ_CTX_get_resp_len(const OSSL_HTTP_REQ_CTX *rctx);
+void OSSL_HTTP_REQ_CTX_set_max_response_length(OSSL_HTTP_REQ_CTX *rctx,
+ unsigned long len);
+int OSSL_HTTP_is_alive(const OSSL_HTTP_REQ_CTX *rctx);
+
+/* High-level HTTP API */
+typedef BIO *(*OSSL_HTTP_bio_cb_t)(BIO *bio, void *arg, int connect, int detail);
+OSSL_HTTP_REQ_CTX *OSSL_HTTP_open(const char *server, const char *port,
+ const char *proxy, const char *no_proxy,
+ int use_ssl, BIO *bio, BIO *rbio,
+ OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
+ int buf_size, int overall_timeout);
+int OSSL_HTTP_proxy_connect(BIO *bio, const char *server, const char *port,
+ const char *proxyuser, const char *proxypass,
+ int timeout, BIO *bio_err, const char *prog);
+int OSSL_HTTP_set1_request(OSSL_HTTP_REQ_CTX *rctx, const char *path,
+ const STACK_OF(CONF_VALUE) *headers,
+ const char *content_type, BIO *req,
+ const char *expected_content_type, int expect_asn1,
+ size_t max_resp_len, int timeout, int keep_alive);
+BIO *OSSL_HTTP_exchange(OSSL_HTTP_REQ_CTX *rctx, char **redirection_url);
+BIO *OSSL_HTTP_get(const char *url, const char *proxy, const char *no_proxy,
+ BIO *bio, BIO *rbio,
+ OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
+ int buf_size, const STACK_OF(CONF_VALUE) *headers,
+ const char *expected_content_type, int expect_asn1,
+ size_t max_resp_len, int timeout);
+BIO *OSSL_HTTP_transfer(OSSL_HTTP_REQ_CTX **prctx,
+ const char *server, const char *port,
+ const char *path, int use_ssl,
+ const char *proxy, const char *no_proxy,
+ BIO *bio, BIO *rbio,
+ OSSL_HTTP_bio_cb_t bio_update_fn, void *arg,
+ int buf_size, const STACK_OF(CONF_VALUE) *headers,
+ const char *content_type, BIO *req,
+ const char *expected_content_type, int expect_asn1,
+ size_t max_resp_len, int timeout, int keep_alive);
+int OSSL_HTTP_close(OSSL_HTTP_REQ_CTX *rctx, int ok);
+
+/* Auxiliary functions */
+int OSSL_parse_url(const char *url, char **pscheme, char **puser, char **phost,
+ char **pport, int *pport_num,
+ char **ppath, char **pquery, char **pfrag);
+int OSSL_HTTP_parse_url(const char *url, int *pssl, char **puser, char **phost,
+ char **pport, int *pport_num,
+ char **ppath, char **pquery, char **pfrag);
+const char *OSSL_HTTP_adapt_proxy(const char *proxy, const char *no_proxy,
+ const char *server, int use_ssl);
+
+# ifdef __cplusplus
+}
+# endif
+#endif /* !defined(OPENSSL_HTTP_H) */
diff --git a/include/openssl/httperr.h b/include/openssl/httperr.h
new file mode 100644
index 00000000..ee089592
--- /dev/null
+++ b/include/openssl/httperr.h
@@ -0,0 +1,55 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_HTTPERR_H
+# define OPENSSL_HTTPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * HTTP reason codes.
+ */
+# define HTTP_R_ASN1_LEN_EXCEEDS_MAX_RESP_LEN 108
+# define HTTP_R_CONNECT_FAILURE 100
+# define HTTP_R_ERROR_PARSING_ASN1_LENGTH 109
+# define HTTP_R_ERROR_PARSING_CONTENT_LENGTH 119
+# define HTTP_R_ERROR_PARSING_URL 101
+# define HTTP_R_ERROR_RECEIVING 103
+# define HTTP_R_ERROR_SENDING 102
+# define HTTP_R_FAILED_READING_DATA 128
+# define HTTP_R_HEADER_PARSE_ERROR 126
+# define HTTP_R_INCONSISTENT_CONTENT_LENGTH 120
+# define HTTP_R_INVALID_PORT_NUMBER 123
+# define HTTP_R_INVALID_URL_PATH 125
+# define HTTP_R_INVALID_URL_SCHEME 124
+# define HTTP_R_MAX_RESP_LEN_EXCEEDED 117
+# define HTTP_R_MISSING_ASN1_ENCODING 110
+# define HTTP_R_MISSING_CONTENT_TYPE 121
+# define HTTP_R_MISSING_REDIRECT_LOCATION 111
+# define HTTP_R_RECEIVED_ERROR 105
+# define HTTP_R_RECEIVED_WRONG_HTTP_VERSION 106
+# define HTTP_R_REDIRECTION_FROM_HTTPS_TO_HTTP 112
+# define HTTP_R_REDIRECTION_NOT_ENABLED 116
+# define HTTP_R_RESPONSE_LINE_TOO_LONG 113
+# define HTTP_R_RESPONSE_PARSE_ERROR 104
+# define HTTP_R_RETRY_TIMEOUT 129
+# define HTTP_R_SERVER_CANCELED_CONNECTION 127
+# define HTTP_R_SOCK_NOT_SUPPORTED 122
+# define HTTP_R_STATUS_CODE_UNSUPPORTED 114
+# define HTTP_R_TLS_NOT_ENABLED 107
+# define HTTP_R_TOO_MANY_REDIRECTIONS 115
+# define HTTP_R_UNEXPECTED_CONTENT_TYPE 118
+
+#endif
diff --git a/include/openssl/idea.h b/include/openssl/idea.h
new file mode 100644
index 00000000..1f9bb3b3
--- /dev/null
+++ b/include/openssl/idea.h
@@ -0,0 +1,82 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_IDEA_H
+# define OPENSSL_IDEA_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_IDEA_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_IDEA
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define IDEA_BLOCK 8
+# define IDEA_KEY_LENGTH 16
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+typedef unsigned int IDEA_INT;
+
+# define IDEA_ENCRYPT 1
+# define IDEA_DECRYPT 0
+
+typedef struct idea_key_st {
+ IDEA_INT data[9][6];
+} IDEA_KEY_SCHEDULE;
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *IDEA_options(void);
+OSSL_DEPRECATEDIN_3_0 void IDEA_ecb_encrypt(const unsigned char *in,
+ unsigned char *out,
+ IDEA_KEY_SCHEDULE *ks);
+OSSL_DEPRECATEDIN_3_0 void IDEA_set_encrypt_key(const unsigned char *key,
+ IDEA_KEY_SCHEDULE *ks);
+OSSL_DEPRECATEDIN_3_0 void IDEA_set_decrypt_key(IDEA_KEY_SCHEDULE *ek,
+ IDEA_KEY_SCHEDULE *dk);
+OSSL_DEPRECATEDIN_3_0 void IDEA_cbc_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ IDEA_KEY_SCHEDULE *ks,
+ unsigned char *iv, int enc);
+OSSL_DEPRECATEDIN_3_0 void IDEA_cfb64_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ IDEA_KEY_SCHEDULE *ks,
+ unsigned char *iv, int *num,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void IDEA_ofb64_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ IDEA_KEY_SCHEDULE *ks,
+ unsigned char *iv, int *num);
+OSSL_DEPRECATEDIN_3_0 void IDEA_encrypt(unsigned long *in,
+ IDEA_KEY_SCHEDULE *ks);
+#endif
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define idea_options IDEA_options
+# define idea_ecb_encrypt IDEA_ecb_encrypt
+# define idea_set_encrypt_key IDEA_set_encrypt_key
+# define idea_set_decrypt_key IDEA_set_decrypt_key
+# define idea_cbc_encrypt IDEA_cbc_encrypt
+# define idea_cfb64_encrypt IDEA_cfb64_encrypt
+# define idea_ofb64_encrypt IDEA_ofb64_encrypt
+# define idea_encrypt IDEA_encrypt
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/kdf.h b/include/openssl/kdf.h
new file mode 100644
index 00000000..0983230a
--- /dev/null
+++ b/include/openssl/kdf.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_KDF_H
+# define OPENSSL_KDF_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_KDF_H
+# endif
+
+# include <stdarg.h>
+# include <stddef.h>
+# include <openssl/types.h>
+# include <openssl/core.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+int EVP_KDF_up_ref(EVP_KDF *kdf);
+void EVP_KDF_free(EVP_KDF *kdf);
+EVP_KDF *EVP_KDF_fetch(OSSL_LIB_CTX *libctx, const char *algorithm,
+ const char *properties);
+
+EVP_KDF_CTX *EVP_KDF_CTX_new(EVP_KDF *kdf);
+void EVP_KDF_CTX_free(EVP_KDF_CTX *ctx);
+EVP_KDF_CTX *EVP_KDF_CTX_dup(const EVP_KDF_CTX *src);
+const char *EVP_KDF_get0_description(const EVP_KDF *kdf);
+int EVP_KDF_is_a(const EVP_KDF *kdf, const char *name);
+const char *EVP_KDF_get0_name(const EVP_KDF *kdf);
+const OSSL_PROVIDER *EVP_KDF_get0_provider(const EVP_KDF *kdf);
+const EVP_KDF *EVP_KDF_CTX_kdf(EVP_KDF_CTX *ctx);
+
+void EVP_KDF_CTX_reset(EVP_KDF_CTX *ctx);
+size_t EVP_KDF_CTX_get_kdf_size(EVP_KDF_CTX *ctx);
+int EVP_KDF_derive(EVP_KDF_CTX *ctx, unsigned char *key, size_t keylen,
+ const OSSL_PARAM params[]);
+int EVP_KDF_get_params(EVP_KDF *kdf, OSSL_PARAM params[]);
+int EVP_KDF_CTX_get_params(EVP_KDF_CTX *ctx, OSSL_PARAM params[]);
+int EVP_KDF_CTX_set_params(EVP_KDF_CTX *ctx, const OSSL_PARAM params[]);
+const OSSL_PARAM *EVP_KDF_gettable_params(const EVP_KDF *kdf);
+const OSSL_PARAM *EVP_KDF_gettable_ctx_params(const EVP_KDF *kdf);
+const OSSL_PARAM *EVP_KDF_settable_ctx_params(const EVP_KDF *kdf);
+const OSSL_PARAM *EVP_KDF_CTX_gettable_params(EVP_KDF_CTX *ctx);
+const OSSL_PARAM *EVP_KDF_CTX_settable_params(EVP_KDF_CTX *ctx);
+
+void EVP_KDF_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(EVP_KDF *kdf, void *arg),
+ void *arg);
+int EVP_KDF_names_do_all(const EVP_KDF *kdf,
+ void (*fn)(const char *name, void *data),
+ void *data);
+
+# define EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND 0
+# define EVP_KDF_HKDF_MODE_EXTRACT_ONLY 1
+# define EVP_KDF_HKDF_MODE_EXPAND_ONLY 2
+
+#define EVP_KDF_SSHKDF_TYPE_INITIAL_IV_CLI_TO_SRV 65
+#define EVP_KDF_SSHKDF_TYPE_INITIAL_IV_SRV_TO_CLI 66
+#define EVP_KDF_SSHKDF_TYPE_ENCRYPTION_KEY_CLI_TO_SRV 67
+#define EVP_KDF_SSHKDF_TYPE_ENCRYPTION_KEY_SRV_TO_CLI 68
+#define EVP_KDF_SSHKDF_TYPE_INTEGRITY_KEY_CLI_TO_SRV 69
+#define EVP_KDF_SSHKDF_TYPE_INTEGRITY_KEY_SRV_TO_CLI 70
+
+/**** The legacy PKEY-based KDF API follows. ****/
+
+# define EVP_PKEY_CTRL_TLS_MD (EVP_PKEY_ALG_CTRL)
+# define EVP_PKEY_CTRL_TLS_SECRET (EVP_PKEY_ALG_CTRL + 1)
+# define EVP_PKEY_CTRL_TLS_SEED (EVP_PKEY_ALG_CTRL + 2)
+# define EVP_PKEY_CTRL_HKDF_MD (EVP_PKEY_ALG_CTRL + 3)
+# define EVP_PKEY_CTRL_HKDF_SALT (EVP_PKEY_ALG_CTRL + 4)
+# define EVP_PKEY_CTRL_HKDF_KEY (EVP_PKEY_ALG_CTRL + 5)
+# define EVP_PKEY_CTRL_HKDF_INFO (EVP_PKEY_ALG_CTRL + 6)
+# define EVP_PKEY_CTRL_HKDF_MODE (EVP_PKEY_ALG_CTRL + 7)
+# define EVP_PKEY_CTRL_PASS (EVP_PKEY_ALG_CTRL + 8)
+# define EVP_PKEY_CTRL_SCRYPT_SALT (EVP_PKEY_ALG_CTRL + 9)
+# define EVP_PKEY_CTRL_SCRYPT_N (EVP_PKEY_ALG_CTRL + 10)
+# define EVP_PKEY_CTRL_SCRYPT_R (EVP_PKEY_ALG_CTRL + 11)
+# define EVP_PKEY_CTRL_SCRYPT_P (EVP_PKEY_ALG_CTRL + 12)
+# define EVP_PKEY_CTRL_SCRYPT_MAXMEM_BYTES (EVP_PKEY_ALG_CTRL + 13)
+
+# define EVP_PKEY_HKDEF_MODE_EXTRACT_AND_EXPAND \
+ EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND
+# define EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY \
+ EVP_KDF_HKDF_MODE_EXTRACT_ONLY
+# define EVP_PKEY_HKDEF_MODE_EXPAND_ONLY \
+ EVP_KDF_HKDF_MODE_EXPAND_ONLY
+
+int EVP_PKEY_CTX_set_tls1_prf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+
+int EVP_PKEY_CTX_set1_tls1_prf_secret(EVP_PKEY_CTX *pctx,
+ const unsigned char *sec, int seclen);
+
+int EVP_PKEY_CTX_add1_tls1_prf_seed(EVP_PKEY_CTX *pctx,
+ const unsigned char *seed, int seedlen);
+
+int EVP_PKEY_CTX_set_hkdf_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+
+int EVP_PKEY_CTX_set1_hkdf_salt(EVP_PKEY_CTX *ctx,
+ const unsigned char *salt, int saltlen);
+
+int EVP_PKEY_CTX_set1_hkdf_key(EVP_PKEY_CTX *ctx,
+ const unsigned char *key, int keylen);
+
+int EVP_PKEY_CTX_add1_hkdf_info(EVP_PKEY_CTX *ctx,
+ const unsigned char *info, int infolen);
+
+int EVP_PKEY_CTX_set_hkdf_mode(EVP_PKEY_CTX *ctx, int mode);
+# define EVP_PKEY_CTX_hkdf_mode EVP_PKEY_CTX_set_hkdf_mode
+
+int EVP_PKEY_CTX_set1_pbe_pass(EVP_PKEY_CTX *ctx, const char *pass,
+ int passlen);
+
+int EVP_PKEY_CTX_set1_scrypt_salt(EVP_PKEY_CTX *ctx,
+ const unsigned char *salt, int saltlen);
+
+int EVP_PKEY_CTX_set_scrypt_N(EVP_PKEY_CTX *ctx, uint64_t n);
+
+int EVP_PKEY_CTX_set_scrypt_r(EVP_PKEY_CTX *ctx, uint64_t r);
+
+int EVP_PKEY_CTX_set_scrypt_p(EVP_PKEY_CTX *ctx, uint64_t p);
+
+int EVP_PKEY_CTX_set_scrypt_maxmem_bytes(EVP_PKEY_CTX *ctx,
+ uint64_t maxmem_bytes);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/kdferr.h b/include/openssl/kdferr.h
new file mode 100644
index 00000000..963d766d
--- /dev/null
+++ b/include/openssl/kdferr.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_KDFERR_H
+# define OPENSSL_KDFERR_H
+# pragma once
+
+#include <openssl/cryptoerr_legacy.h>
+
+#endif /* !defined(OPENSSL_KDFERR_H) */
diff --git a/include/openssl/lhash.h b/include/openssl/lhash.h
new file mode 100644
index 00000000..39dd6254
--- /dev/null
+++ b/include/openssl/lhash.h
@@ -0,0 +1,288 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+/*
+ * Header for dynamic hash table routines Author - Eric Young
+ */
+
+#ifndef OPENSSL_LHASH_H
+# define OPENSSL_LHASH_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_LHASH_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/bio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct lhash_node_st OPENSSL_LH_NODE;
+typedef int (*OPENSSL_LH_COMPFUNC) (const void *, const void *);
+typedef unsigned long (*OPENSSL_LH_HASHFUNC) (const void *);
+typedef void (*OPENSSL_LH_DOALL_FUNC) (void *);
+typedef void (*OPENSSL_LH_DOALL_FUNCARG) (void *, void *);
+typedef struct lhash_st OPENSSL_LHASH;
+
+/*
+ * Macros for declaring and implementing type-safe wrappers for LHASH
+ * callbacks. This way, callbacks can be provided to LHASH structures without
+ * function pointer casting and the macro-defined callbacks provide
+ * per-variable casting before deferring to the underlying type-specific
+ * callbacks. NB: It is possible to place a "static" in front of both the
+ * DECLARE and IMPLEMENT macros if the functions are strictly internal.
+ */
+
+/* First: "hash" functions */
+# define DECLARE_LHASH_HASH_FN(name, o_type) \
+ unsigned long name##_LHASH_HASH(const void *);
+# define IMPLEMENT_LHASH_HASH_FN(name, o_type) \
+ unsigned long name##_LHASH_HASH(const void *arg) { \
+ const o_type *a = arg; \
+ return name##_hash(a); }
+# define LHASH_HASH_FN(name) name##_LHASH_HASH
+
+/* Second: "compare" functions */
+# define DECLARE_LHASH_COMP_FN(name, o_type) \
+ int name##_LHASH_COMP(const void *, const void *);
+# define IMPLEMENT_LHASH_COMP_FN(name, o_type) \
+ int name##_LHASH_COMP(const void *arg1, const void *arg2) { \
+ const o_type *a = arg1; \
+ const o_type *b = arg2; \
+ return name##_cmp(a,b); }
+# define LHASH_COMP_FN(name) name##_LHASH_COMP
+
+/* Fourth: "doall_arg" functions */
+# define DECLARE_LHASH_DOALL_ARG_FN(name, o_type, a_type) \
+ void name##_LHASH_DOALL_ARG(void *, void *);
+# define IMPLEMENT_LHASH_DOALL_ARG_FN(name, o_type, a_type) \
+ void name##_LHASH_DOALL_ARG(void *arg1, void *arg2) { \
+ o_type *a = arg1; \
+ a_type *b = arg2; \
+ name##_doall_arg(a, b); }
+# define LHASH_DOALL_ARG_FN(name) name##_LHASH_DOALL_ARG
+
+
+# define LH_LOAD_MULT 256
+
+int OPENSSL_LH_error(OPENSSL_LHASH *lh);
+OPENSSL_LHASH *OPENSSL_LH_new(OPENSSL_LH_HASHFUNC h, OPENSSL_LH_COMPFUNC c);
+void OPENSSL_LH_free(OPENSSL_LHASH *lh);
+void OPENSSL_LH_flush(OPENSSL_LHASH *lh);
+void *OPENSSL_LH_insert(OPENSSL_LHASH *lh, void *data);
+void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data);
+void *OPENSSL_LH_retrieve(OPENSSL_LHASH *lh, const void *data);
+void OPENSSL_LH_doall(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNC func);
+void OPENSSL_LH_doall_arg(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNCARG func, void *arg);
+unsigned long OPENSSL_LH_strhash(const char *c);
+unsigned long OPENSSL_LH_num_items(const OPENSSL_LHASH *lh);
+unsigned long OPENSSL_LH_get_down_load(const OPENSSL_LHASH *lh);
+void OPENSSL_LH_set_down_load(OPENSSL_LHASH *lh, unsigned long down_load);
+
+# ifndef OPENSSL_NO_STDIO
+void OPENSSL_LH_stats(const OPENSSL_LHASH *lh, FILE *fp);
+void OPENSSL_LH_node_stats(const OPENSSL_LHASH *lh, FILE *fp);
+void OPENSSL_LH_node_usage_stats(const OPENSSL_LHASH *lh, FILE *fp);
+# endif
+void OPENSSL_LH_stats_bio(const OPENSSL_LHASH *lh, BIO *out);
+void OPENSSL_LH_node_stats_bio(const OPENSSL_LHASH *lh, BIO *out);
+void OPENSSL_LH_node_usage_stats_bio(const OPENSSL_LHASH *lh, BIO *out);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define _LHASH OPENSSL_LHASH
+# define LHASH_NODE OPENSSL_LH_NODE
+# define lh_error OPENSSL_LH_error
+# define lh_new OPENSSL_LH_new
+# define lh_free OPENSSL_LH_free
+# define lh_insert OPENSSL_LH_insert
+# define lh_delete OPENSSL_LH_delete
+# define lh_retrieve OPENSSL_LH_retrieve
+# define lh_doall OPENSSL_LH_doall
+# define lh_doall_arg OPENSSL_LH_doall_arg
+# define lh_strhash OPENSSL_LH_strhash
+# define lh_num_items OPENSSL_LH_num_items
+# ifndef OPENSSL_NO_STDIO
+# define lh_stats OPENSSL_LH_stats
+# define lh_node_stats OPENSSL_LH_node_stats
+# define lh_node_usage_stats OPENSSL_LH_node_usage_stats
+# endif
+# define lh_stats_bio OPENSSL_LH_stats_bio
+# define lh_node_stats_bio OPENSSL_LH_node_stats_bio
+# define lh_node_usage_stats_bio OPENSSL_LH_node_usage_stats_bio
+# endif
+
+/* Type checking... */
+
+# define LHASH_OF(type) struct lhash_st_##type
+
+/* Helper macro for internal use */
+# define DEFINE_LHASH_OF_INTERNAL(type) \
+ LHASH_OF(type) { union lh_##type##_dummy { void* d1; unsigned long d2; int d3; } dummy; }; \
+ typedef int (*lh_##type##_compfunc)(const type *a, const type *b); \
+ typedef unsigned long (*lh_##type##_hashfunc)(const type *a); \
+ typedef void (*lh_##type##_doallfunc)(type *a); \
+ static ossl_unused ossl_inline type *ossl_check_##type##_lh_plain_type(type *ptr) \
+ { \
+ return ptr; \
+ } \
+ static ossl_unused ossl_inline const type *ossl_check_const_##type##_lh_plain_type(const type *ptr) \
+ { \
+ return ptr; \
+ } \
+ static ossl_unused ossl_inline const OPENSSL_LHASH *ossl_check_const_##type##_lh_type(const LHASH_OF(type) *lh) \
+ { \
+ return (const OPENSSL_LHASH *)lh; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LHASH *ossl_check_##type##_lh_type(LHASH_OF(type) *lh) \
+ { \
+ return (OPENSSL_LHASH *)lh; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LH_COMPFUNC ossl_check_##type##_lh_compfunc_type(lh_##type##_compfunc cmp) \
+ { \
+ return (OPENSSL_LH_COMPFUNC)cmp; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LH_HASHFUNC ossl_check_##type##_lh_hashfunc_type(lh_##type##_hashfunc hfn) \
+ { \
+ return (OPENSSL_LH_HASHFUNC)hfn; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LH_DOALL_FUNC ossl_check_##type##_lh_doallfunc_type(lh_##type##_doallfunc dfn) \
+ { \
+ return (OPENSSL_LH_DOALL_FUNC)dfn; \
+ } \
+ LHASH_OF(type)
+
+# define DEFINE_LHASH_OF(type) \
+ LHASH_OF(type) { union lh_##type##_dummy { void* d1; unsigned long d2; int d3; } dummy; }; \
+ static ossl_unused ossl_inline LHASH_OF(type) *lh_##type##_new(unsigned long (*hfn)(const type *), \
+ int (*cfn)(const type *, const type *)) \
+ { \
+ return (LHASH_OF(type) *) \
+ OPENSSL_LH_new((OPENSSL_LH_HASHFUNC)hfn, (OPENSSL_LH_COMPFUNC)cfn); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_free(LHASH_OF(type) *lh) \
+ { \
+ OPENSSL_LH_free((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_flush(LHASH_OF(type) *lh) \
+ { \
+ OPENSSL_LH_flush((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline type *lh_##type##_insert(LHASH_OF(type) *lh, type *d) \
+ { \
+ return (type *)OPENSSL_LH_insert((OPENSSL_LHASH *)lh, d); \
+ } \
+ static ossl_unused ossl_inline type *lh_##type##_delete(LHASH_OF(type) *lh, const type *d) \
+ { \
+ return (type *)OPENSSL_LH_delete((OPENSSL_LHASH *)lh, d); \
+ } \
+ static ossl_unused ossl_inline type *lh_##type##_retrieve(LHASH_OF(type) *lh, const type *d) \
+ { \
+ return (type *)OPENSSL_LH_retrieve((OPENSSL_LHASH *)lh, d); \
+ } \
+ static ossl_unused ossl_inline int lh_##type##_error(LHASH_OF(type) *lh) \
+ { \
+ return OPENSSL_LH_error((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline unsigned long lh_##type##_num_items(LHASH_OF(type) *lh) \
+ { \
+ return OPENSSL_LH_num_items((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_node_stats_bio(const LHASH_OF(type) *lh, BIO *out) \
+ { \
+ OPENSSL_LH_node_stats_bio((const OPENSSL_LHASH *)lh, out); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_node_usage_stats_bio(const LHASH_OF(type) *lh, BIO *out) \
+ { \
+ OPENSSL_LH_node_usage_stats_bio((const OPENSSL_LHASH *)lh, out); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_stats_bio(const LHASH_OF(type) *lh, BIO *out) \
+ { \
+ OPENSSL_LH_stats_bio((const OPENSSL_LHASH *)lh, out); \
+ } \
+ static ossl_unused ossl_inline unsigned long lh_##type##_get_down_load(LHASH_OF(type) *lh) \
+ { \
+ return OPENSSL_LH_get_down_load((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_set_down_load(LHASH_OF(type) *lh, unsigned long dl) \
+ { \
+ OPENSSL_LH_set_down_load((OPENSSL_LHASH *)lh, dl); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_doall(LHASH_OF(type) *lh, \
+ void (*doall)(type *)) \
+ { \
+ OPENSSL_LH_doall((OPENSSL_LHASH *)lh, (OPENSSL_LH_DOALL_FUNC)doall); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_doall_arg(LHASH_OF(type) *lh, \
+ void (*doallarg)(type *, void *), \
+ void *arg) \
+ { \
+ OPENSSL_LH_doall_arg((OPENSSL_LHASH *)lh, \
+ (OPENSSL_LH_DOALL_FUNCARG)doallarg, arg); \
+ } \
+ LHASH_OF(type)
+
+#define IMPLEMENT_LHASH_DOALL_ARG_CONST(type, argtype) \
+ int_implement_lhash_doall(type, argtype, const type)
+
+#define IMPLEMENT_LHASH_DOALL_ARG(type, argtype) \
+ int_implement_lhash_doall(type, argtype, type)
+
+#define int_implement_lhash_doall(type, argtype, cbargtype) \
+ static ossl_unused ossl_inline void \
+ lh_##type##_doall_##argtype(LHASH_OF(type) *lh, \
+ void (*fn)(cbargtype *, argtype *), \
+ argtype *arg) \
+ { \
+ OPENSSL_LH_doall_arg((OPENSSL_LHASH *)lh, (OPENSSL_LH_DOALL_FUNCARG)fn, (void *)arg); \
+ } \
+ LHASH_OF(type)
+
+DEFINE_LHASH_OF_INTERNAL(OPENSSL_STRING);
+#define lh_OPENSSL_STRING_new(hfn, cmp) ((LHASH_OF(OPENSSL_STRING) *)OPENSSL_LH_new(ossl_check_OPENSSL_STRING_lh_hashfunc_type(hfn), ossl_check_OPENSSL_STRING_lh_compfunc_type(cmp)))
+#define lh_OPENSSL_STRING_free(lh) OPENSSL_LH_free(ossl_check_OPENSSL_STRING_lh_type(lh))
+#define lh_OPENSSL_STRING_flush(lh) OPENSSL_LH_flush(ossl_check_OPENSSL_STRING_lh_type(lh))
+#define lh_OPENSSL_STRING_insert(lh, ptr) ((OPENSSL_STRING *)OPENSSL_LH_insert(ossl_check_OPENSSL_STRING_lh_type(lh), ossl_check_OPENSSL_STRING_lh_plain_type(ptr)))
+#define lh_OPENSSL_STRING_delete(lh, ptr) ((OPENSSL_STRING *)OPENSSL_LH_delete(ossl_check_OPENSSL_STRING_lh_type(lh), ossl_check_const_OPENSSL_STRING_lh_plain_type(ptr)))
+#define lh_OPENSSL_STRING_retrieve(lh, ptr) ((OPENSSL_STRING *)OPENSSL_LH_retrieve(ossl_check_OPENSSL_STRING_lh_type(lh), ossl_check_const_OPENSSL_STRING_lh_plain_type(ptr)))
+#define lh_OPENSSL_STRING_error(lh) OPENSSL_LH_error(ossl_check_OPENSSL_STRING_lh_type(lh))
+#define lh_OPENSSL_STRING_num_items(lh) OPENSSL_LH_num_items(ossl_check_OPENSSL_STRING_lh_type(lh))
+#define lh_OPENSSL_STRING_node_stats_bio(lh, out) OPENSSL_LH_node_stats_bio(ossl_check_const_OPENSSL_STRING_lh_type(lh), out)
+#define lh_OPENSSL_STRING_node_usage_stats_bio(lh, out) OPENSSL_LH_node_usage_stats_bio(ossl_check_const_OPENSSL_STRING_lh_type(lh), out)
+#define lh_OPENSSL_STRING_stats_bio(lh, out) OPENSSL_LH_stats_bio(ossl_check_const_OPENSSL_STRING_lh_type(lh), out)
+#define lh_OPENSSL_STRING_get_down_load(lh) OPENSSL_LH_get_down_load(ossl_check_OPENSSL_STRING_lh_type(lh))
+#define lh_OPENSSL_STRING_set_down_load(lh, dl) OPENSSL_LH_set_down_load(ossl_check_OPENSSL_STRING_lh_type(lh), dl)
+#define lh_OPENSSL_STRING_doall(lh, dfn) OPENSSL_LH_doall(ossl_check_OPENSSL_STRING_lh_type(lh), ossl_check_OPENSSL_STRING_lh_doallfunc_type(dfn))
+DEFINE_LHASH_OF_INTERNAL(OPENSSL_CSTRING);
+#define lh_OPENSSL_CSTRING_new(hfn, cmp) ((LHASH_OF(OPENSSL_CSTRING) *)OPENSSL_LH_new(ossl_check_OPENSSL_CSTRING_lh_hashfunc_type(hfn), ossl_check_OPENSSL_CSTRING_lh_compfunc_type(cmp)))
+#define lh_OPENSSL_CSTRING_free(lh) OPENSSL_LH_free(ossl_check_OPENSSL_CSTRING_lh_type(lh))
+#define lh_OPENSSL_CSTRING_flush(lh) OPENSSL_LH_flush(ossl_check_OPENSSL_CSTRING_lh_type(lh))
+#define lh_OPENSSL_CSTRING_insert(lh, ptr) ((OPENSSL_CSTRING *)OPENSSL_LH_insert(ossl_check_OPENSSL_CSTRING_lh_type(lh), ossl_check_OPENSSL_CSTRING_lh_plain_type(ptr)))
+#define lh_OPENSSL_CSTRING_delete(lh, ptr) ((OPENSSL_CSTRING *)OPENSSL_LH_delete(ossl_check_OPENSSL_CSTRING_lh_type(lh), ossl_check_const_OPENSSL_CSTRING_lh_plain_type(ptr)))
+#define lh_OPENSSL_CSTRING_retrieve(lh, ptr) ((OPENSSL_CSTRING *)OPENSSL_LH_retrieve(ossl_check_OPENSSL_CSTRING_lh_type(lh), ossl_check_const_OPENSSL_CSTRING_lh_plain_type(ptr)))
+#define lh_OPENSSL_CSTRING_error(lh) OPENSSL_LH_error(ossl_check_OPENSSL_CSTRING_lh_type(lh))
+#define lh_OPENSSL_CSTRING_num_items(lh) OPENSSL_LH_num_items(ossl_check_OPENSSL_CSTRING_lh_type(lh))
+#define lh_OPENSSL_CSTRING_node_stats_bio(lh, out) OPENSSL_LH_node_stats_bio(ossl_check_const_OPENSSL_CSTRING_lh_type(lh), out)
+#define lh_OPENSSL_CSTRING_node_usage_stats_bio(lh, out) OPENSSL_LH_node_usage_stats_bio(ossl_check_const_OPENSSL_CSTRING_lh_type(lh), out)
+#define lh_OPENSSL_CSTRING_stats_bio(lh, out) OPENSSL_LH_stats_bio(ossl_check_const_OPENSSL_CSTRING_lh_type(lh), out)
+#define lh_OPENSSL_CSTRING_get_down_load(lh) OPENSSL_LH_get_down_load(ossl_check_OPENSSL_CSTRING_lh_type(lh))
+#define lh_OPENSSL_CSTRING_set_down_load(lh, dl) OPENSSL_LH_set_down_load(ossl_check_OPENSSL_CSTRING_lh_type(lh), dl)
+#define lh_OPENSSL_CSTRING_doall(lh, dfn) OPENSSL_LH_doall(ossl_check_OPENSSL_CSTRING_lh_type(lh), ossl_check_OPENSSL_CSTRING_lh_doallfunc_type(dfn))
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/lhash.h.in b/include/openssl/lhash.h.in
new file mode 100644
index 00000000..febefa3c
--- /dev/null
+++ b/include/openssl/lhash.h.in
@@ -0,0 +1,263 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_lhash_macros);
+-}
+
+/*
+ * Header for dynamic hash table routines Author - Eric Young
+ */
+
+#ifndef OPENSSL_LHASH_H
+# define OPENSSL_LHASH_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_LHASH_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/bio.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct lhash_node_st OPENSSL_LH_NODE;
+typedef int (*OPENSSL_LH_COMPFUNC) (const void *, const void *);
+typedef unsigned long (*OPENSSL_LH_HASHFUNC) (const void *);
+typedef void (*OPENSSL_LH_DOALL_FUNC) (void *);
+typedef void (*OPENSSL_LH_DOALL_FUNCARG) (void *, void *);
+typedef struct lhash_st OPENSSL_LHASH;
+
+/*
+ * Macros for declaring and implementing type-safe wrappers for LHASH
+ * callbacks. This way, callbacks can be provided to LHASH structures without
+ * function pointer casting and the macro-defined callbacks provide
+ * per-variable casting before deferring to the underlying type-specific
+ * callbacks. NB: It is possible to place a "static" in front of both the
+ * DECLARE and IMPLEMENT macros if the functions are strictly internal.
+ */
+
+/* First: "hash" functions */
+# define DECLARE_LHASH_HASH_FN(name, o_type) \
+ unsigned long name##_LHASH_HASH(const void *);
+# define IMPLEMENT_LHASH_HASH_FN(name, o_type) \
+ unsigned long name##_LHASH_HASH(const void *arg) { \
+ const o_type *a = arg; \
+ return name##_hash(a); }
+# define LHASH_HASH_FN(name) name##_LHASH_HASH
+
+/* Second: "compare" functions */
+# define DECLARE_LHASH_COMP_FN(name, o_type) \
+ int name##_LHASH_COMP(const void *, const void *);
+# define IMPLEMENT_LHASH_COMP_FN(name, o_type) \
+ int name##_LHASH_COMP(const void *arg1, const void *arg2) { \
+ const o_type *a = arg1; \
+ const o_type *b = arg2; \
+ return name##_cmp(a,b); }
+# define LHASH_COMP_FN(name) name##_LHASH_COMP
+
+/* Fourth: "doall_arg" functions */
+# define DECLARE_LHASH_DOALL_ARG_FN(name, o_type, a_type) \
+ void name##_LHASH_DOALL_ARG(void *, void *);
+# define IMPLEMENT_LHASH_DOALL_ARG_FN(name, o_type, a_type) \
+ void name##_LHASH_DOALL_ARG(void *arg1, void *arg2) { \
+ o_type *a = arg1; \
+ a_type *b = arg2; \
+ name##_doall_arg(a, b); }
+# define LHASH_DOALL_ARG_FN(name) name##_LHASH_DOALL_ARG
+
+
+# define LH_LOAD_MULT 256
+
+int OPENSSL_LH_error(OPENSSL_LHASH *lh);
+OPENSSL_LHASH *OPENSSL_LH_new(OPENSSL_LH_HASHFUNC h, OPENSSL_LH_COMPFUNC c);
+void OPENSSL_LH_free(OPENSSL_LHASH *lh);
+void OPENSSL_LH_flush(OPENSSL_LHASH *lh);
+void *OPENSSL_LH_insert(OPENSSL_LHASH *lh, void *data);
+void *OPENSSL_LH_delete(OPENSSL_LHASH *lh, const void *data);
+void *OPENSSL_LH_retrieve(OPENSSL_LHASH *lh, const void *data);
+void OPENSSL_LH_doall(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNC func);
+void OPENSSL_LH_doall_arg(OPENSSL_LHASH *lh, OPENSSL_LH_DOALL_FUNCARG func, void *arg);
+unsigned long OPENSSL_LH_strhash(const char *c);
+unsigned long OPENSSL_LH_num_items(const OPENSSL_LHASH *lh);
+unsigned long OPENSSL_LH_get_down_load(const OPENSSL_LHASH *lh);
+void OPENSSL_LH_set_down_load(OPENSSL_LHASH *lh, unsigned long down_load);
+
+# ifndef OPENSSL_NO_STDIO
+void OPENSSL_LH_stats(const OPENSSL_LHASH *lh, FILE *fp);
+void OPENSSL_LH_node_stats(const OPENSSL_LHASH *lh, FILE *fp);
+void OPENSSL_LH_node_usage_stats(const OPENSSL_LHASH *lh, FILE *fp);
+# endif
+void OPENSSL_LH_stats_bio(const OPENSSL_LHASH *lh, BIO *out);
+void OPENSSL_LH_node_stats_bio(const OPENSSL_LHASH *lh, BIO *out);
+void OPENSSL_LH_node_usage_stats_bio(const OPENSSL_LHASH *lh, BIO *out);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define _LHASH OPENSSL_LHASH
+# define LHASH_NODE OPENSSL_LH_NODE
+# define lh_error OPENSSL_LH_error
+# define lh_new OPENSSL_LH_new
+# define lh_free OPENSSL_LH_free
+# define lh_insert OPENSSL_LH_insert
+# define lh_delete OPENSSL_LH_delete
+# define lh_retrieve OPENSSL_LH_retrieve
+# define lh_doall OPENSSL_LH_doall
+# define lh_doall_arg OPENSSL_LH_doall_arg
+# define lh_strhash OPENSSL_LH_strhash
+# define lh_num_items OPENSSL_LH_num_items
+# ifndef OPENSSL_NO_STDIO
+# define lh_stats OPENSSL_LH_stats
+# define lh_node_stats OPENSSL_LH_node_stats
+# define lh_node_usage_stats OPENSSL_LH_node_usage_stats
+# endif
+# define lh_stats_bio OPENSSL_LH_stats_bio
+# define lh_node_stats_bio OPENSSL_LH_node_stats_bio
+# define lh_node_usage_stats_bio OPENSSL_LH_node_usage_stats_bio
+# endif
+
+/* Type checking... */
+
+# define LHASH_OF(type) struct lhash_st_##type
+
+/* Helper macro for internal use */
+# define DEFINE_LHASH_OF_INTERNAL(type) \
+ LHASH_OF(type) { union lh_##type##_dummy { void* d1; unsigned long d2; int d3; } dummy; }; \
+ typedef int (*lh_##type##_compfunc)(const type *a, const type *b); \
+ typedef unsigned long (*lh_##type##_hashfunc)(const type *a); \
+ typedef void (*lh_##type##_doallfunc)(type *a); \
+ static ossl_unused ossl_inline type *ossl_check_##type##_lh_plain_type(type *ptr) \
+ { \
+ return ptr; \
+ } \
+ static ossl_unused ossl_inline const type *ossl_check_const_##type##_lh_plain_type(const type *ptr) \
+ { \
+ return ptr; \
+ } \
+ static ossl_unused ossl_inline const OPENSSL_LHASH *ossl_check_const_##type##_lh_type(const LHASH_OF(type) *lh) \
+ { \
+ return (const OPENSSL_LHASH *)lh; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LHASH *ossl_check_##type##_lh_type(LHASH_OF(type) *lh) \
+ { \
+ return (OPENSSL_LHASH *)lh; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LH_COMPFUNC ossl_check_##type##_lh_compfunc_type(lh_##type##_compfunc cmp) \
+ { \
+ return (OPENSSL_LH_COMPFUNC)cmp; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LH_HASHFUNC ossl_check_##type##_lh_hashfunc_type(lh_##type##_hashfunc hfn) \
+ { \
+ return (OPENSSL_LH_HASHFUNC)hfn; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_LH_DOALL_FUNC ossl_check_##type##_lh_doallfunc_type(lh_##type##_doallfunc dfn) \
+ { \
+ return (OPENSSL_LH_DOALL_FUNC)dfn; \
+ } \
+ LHASH_OF(type)
+
+# define DEFINE_LHASH_OF(type) \
+ LHASH_OF(type) { union lh_##type##_dummy { void* d1; unsigned long d2; int d3; } dummy; }; \
+ static ossl_unused ossl_inline LHASH_OF(type) *lh_##type##_new(unsigned long (*hfn)(const type *), \
+ int (*cfn)(const type *, const type *)) \
+ { \
+ return (LHASH_OF(type) *) \
+ OPENSSL_LH_new((OPENSSL_LH_HASHFUNC)hfn, (OPENSSL_LH_COMPFUNC)cfn); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_free(LHASH_OF(type) *lh) \
+ { \
+ OPENSSL_LH_free((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_flush(LHASH_OF(type) *lh) \
+ { \
+ OPENSSL_LH_flush((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline type *lh_##type##_insert(LHASH_OF(type) *lh, type *d) \
+ { \
+ return (type *)OPENSSL_LH_insert((OPENSSL_LHASH *)lh, d); \
+ } \
+ static ossl_unused ossl_inline type *lh_##type##_delete(LHASH_OF(type) *lh, const type *d) \
+ { \
+ return (type *)OPENSSL_LH_delete((OPENSSL_LHASH *)lh, d); \
+ } \
+ static ossl_unused ossl_inline type *lh_##type##_retrieve(LHASH_OF(type) *lh, const type *d) \
+ { \
+ return (type *)OPENSSL_LH_retrieve((OPENSSL_LHASH *)lh, d); \
+ } \
+ static ossl_unused ossl_inline int lh_##type##_error(LHASH_OF(type) *lh) \
+ { \
+ return OPENSSL_LH_error((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline unsigned long lh_##type##_num_items(LHASH_OF(type) *lh) \
+ { \
+ return OPENSSL_LH_num_items((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_node_stats_bio(const LHASH_OF(type) *lh, BIO *out) \
+ { \
+ OPENSSL_LH_node_stats_bio((const OPENSSL_LHASH *)lh, out); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_node_usage_stats_bio(const LHASH_OF(type) *lh, BIO *out) \
+ { \
+ OPENSSL_LH_node_usage_stats_bio((const OPENSSL_LHASH *)lh, out); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_stats_bio(const LHASH_OF(type) *lh, BIO *out) \
+ { \
+ OPENSSL_LH_stats_bio((const OPENSSL_LHASH *)lh, out); \
+ } \
+ static ossl_unused ossl_inline unsigned long lh_##type##_get_down_load(LHASH_OF(type) *lh) \
+ { \
+ return OPENSSL_LH_get_down_load((OPENSSL_LHASH *)lh); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_set_down_load(LHASH_OF(type) *lh, unsigned long dl) \
+ { \
+ OPENSSL_LH_set_down_load((OPENSSL_LHASH *)lh, dl); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_doall(LHASH_OF(type) *lh, \
+ void (*doall)(type *)) \
+ { \
+ OPENSSL_LH_doall((OPENSSL_LHASH *)lh, (OPENSSL_LH_DOALL_FUNC)doall); \
+ } \
+ static ossl_unused ossl_inline void lh_##type##_doall_arg(LHASH_OF(type) *lh, \
+ void (*doallarg)(type *, void *), \
+ void *arg) \
+ { \
+ OPENSSL_LH_doall_arg((OPENSSL_LHASH *)lh, \
+ (OPENSSL_LH_DOALL_FUNCARG)doallarg, arg); \
+ } \
+ LHASH_OF(type)
+
+#define IMPLEMENT_LHASH_DOALL_ARG_CONST(type, argtype) \
+ int_implement_lhash_doall(type, argtype, const type)
+
+#define IMPLEMENT_LHASH_DOALL_ARG(type, argtype) \
+ int_implement_lhash_doall(type, argtype, type)
+
+#define int_implement_lhash_doall(type, argtype, cbargtype) \
+ static ossl_unused ossl_inline void \
+ lh_##type##_doall_##argtype(LHASH_OF(type) *lh, \
+ void (*fn)(cbargtype *, argtype *), \
+ argtype *arg) \
+ { \
+ OPENSSL_LH_doall_arg((OPENSSL_LHASH *)lh, (OPENSSL_LH_DOALL_FUNCARG)fn, (void *)arg); \
+ } \
+ LHASH_OF(type)
+
+{-
+ generate_lhash_macros("OPENSSL_STRING")
+ .generate_lhash_macros("OPENSSL_CSTRING");
+-}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/macros.h b/include/openssl/macros.h
new file mode 100644
index 00000000..a6bc3f1f
--- /dev/null
+++ b/include/openssl/macros.h
@@ -0,0 +1,304 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_MACROS_H
+# define OPENSSL_MACROS_H
+# pragma once
+
+#include <openssl/opensslconf.h>
+#include <openssl/opensslv.h>
+
+
+/* Helper macros for CPP string composition */
+# define OPENSSL_MSTR_HELPER(x) #x
+# define OPENSSL_MSTR(x) OPENSSL_MSTR_HELPER(x)
+
+/*
+ * Sometimes OPENSSL_NO_xxx ends up with an empty file and some compilers
+ * don't like that. This will hopefully silence them.
+ */
+# define NON_EMPTY_TRANSLATION_UNIT static void *dummy = &dummy;
+
+/*
+ * Generic deprecation macro
+ *
+ * If OPENSSL_SUPPRESS_DEPRECATED is defined, then OSSL_DEPRECATED and
+ * OSSL_DEPRECATED_FOR become no-ops
+ */
+# ifndef OSSL_DEPRECATED
+# undef OSSL_DEPRECATED_FOR
+# ifndef OPENSSL_SUPPRESS_DEPRECATED
+# if defined(_MSC_VER)
+ /*
+ * MSVC supports __declspec(deprecated) since MSVC 2003 (13.10),
+ * and __declspec(deprecated(message)) since MSVC 2005 (14.00)
+ */
+# if _MSC_VER >= 1400
+# define OSSL_DEPRECATED(since) \
+ __declspec(deprecated("Since OpenSSL " # since))
+# define OSSL_DEPRECATED_FOR(since, message) \
+ __declspec(deprecated("Since OpenSSL " # since ";" message))
+# elif _MSC_VER >= 1310
+# define OSSL_DEPRECATED(since) __declspec(deprecated)
+# define OSSL_DEPRECATED_FOR(since, message) __declspec(deprecated)
+# endif
+# elif defined(__GNUC__)
+ /*
+ * According to GCC documentation, deprecations with message appeared in
+ * GCC 4.5.0
+ */
+# if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
+# define OSSL_DEPRECATED(since) \
+ __attribute__((deprecated("Since OpenSSL " # since)))
+# define OSSL_DEPRECATED_FOR(since, message) \
+ __attribute__((deprecated("Since OpenSSL " # since ";" message)))
+# elif __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ > 0)
+# define OSSL_DEPRECATED(since) __attribute__((deprecated))
+# define OSSL_DEPRECATED_FOR(since, message) __attribute__((deprecated))
+# endif
+# elif defined(__SUNPRO_C)
+# if (__SUNPRO_C >= 0x5130)
+# define OSSL_DEPRECATED(since) __attribute__ ((deprecated))
+# define OSSL_DEPRECATED_FOR(since, message) __attribute__ ((deprecated))
+# endif
+# endif
+# endif
+# endif
+
+/*
+ * Still not defined? Then define no-op macros. This means these macros
+ * are unsuitable for use in a typedef.
+ */
+# ifndef OSSL_DEPRECATED
+# define OSSL_DEPRECATED(since) extern
+# define OSSL_DEPRECATED_FOR(since, message) extern
+# endif
+
+/*
+ * Applications should use -DOPENSSL_API_COMPAT=<version> to suppress the
+ * declarations of functions deprecated in or before <version>. If this is
+ * undefined, the value of the macro OPENSSL_CONFIGURED_API (defined in
+ * <openssl/opensslconf.h>) is the default.
+ *
+ * For any version number up until version 1.1.x, <version> is expected to be
+ * the calculated version number 0xMNNFFPPSL.
+ * For version numbers 3.0 and on, <version> is expected to be a computation
+ * of the major and minor numbers in decimal using this formula:
+ *
+ * MAJOR * 10000 + MINOR * 100
+ *
+ * So version 3.0 becomes 30000, version 3.2 becomes 30200, etc.
+ */
+
+/*
+ * We use the OPENSSL_API_COMPAT value to define API level macros. These
+ * macros are used to enable or disable features at that API version boundary.
+ */
+
+# ifdef OPENSSL_API_LEVEL
+# error "OPENSSL_API_LEVEL must not be defined by application"
+# endif
+
+/*
+ * We figure out what API level was intended by simple numeric comparison.
+ * The lowest old style number we recognise is 0x00908000L, so we take some
+ * safety margin and assume that anything below 0x00900000L is a new style
+ * number. This allows new versions up to and including v943.71.83.
+ */
+# ifdef OPENSSL_API_COMPAT
+# if OPENSSL_API_COMPAT < 0x900000L
+# define OPENSSL_API_LEVEL (OPENSSL_API_COMPAT)
+# else
+# define OPENSSL_API_LEVEL \
+ (((OPENSSL_API_COMPAT >> 28) & 0xF) * 10000 \
+ + ((OPENSSL_API_COMPAT >> 20) & 0xFF) * 100 \
+ + ((OPENSSL_API_COMPAT >> 12) & 0xFF))
+# endif
+# endif
+
+/*
+ * If OPENSSL_API_COMPAT wasn't given, we use default numbers to set
+ * the API compatibility level.
+ */
+# ifndef OPENSSL_API_LEVEL
+# if OPENSSL_CONFIGURED_API > 0
+# define OPENSSL_API_LEVEL (OPENSSL_CONFIGURED_API)
+# else
+# define OPENSSL_API_LEVEL \
+ (OPENSSL_VERSION_MAJOR * 10000 + OPENSSL_VERSION_MINOR * 100)
+# endif
+# endif
+
+# if OPENSSL_API_LEVEL > OPENSSL_CONFIGURED_API
+# error "The requested API level higher than the configured API compatibility level"
+# endif
+
+/*
+ * Check of sane values.
+ */
+/* Can't go higher than the current version. */
+# if OPENSSL_API_LEVEL > (OPENSSL_VERSION_MAJOR * 10000 + OPENSSL_VERSION_MINOR * 100)
+# error "OPENSSL_API_COMPAT expresses an impossible API compatibility level"
+# endif
+/* OpenSSL will have no version 2.y.z */
+# if OPENSSL_API_LEVEL < 30000 && OPENSSL_API_LEVEL >= 20000
+# error "OPENSSL_API_COMPAT expresses an impossible API compatibility level"
+# endif
+/* Below 0.9.8 is unacceptably low */
+# if OPENSSL_API_LEVEL < 908
+# error "OPENSSL_API_COMPAT expresses an impossible API compatibility level"
+# endif
+
+/*
+ * Define macros for deprecation and simulated removal purposes.
+ *
+ * The macros OSSL_DEPRECATED_{major}_{minor} are always defined for
+ * all OpenSSL versions we care for. They can be used as attributes
+ * in function declarations where appropriate.
+ *
+ * The macros OPENSSL_NO_DEPRECATED_{major}_{minor} are defined for
+ * all OpenSSL versions up to or equal to the version given with
+ * OPENSSL_API_COMPAT. They are used as guards around anything that's
+ * deprecated up to that version, as an effect of the developer option
+ * 'no-deprecated'.
+ */
+
+# undef OPENSSL_NO_DEPRECATED_3_0
+# undef OPENSSL_NO_DEPRECATED_1_1_1
+# undef OPENSSL_NO_DEPRECATED_1_1_0
+# undef OPENSSL_NO_DEPRECATED_1_0_2
+# undef OPENSSL_NO_DEPRECATED_1_0_1
+# undef OPENSSL_NO_DEPRECATED_1_0_0
+# undef OPENSSL_NO_DEPRECATED_0_9_8
+
+# if OPENSSL_API_LEVEL >= 30000
+# ifndef OPENSSL_NO_DEPRECATED
+# define OSSL_DEPRECATEDIN_3_0 OSSL_DEPRECATED(3.0)
+# define OSSL_DEPRECATEDIN_3_0_FOR(msg) OSSL_DEPRECATED_FOR(3.0, msg)
+# else
+# define OPENSSL_NO_DEPRECATED_3_0
+# endif
+# else
+# define OSSL_DEPRECATEDIN_3_0
+# define OSSL_DEPRECATEDIN_3_0_FOR(msg)
+# endif
+# if OPENSSL_API_LEVEL >= 10101
+# ifndef OPENSSL_NO_DEPRECATED
+# define OSSL_DEPRECATEDIN_1_1_1 OSSL_DEPRECATED(1.1.1)
+# define OSSL_DEPRECATEDIN_1_1_1_FOR(msg) OSSL_DEPRECATED_FOR(1.1.1, msg)
+# else
+# define OPENSSL_NO_DEPRECATED_1_1_1
+# endif
+# else
+# define OSSL_DEPRECATEDIN_1_1_1
+# define OSSL_DEPRECATEDIN_1_1_1_FOR(msg)
+# endif
+# if OPENSSL_API_LEVEL >= 10100
+# ifndef OPENSSL_NO_DEPRECATED
+# define OSSL_DEPRECATEDIN_1_1_0 OSSL_DEPRECATED(1.1.0)
+# define OSSL_DEPRECATEDIN_1_1_0_FOR(msg) OSSL_DEPRECATED_FOR(1.1.0, msg)
+# else
+# define OPENSSL_NO_DEPRECATED_1_1_0
+# endif
+# else
+# define OSSL_DEPRECATEDIN_1_1_0
+# define OSSL_DEPRECATEDIN_1_1_0_FOR(msg)
+# endif
+# if OPENSSL_API_LEVEL >= 10002
+# ifndef OPENSSL_NO_DEPRECATED
+# define OSSL_DEPRECATEDIN_1_0_2 OSSL_DEPRECATED(1.0.2)
+# define OSSL_DEPRECATEDIN_1_0_2_FOR(msg) OSSL_DEPRECATED_FOR(1.0.2, msg)
+# else
+# define OPENSSL_NO_DEPRECATED_1_0_2
+# endif
+# else
+# define OSSL_DEPRECATEDIN_1_0_2
+# define OSSL_DEPRECATEDIN_1_0_2_FOR(msg)
+# endif
+# if OPENSSL_API_LEVEL >= 10001
+# ifndef OPENSSL_NO_DEPRECATED
+# define OSSL_DEPRECATEDIN_1_0_1 OSSL_DEPRECATED(1.0.1)
+# define OSSL_DEPRECATEDIN_1_0_1_FOR(msg) OSSL_DEPRECATED_FOR(1.0.1, msg)
+# else
+# define OPENSSL_NO_DEPRECATED_1_0_1
+# endif
+# else
+# define OSSL_DEPRECATEDIN_1_0_1
+# define OSSL_DEPRECATEDIN_1_0_1_FOR(msg)
+# endif
+# if OPENSSL_API_LEVEL >= 10000
+# ifndef OPENSSL_NO_DEPRECATED
+# define OSSL_DEPRECATEDIN_1_0_0 OSSL_DEPRECATED(1.0.0)
+# define OSSL_DEPRECATEDIN_1_0_0_FOR(msg) OSSL_DEPRECATED_FOR(1.0.0, msg)
+# else
+# define OPENSSL_NO_DEPRECATED_1_0_0
+# endif
+# else
+# define OSSL_DEPRECATEDIN_1_0_0
+# define OSSL_DEPRECATEDIN_1_0_0_FOR(msg)
+# endif
+# if OPENSSL_API_LEVEL >= 908
+# ifndef OPENSSL_NO_DEPRECATED
+# define OSSL_DEPRECATEDIN_0_9_8 OSSL_DEPRECATED(0.9.8)
+# define OSSL_DEPRECATEDIN_0_9_8_FOR(msg) OSSL_DEPRECATED_FOR(0.9.8, msg)
+# else
+# define OPENSSL_NO_DEPRECATED_0_9_8
+# endif
+# else
+# define OSSL_DEPRECATEDIN_0_9_8
+# define OSSL_DEPRECATEDIN_0_9_8_FOR(msg)
+# endif
+
+/*
+ * Make our own variants of __FILE__ and __LINE__, depending on configuration
+ */
+
+# ifndef OPENSSL_FILE
+# ifdef OPENSSL_NO_FILENAMES
+# define OPENSSL_FILE ""
+# define OPENSSL_LINE 0
+# else
+# define OPENSSL_FILE __FILE__
+# define OPENSSL_LINE __LINE__
+# endif
+# endif
+
+/*
+ * __func__ was standardized in C99, so for any compiler that claims
+ * to implement that language level or newer, we assume we can safely
+ * use that symbol.
+ *
+ * GNU C also provides __FUNCTION__ since version 2, which predates
+ * C99. We can, however, only use this if __STDC_VERSION__ exists,
+ * as it's otherwise not allowed according to ISO C standards (C90).
+ * (compiling with GNU C's -pedantic tells us so)
+ *
+ * If none of the above applies, we check if the compiler is MSVC,
+ * and use __FUNCTION__ if that's the case.
+ */
+# ifndef OPENSSL_FUNC
+# if defined(__STDC_VERSION__)
+# if __STDC_VERSION__ >= 199901L
+# define OPENSSL_FUNC __func__
+# elif defined(__GNUC__) && __GNUC__ >= 2
+# define OPENSSL_FUNC __FUNCTION__
+# endif
+# elif defined(_MSC_VER)
+# define OPENSSL_FUNC __FUNCTION__
+# endif
+/*
+ * If all these possibilities are exhausted, we give up and use a
+ * static string.
+ */
+# ifndef OPENSSL_FUNC
+# define OPENSSL_FUNC "(unknown function)"
+# endif
+# endif
+
+#endif /* OPENSSL_MACROS_H */
diff --git a/include/openssl/md2.h b/include/openssl/md2.h
new file mode 100644
index 00000000..5d4cb77e
--- /dev/null
+++ b/include/openssl/md2.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_MD2_H
+# define OPENSSL_MD2_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_MD2_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_MD2
+# include <stddef.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define MD2_DIGEST_LENGTH 16
+
+# if !defined(OPENSSL_NO_DEPRECATED_3_0)
+
+typedef unsigned char MD2_INT;
+
+# define MD2_BLOCK 16
+
+typedef struct MD2state_st {
+ unsigned int num;
+ unsigned char data[MD2_BLOCK];
+ MD2_INT cksm[MD2_BLOCK];
+ MD2_INT state[MD2_BLOCK];
+} MD2_CTX;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *MD2_options(void);
+OSSL_DEPRECATEDIN_3_0 int MD2_Init(MD2_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int MD2_Update(MD2_CTX *c, const unsigned char *data,
+ size_t len);
+OSSL_DEPRECATEDIN_3_0 int MD2_Final(unsigned char *md, MD2_CTX *c);
+OSSL_DEPRECATEDIN_3_0 unsigned char *MD2(const unsigned char *d, size_t n,
+ unsigned char *md);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/md4.h b/include/openssl/md4.h
new file mode 100644
index 00000000..6c150a6c
--- /dev/null
+++ b/include/openssl/md4.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_MD4_H
+# define OPENSSL_MD4_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_MD4_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_MD4
+# include <openssl/e_os2.h>
+# include <stddef.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define MD4_DIGEST_LENGTH 16
+
+# if !defined(OPENSSL_NO_DEPRECATED_3_0)
+
+/*-
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ * ! MD4_LONG has to be at least 32 bits wide. !
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ */
+# define MD4_LONG unsigned int
+
+# define MD4_CBLOCK 64
+# define MD4_LBLOCK (MD4_CBLOCK/4)
+
+typedef struct MD4state_st {
+ MD4_LONG A, B, C, D;
+ MD4_LONG Nl, Nh;
+ MD4_LONG data[MD4_LBLOCK];
+ unsigned int num;
+} MD4_CTX;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int MD4_Init(MD4_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int MD4_Update(MD4_CTX *c, const void *data, size_t len);
+OSSL_DEPRECATEDIN_3_0 int MD4_Final(unsigned char *md, MD4_CTX *c);
+OSSL_DEPRECATEDIN_3_0 unsigned char *MD4(const unsigned char *d, size_t n,
+ unsigned char *md);
+OSSL_DEPRECATEDIN_3_0 void MD4_Transform(MD4_CTX *c, const unsigned char *b);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/md5.h b/include/openssl/md5.h
new file mode 100644
index 00000000..77a57734
--- /dev/null
+++ b/include/openssl/md5.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_MD5_H
+# define OPENSSL_MD5_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_MD5_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_MD5
+# include <openssl/e_os2.h>
+# include <stddef.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define MD5_DIGEST_LENGTH 16
+
+# if !defined(OPENSSL_NO_DEPRECATED_3_0)
+/*
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ * ! MD5_LONG has to be at least 32 bits wide. !
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ */
+# define MD5_LONG unsigned int
+
+# define MD5_CBLOCK 64
+# define MD5_LBLOCK (MD5_CBLOCK/4)
+
+typedef struct MD5state_st {
+ MD5_LONG A, B, C, D;
+ MD5_LONG Nl, Nh;
+ MD5_LONG data[MD5_LBLOCK];
+ unsigned int num;
+} MD5_CTX;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int MD5_Init(MD5_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int MD5_Update(MD5_CTX *c, const void *data, size_t len);
+OSSL_DEPRECATEDIN_3_0 int MD5_Final(unsigned char *md, MD5_CTX *c);
+OSSL_DEPRECATEDIN_3_0 unsigned char *MD5(const unsigned char *d, size_t n,
+ unsigned char *md);
+OSSL_DEPRECATEDIN_3_0 void MD5_Transform(MD5_CTX *c, const unsigned char *b);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/mdc2.h b/include/openssl/mdc2.h
new file mode 100644
index 00000000..5a7ee289
--- /dev/null
+++ b/include/openssl/mdc2.h
@@ -0,0 +1,55 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_MDC2_H
+# define OPENSSL_MDC2_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_MDC2_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_MDC2
+# include <stdlib.h>
+# include <openssl/des.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define MDC2_DIGEST_LENGTH 16
+
+# if !defined(OPENSSL_NO_DEPRECATED_3_0)
+
+# define MDC2_BLOCK 8
+
+typedef struct mdc2_ctx_st {
+ unsigned int num;
+ unsigned char data[MDC2_BLOCK];
+ DES_cblock h, hh;
+ unsigned int pad_type; /* either 1 or 2, default 1 */
+} MDC2_CTX;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int MDC2_Init(MDC2_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int MDC2_Update(MDC2_CTX *c, const unsigned char *data,
+ size_t len);
+OSSL_DEPRECATEDIN_3_0 int MDC2_Final(unsigned char *md, MDC2_CTX *c);
+OSSL_DEPRECATEDIN_3_0 unsigned char *MDC2(const unsigned char *d, size_t n,
+ unsigned char *md);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/modes.h b/include/openssl/modes.h
new file mode 100644
index 00000000..e1907991
--- /dev/null
+++ b/include/openssl/modes.h
@@ -0,0 +1,219 @@
+/*
+ * Copyright 2008-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_MODES_H
+# define OPENSSL_MODES_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_MODES_H
+# endif
+
+# include <stddef.h>
+# include <openssl/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+typedef void (*block128_f) (const unsigned char in[16],
+ unsigned char out[16], const void *key);
+
+typedef void (*cbc128_f) (const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], int enc);
+
+typedef void (*ecb128_f) (const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ int enc);
+
+typedef void (*ctr128_f) (const unsigned char *in, unsigned char *out,
+ size_t blocks, const void *key,
+ const unsigned char ivec[16]);
+
+typedef void (*ccm128_f) (const unsigned char *in, unsigned char *out,
+ size_t blocks, const void *key,
+ const unsigned char ivec[16],
+ unsigned char cmac[16]);
+
+void CRYPTO_cbc128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], block128_f block);
+void CRYPTO_cbc128_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], block128_f block);
+
+void CRYPTO_ctr128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16],
+ unsigned char ecount_buf[16], unsigned int *num,
+ block128_f block);
+
+void CRYPTO_ctr128_encrypt_ctr32(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16],
+ unsigned char ecount_buf[16],
+ unsigned int *num, ctr128_f ctr);
+
+void CRYPTO_ofb128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], int *num,
+ block128_f block);
+
+void CRYPTO_cfb128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], int *num,
+ int enc, block128_f block);
+void CRYPTO_cfb128_8_encrypt(const unsigned char *in, unsigned char *out,
+ size_t length, const void *key,
+ unsigned char ivec[16], int *num,
+ int enc, block128_f block);
+void CRYPTO_cfb128_1_encrypt(const unsigned char *in, unsigned char *out,
+ size_t bits, const void *key,
+ unsigned char ivec[16], int *num,
+ int enc, block128_f block);
+
+size_t CRYPTO_cts128_encrypt_block(const unsigned char *in,
+ unsigned char *out, size_t len,
+ const void *key, unsigned char ivec[16],
+ block128_f block);
+size_t CRYPTO_cts128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], cbc128_f cbc);
+size_t CRYPTO_cts128_decrypt_block(const unsigned char *in,
+ unsigned char *out, size_t len,
+ const void *key, unsigned char ivec[16],
+ block128_f block);
+size_t CRYPTO_cts128_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], cbc128_f cbc);
+
+size_t CRYPTO_nistcts128_encrypt_block(const unsigned char *in,
+ unsigned char *out, size_t len,
+ const void *key,
+ unsigned char ivec[16],
+ block128_f block);
+size_t CRYPTO_nistcts128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], cbc128_f cbc);
+size_t CRYPTO_nistcts128_decrypt_block(const unsigned char *in,
+ unsigned char *out, size_t len,
+ const void *key,
+ unsigned char ivec[16],
+ block128_f block);
+size_t CRYPTO_nistcts128_decrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const void *key,
+ unsigned char ivec[16], cbc128_f cbc);
+
+typedef struct gcm128_context GCM128_CONTEXT;
+
+GCM128_CONTEXT *CRYPTO_gcm128_new(void *key, block128_f block);
+void CRYPTO_gcm128_init(GCM128_CONTEXT *ctx, void *key, block128_f block);
+void CRYPTO_gcm128_setiv(GCM128_CONTEXT *ctx, const unsigned char *iv,
+ size_t len);
+int CRYPTO_gcm128_aad(GCM128_CONTEXT *ctx, const unsigned char *aad,
+ size_t len);
+int CRYPTO_gcm128_encrypt(GCM128_CONTEXT *ctx,
+ const unsigned char *in, unsigned char *out,
+ size_t len);
+int CRYPTO_gcm128_decrypt(GCM128_CONTEXT *ctx,
+ const unsigned char *in, unsigned char *out,
+ size_t len);
+int CRYPTO_gcm128_encrypt_ctr32(GCM128_CONTEXT *ctx,
+ const unsigned char *in, unsigned char *out,
+ size_t len, ctr128_f stream);
+int CRYPTO_gcm128_decrypt_ctr32(GCM128_CONTEXT *ctx,
+ const unsigned char *in, unsigned char *out,
+ size_t len, ctr128_f stream);
+int CRYPTO_gcm128_finish(GCM128_CONTEXT *ctx, const unsigned char *tag,
+ size_t len);
+void CRYPTO_gcm128_tag(GCM128_CONTEXT *ctx, unsigned char *tag, size_t len);
+void CRYPTO_gcm128_release(GCM128_CONTEXT *ctx);
+
+typedef struct ccm128_context CCM128_CONTEXT;
+
+void CRYPTO_ccm128_init(CCM128_CONTEXT *ctx,
+ unsigned int M, unsigned int L, void *key,
+ block128_f block);
+int CRYPTO_ccm128_setiv(CCM128_CONTEXT *ctx, const unsigned char *nonce,
+ size_t nlen, size_t mlen);
+void CRYPTO_ccm128_aad(CCM128_CONTEXT *ctx, const unsigned char *aad,
+ size_t alen);
+int CRYPTO_ccm128_encrypt(CCM128_CONTEXT *ctx, const unsigned char *inp,
+ unsigned char *out, size_t len);
+int CRYPTO_ccm128_decrypt(CCM128_CONTEXT *ctx, const unsigned char *inp,
+ unsigned char *out, size_t len);
+int CRYPTO_ccm128_encrypt_ccm64(CCM128_CONTEXT *ctx, const unsigned char *inp,
+ unsigned char *out, size_t len,
+ ccm128_f stream);
+int CRYPTO_ccm128_decrypt_ccm64(CCM128_CONTEXT *ctx, const unsigned char *inp,
+ unsigned char *out, size_t len,
+ ccm128_f stream);
+size_t CRYPTO_ccm128_tag(CCM128_CONTEXT *ctx, unsigned char *tag, size_t len);
+
+typedef struct xts128_context XTS128_CONTEXT;
+
+int CRYPTO_xts128_encrypt(const XTS128_CONTEXT *ctx,
+ const unsigned char iv[16],
+ const unsigned char *inp, unsigned char *out,
+ size_t len, int enc);
+
+size_t CRYPTO_128_wrap(void *key, const unsigned char *iv,
+ unsigned char *out,
+ const unsigned char *in, size_t inlen,
+ block128_f block);
+
+size_t CRYPTO_128_unwrap(void *key, const unsigned char *iv,
+ unsigned char *out,
+ const unsigned char *in, size_t inlen,
+ block128_f block);
+size_t CRYPTO_128_wrap_pad(void *key, const unsigned char *icv,
+ unsigned char *out, const unsigned char *in,
+ size_t inlen, block128_f block);
+size_t CRYPTO_128_unwrap_pad(void *key, const unsigned char *icv,
+ unsigned char *out, const unsigned char *in,
+ size_t inlen, block128_f block);
+
+# ifndef OPENSSL_NO_OCB
+typedef struct ocb128_context OCB128_CONTEXT;
+
+typedef void (*ocb128_f) (const unsigned char *in, unsigned char *out,
+ size_t blocks, const void *key,
+ size_t start_block_num,
+ unsigned char offset_i[16],
+ const unsigned char L_[][16],
+ unsigned char checksum[16]);
+
+OCB128_CONTEXT *CRYPTO_ocb128_new(void *keyenc, void *keydec,
+ block128_f encrypt, block128_f decrypt,
+ ocb128_f stream);
+int CRYPTO_ocb128_init(OCB128_CONTEXT *ctx, void *keyenc, void *keydec,
+ block128_f encrypt, block128_f decrypt,
+ ocb128_f stream);
+int CRYPTO_ocb128_copy_ctx(OCB128_CONTEXT *dest, OCB128_CONTEXT *src,
+ void *keyenc, void *keydec);
+int CRYPTO_ocb128_setiv(OCB128_CONTEXT *ctx, const unsigned char *iv,
+ size_t len, size_t taglen);
+int CRYPTO_ocb128_aad(OCB128_CONTEXT *ctx, const unsigned char *aad,
+ size_t len);
+int CRYPTO_ocb128_encrypt(OCB128_CONTEXT *ctx, const unsigned char *in,
+ unsigned char *out, size_t len);
+int CRYPTO_ocb128_decrypt(OCB128_CONTEXT *ctx, const unsigned char *in,
+ unsigned char *out, size_t len);
+int CRYPTO_ocb128_finish(OCB128_CONTEXT *ctx, const unsigned char *tag,
+ size_t len);
+int CRYPTO_ocb128_tag(OCB128_CONTEXT *ctx, unsigned char *tag, size_t len);
+void CRYPTO_ocb128_cleanup(OCB128_CONTEXT *ctx);
+# endif /* OPENSSL_NO_OCB */
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/obj_mac.h b/include/openssl/obj_mac.h
new file mode 100644
index 00000000..0e860276
--- /dev/null
+++ b/include/openssl/obj_mac.h
@@ -0,0 +1,5481 @@
+/*
+ * WARNING: do not edit!
+ * Generated by crypto/objects/objects.pl
+ *
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_OBJ_MAC_H
+# define OPENSSL_OBJ_MAC_H
+# pragma once
+
+#define SN_undef "UNDEF"
+#define LN_undef "undefined"
+#define NID_undef 0
+#define OBJ_undef 0L
+
+#define SN_itu_t "ITU-T"
+#define LN_itu_t "itu-t"
+#define NID_itu_t 645
+#define OBJ_itu_t 0L
+
+#define NID_ccitt 404
+#define OBJ_ccitt OBJ_itu_t
+
+#define SN_iso "ISO"
+#define LN_iso "iso"
+#define NID_iso 181
+#define OBJ_iso 1L
+
+#define SN_joint_iso_itu_t "JOINT-ISO-ITU-T"
+#define LN_joint_iso_itu_t "joint-iso-itu-t"
+#define NID_joint_iso_itu_t 646
+#define OBJ_joint_iso_itu_t 2L
+
+#define NID_joint_iso_ccitt 393
+#define OBJ_joint_iso_ccitt OBJ_joint_iso_itu_t
+
+#define SN_member_body "member-body"
+#define LN_member_body "ISO Member Body"
+#define NID_member_body 182
+#define OBJ_member_body OBJ_iso,2L
+
+#define SN_identified_organization "identified-organization"
+#define NID_identified_organization 676
+#define OBJ_identified_organization OBJ_iso,3L
+
+#define SN_gmac "GMAC"
+#define LN_gmac "gmac"
+#define NID_gmac 1195
+#define OBJ_gmac OBJ_iso,0L,9797L,3L,4L
+
+#define SN_hmac_md5 "HMAC-MD5"
+#define LN_hmac_md5 "hmac-md5"
+#define NID_hmac_md5 780
+#define OBJ_hmac_md5 OBJ_identified_organization,6L,1L,5L,5L,8L,1L,1L
+
+#define SN_hmac_sha1 "HMAC-SHA1"
+#define LN_hmac_sha1 "hmac-sha1"
+#define NID_hmac_sha1 781
+#define OBJ_hmac_sha1 OBJ_identified_organization,6L,1L,5L,5L,8L,1L,2L
+
+#define SN_x509ExtAdmission "x509ExtAdmission"
+#define LN_x509ExtAdmission "Professional Information or basis for Admission"
+#define NID_x509ExtAdmission 1093
+#define OBJ_x509ExtAdmission OBJ_identified_organization,36L,8L,3L,3L
+
+#define SN_certicom_arc "certicom-arc"
+#define NID_certicom_arc 677
+#define OBJ_certicom_arc OBJ_identified_organization,132L
+
+#define SN_ieee "ieee"
+#define NID_ieee 1170
+#define OBJ_ieee OBJ_identified_organization,111L
+
+#define SN_ieee_siswg "ieee-siswg"
+#define LN_ieee_siswg "IEEE Security in Storage Working Group"
+#define NID_ieee_siswg 1171
+#define OBJ_ieee_siswg OBJ_ieee,2L,1619L
+
+#define SN_international_organizations "international-organizations"
+#define LN_international_organizations "International Organizations"
+#define NID_international_organizations 647
+#define OBJ_international_organizations OBJ_joint_iso_itu_t,23L
+
+#define SN_wap "wap"
+#define NID_wap 678
+#define OBJ_wap OBJ_international_organizations,43L
+
+#define SN_wap_wsg "wap-wsg"
+#define NID_wap_wsg 679
+#define OBJ_wap_wsg OBJ_wap,1L
+
+#define SN_selected_attribute_types "selected-attribute-types"
+#define LN_selected_attribute_types "Selected Attribute Types"
+#define NID_selected_attribute_types 394
+#define OBJ_selected_attribute_types OBJ_joint_iso_itu_t,5L,1L,5L
+
+#define SN_clearance "clearance"
+#define NID_clearance 395
+#define OBJ_clearance OBJ_selected_attribute_types,55L
+
+#define SN_ISO_US "ISO-US"
+#define LN_ISO_US "ISO US Member Body"
+#define NID_ISO_US 183
+#define OBJ_ISO_US OBJ_member_body,840L
+
+#define SN_X9_57 "X9-57"
+#define LN_X9_57 "X9.57"
+#define NID_X9_57 184
+#define OBJ_X9_57 OBJ_ISO_US,10040L
+
+#define SN_X9cm "X9cm"
+#define LN_X9cm "X9.57 CM ?"
+#define NID_X9cm 185
+#define OBJ_X9cm OBJ_X9_57,4L
+
+#define SN_ISO_CN "ISO-CN"
+#define LN_ISO_CN "ISO CN Member Body"
+#define NID_ISO_CN 1140
+#define OBJ_ISO_CN OBJ_member_body,156L
+
+#define SN_oscca "oscca"
+#define NID_oscca 1141
+#define OBJ_oscca OBJ_ISO_CN,10197L
+
+#define SN_sm_scheme "sm-scheme"
+#define NID_sm_scheme 1142
+#define OBJ_sm_scheme OBJ_oscca,1L
+
+#define SN_dsa "DSA"
+#define LN_dsa "dsaEncryption"
+#define NID_dsa 116
+#define OBJ_dsa OBJ_X9cm,1L
+
+#define SN_dsaWithSHA1 "DSA-SHA1"
+#define LN_dsaWithSHA1 "dsaWithSHA1"
+#define NID_dsaWithSHA1 113
+#define OBJ_dsaWithSHA1 OBJ_X9cm,3L
+
+#define SN_ansi_X9_62 "ansi-X9-62"
+#define LN_ansi_X9_62 "ANSI X9.62"
+#define NID_ansi_X9_62 405
+#define OBJ_ansi_X9_62 OBJ_ISO_US,10045L
+
+#define OBJ_X9_62_id_fieldType OBJ_ansi_X9_62,1L
+
+#define SN_X9_62_prime_field "prime-field"
+#define NID_X9_62_prime_field 406
+#define OBJ_X9_62_prime_field OBJ_X9_62_id_fieldType,1L
+
+#define SN_X9_62_characteristic_two_field "characteristic-two-field"
+#define NID_X9_62_characteristic_two_field 407
+#define OBJ_X9_62_characteristic_two_field OBJ_X9_62_id_fieldType,2L
+
+#define SN_X9_62_id_characteristic_two_basis "id-characteristic-two-basis"
+#define NID_X9_62_id_characteristic_two_basis 680
+#define OBJ_X9_62_id_characteristic_two_basis OBJ_X9_62_characteristic_two_field,3L
+
+#define SN_X9_62_onBasis "onBasis"
+#define NID_X9_62_onBasis 681
+#define OBJ_X9_62_onBasis OBJ_X9_62_id_characteristic_two_basis,1L
+
+#define SN_X9_62_tpBasis "tpBasis"
+#define NID_X9_62_tpBasis 682
+#define OBJ_X9_62_tpBasis OBJ_X9_62_id_characteristic_two_basis,2L
+
+#define SN_X9_62_ppBasis "ppBasis"
+#define NID_X9_62_ppBasis 683
+#define OBJ_X9_62_ppBasis OBJ_X9_62_id_characteristic_two_basis,3L
+
+#define OBJ_X9_62_id_publicKeyType OBJ_ansi_X9_62,2L
+
+#define SN_X9_62_id_ecPublicKey "id-ecPublicKey"
+#define NID_X9_62_id_ecPublicKey 408
+#define OBJ_X9_62_id_ecPublicKey OBJ_X9_62_id_publicKeyType,1L
+
+#define OBJ_X9_62_ellipticCurve OBJ_ansi_X9_62,3L
+
+#define OBJ_X9_62_c_TwoCurve OBJ_X9_62_ellipticCurve,0L
+
+#define SN_X9_62_c2pnb163v1 "c2pnb163v1"
+#define NID_X9_62_c2pnb163v1 684
+#define OBJ_X9_62_c2pnb163v1 OBJ_X9_62_c_TwoCurve,1L
+
+#define SN_X9_62_c2pnb163v2 "c2pnb163v2"
+#define NID_X9_62_c2pnb163v2 685
+#define OBJ_X9_62_c2pnb163v2 OBJ_X9_62_c_TwoCurve,2L
+
+#define SN_X9_62_c2pnb163v3 "c2pnb163v3"
+#define NID_X9_62_c2pnb163v3 686
+#define OBJ_X9_62_c2pnb163v3 OBJ_X9_62_c_TwoCurve,3L
+
+#define SN_X9_62_c2pnb176v1 "c2pnb176v1"
+#define NID_X9_62_c2pnb176v1 687
+#define OBJ_X9_62_c2pnb176v1 OBJ_X9_62_c_TwoCurve,4L
+
+#define SN_X9_62_c2tnb191v1 "c2tnb191v1"
+#define NID_X9_62_c2tnb191v1 688
+#define OBJ_X9_62_c2tnb191v1 OBJ_X9_62_c_TwoCurve,5L
+
+#define SN_X9_62_c2tnb191v2 "c2tnb191v2"
+#define NID_X9_62_c2tnb191v2 689
+#define OBJ_X9_62_c2tnb191v2 OBJ_X9_62_c_TwoCurve,6L
+
+#define SN_X9_62_c2tnb191v3 "c2tnb191v3"
+#define NID_X9_62_c2tnb191v3 690
+#define OBJ_X9_62_c2tnb191v3 OBJ_X9_62_c_TwoCurve,7L
+
+#define SN_X9_62_c2onb191v4 "c2onb191v4"
+#define NID_X9_62_c2onb191v4 691
+#define OBJ_X9_62_c2onb191v4 OBJ_X9_62_c_TwoCurve,8L
+
+#define SN_X9_62_c2onb191v5 "c2onb191v5"
+#define NID_X9_62_c2onb191v5 692
+#define OBJ_X9_62_c2onb191v5 OBJ_X9_62_c_TwoCurve,9L
+
+#define SN_X9_62_c2pnb208w1 "c2pnb208w1"
+#define NID_X9_62_c2pnb208w1 693
+#define OBJ_X9_62_c2pnb208w1 OBJ_X9_62_c_TwoCurve,10L
+
+#define SN_X9_62_c2tnb239v1 "c2tnb239v1"
+#define NID_X9_62_c2tnb239v1 694
+#define OBJ_X9_62_c2tnb239v1 OBJ_X9_62_c_TwoCurve,11L
+
+#define SN_X9_62_c2tnb239v2 "c2tnb239v2"
+#define NID_X9_62_c2tnb239v2 695
+#define OBJ_X9_62_c2tnb239v2 OBJ_X9_62_c_TwoCurve,12L
+
+#define SN_X9_62_c2tnb239v3 "c2tnb239v3"
+#define NID_X9_62_c2tnb239v3 696
+#define OBJ_X9_62_c2tnb239v3 OBJ_X9_62_c_TwoCurve,13L
+
+#define SN_X9_62_c2onb239v4 "c2onb239v4"
+#define NID_X9_62_c2onb239v4 697
+#define OBJ_X9_62_c2onb239v4 OBJ_X9_62_c_TwoCurve,14L
+
+#define SN_X9_62_c2onb239v5 "c2onb239v5"
+#define NID_X9_62_c2onb239v5 698
+#define OBJ_X9_62_c2onb239v5 OBJ_X9_62_c_TwoCurve,15L
+
+#define SN_X9_62_c2pnb272w1 "c2pnb272w1"
+#define NID_X9_62_c2pnb272w1 699
+#define OBJ_X9_62_c2pnb272w1 OBJ_X9_62_c_TwoCurve,16L
+
+#define SN_X9_62_c2pnb304w1 "c2pnb304w1"
+#define NID_X9_62_c2pnb304w1 700
+#define OBJ_X9_62_c2pnb304w1 OBJ_X9_62_c_TwoCurve,17L
+
+#define SN_X9_62_c2tnb359v1 "c2tnb359v1"
+#define NID_X9_62_c2tnb359v1 701
+#define OBJ_X9_62_c2tnb359v1 OBJ_X9_62_c_TwoCurve,18L
+
+#define SN_X9_62_c2pnb368w1 "c2pnb368w1"
+#define NID_X9_62_c2pnb368w1 702
+#define OBJ_X9_62_c2pnb368w1 OBJ_X9_62_c_TwoCurve,19L
+
+#define SN_X9_62_c2tnb431r1 "c2tnb431r1"
+#define NID_X9_62_c2tnb431r1 703
+#define OBJ_X9_62_c2tnb431r1 OBJ_X9_62_c_TwoCurve,20L
+
+#define OBJ_X9_62_primeCurve OBJ_X9_62_ellipticCurve,1L
+
+#define SN_X9_62_prime192v1 "prime192v1"
+#define NID_X9_62_prime192v1 409
+#define OBJ_X9_62_prime192v1 OBJ_X9_62_primeCurve,1L
+
+#define SN_X9_62_prime192v2 "prime192v2"
+#define NID_X9_62_prime192v2 410
+#define OBJ_X9_62_prime192v2 OBJ_X9_62_primeCurve,2L
+
+#define SN_X9_62_prime192v3 "prime192v3"
+#define NID_X9_62_prime192v3 411
+#define OBJ_X9_62_prime192v3 OBJ_X9_62_primeCurve,3L
+
+#define SN_X9_62_prime239v1 "prime239v1"
+#define NID_X9_62_prime239v1 412
+#define OBJ_X9_62_prime239v1 OBJ_X9_62_primeCurve,4L
+
+#define SN_X9_62_prime239v2 "prime239v2"
+#define NID_X9_62_prime239v2 413
+#define OBJ_X9_62_prime239v2 OBJ_X9_62_primeCurve,5L
+
+#define SN_X9_62_prime239v3 "prime239v3"
+#define NID_X9_62_prime239v3 414
+#define OBJ_X9_62_prime239v3 OBJ_X9_62_primeCurve,6L
+
+#define SN_X9_62_prime256v1 "prime256v1"
+#define NID_X9_62_prime256v1 415
+#define OBJ_X9_62_prime256v1 OBJ_X9_62_primeCurve,7L
+
+#define OBJ_X9_62_id_ecSigType OBJ_ansi_X9_62,4L
+
+#define SN_ecdsa_with_SHA1 "ecdsa-with-SHA1"
+#define NID_ecdsa_with_SHA1 416
+#define OBJ_ecdsa_with_SHA1 OBJ_X9_62_id_ecSigType,1L
+
+#define SN_ecdsa_with_Recommended "ecdsa-with-Recommended"
+#define NID_ecdsa_with_Recommended 791
+#define OBJ_ecdsa_with_Recommended OBJ_X9_62_id_ecSigType,2L
+
+#define SN_ecdsa_with_Specified "ecdsa-with-Specified"
+#define NID_ecdsa_with_Specified 792
+#define OBJ_ecdsa_with_Specified OBJ_X9_62_id_ecSigType,3L
+
+#define SN_ecdsa_with_SHA224 "ecdsa-with-SHA224"
+#define NID_ecdsa_with_SHA224 793
+#define OBJ_ecdsa_with_SHA224 OBJ_ecdsa_with_Specified,1L
+
+#define SN_ecdsa_with_SHA256 "ecdsa-with-SHA256"
+#define NID_ecdsa_with_SHA256 794
+#define OBJ_ecdsa_with_SHA256 OBJ_ecdsa_with_Specified,2L
+
+#define SN_ecdsa_with_SHA384 "ecdsa-with-SHA384"
+#define NID_ecdsa_with_SHA384 795
+#define OBJ_ecdsa_with_SHA384 OBJ_ecdsa_with_Specified,3L
+
+#define SN_ecdsa_with_SHA512 "ecdsa-with-SHA512"
+#define NID_ecdsa_with_SHA512 796
+#define OBJ_ecdsa_with_SHA512 OBJ_ecdsa_with_Specified,4L
+
+#define OBJ_secg_ellipticCurve OBJ_certicom_arc,0L
+
+#define SN_secp112r1 "secp112r1"
+#define NID_secp112r1 704
+#define OBJ_secp112r1 OBJ_secg_ellipticCurve,6L
+
+#define SN_secp112r2 "secp112r2"
+#define NID_secp112r2 705
+#define OBJ_secp112r2 OBJ_secg_ellipticCurve,7L
+
+#define SN_secp128r1 "secp128r1"
+#define NID_secp128r1 706
+#define OBJ_secp128r1 OBJ_secg_ellipticCurve,28L
+
+#define SN_secp128r2 "secp128r2"
+#define NID_secp128r2 707
+#define OBJ_secp128r2 OBJ_secg_ellipticCurve,29L
+
+#define SN_secp160k1 "secp160k1"
+#define NID_secp160k1 708
+#define OBJ_secp160k1 OBJ_secg_ellipticCurve,9L
+
+#define SN_secp160r1 "secp160r1"
+#define NID_secp160r1 709
+#define OBJ_secp160r1 OBJ_secg_ellipticCurve,8L
+
+#define SN_secp160r2 "secp160r2"
+#define NID_secp160r2 710
+#define OBJ_secp160r2 OBJ_secg_ellipticCurve,30L
+
+#define SN_secp192k1 "secp192k1"
+#define NID_secp192k1 711
+#define OBJ_secp192k1 OBJ_secg_ellipticCurve,31L
+
+#define SN_secp224k1 "secp224k1"
+#define NID_secp224k1 712
+#define OBJ_secp224k1 OBJ_secg_ellipticCurve,32L
+
+#define SN_secp224r1 "secp224r1"
+#define NID_secp224r1 713
+#define OBJ_secp224r1 OBJ_secg_ellipticCurve,33L
+
+#define SN_secp256k1 "secp256k1"
+#define NID_secp256k1 714
+#define OBJ_secp256k1 OBJ_secg_ellipticCurve,10L
+
+#define SN_secp384r1 "secp384r1"
+#define NID_secp384r1 715
+#define OBJ_secp384r1 OBJ_secg_ellipticCurve,34L
+
+#define SN_secp521r1 "secp521r1"
+#define NID_secp521r1 716
+#define OBJ_secp521r1 OBJ_secg_ellipticCurve,35L
+
+#define SN_sect113r1 "sect113r1"
+#define NID_sect113r1 717
+#define OBJ_sect113r1 OBJ_secg_ellipticCurve,4L
+
+#define SN_sect113r2 "sect113r2"
+#define NID_sect113r2 718
+#define OBJ_sect113r2 OBJ_secg_ellipticCurve,5L
+
+#define SN_sect131r1 "sect131r1"
+#define NID_sect131r1 719
+#define OBJ_sect131r1 OBJ_secg_ellipticCurve,22L
+
+#define SN_sect131r2 "sect131r2"
+#define NID_sect131r2 720
+#define OBJ_sect131r2 OBJ_secg_ellipticCurve,23L
+
+#define SN_sect163k1 "sect163k1"
+#define NID_sect163k1 721
+#define OBJ_sect163k1 OBJ_secg_ellipticCurve,1L
+
+#define SN_sect163r1 "sect163r1"
+#define NID_sect163r1 722
+#define OBJ_sect163r1 OBJ_secg_ellipticCurve,2L
+
+#define SN_sect163r2 "sect163r2"
+#define NID_sect163r2 723
+#define OBJ_sect163r2 OBJ_secg_ellipticCurve,15L
+
+#define SN_sect193r1 "sect193r1"
+#define NID_sect193r1 724
+#define OBJ_sect193r1 OBJ_secg_ellipticCurve,24L
+
+#define SN_sect193r2 "sect193r2"
+#define NID_sect193r2 725
+#define OBJ_sect193r2 OBJ_secg_ellipticCurve,25L
+
+#define SN_sect233k1 "sect233k1"
+#define NID_sect233k1 726
+#define OBJ_sect233k1 OBJ_secg_ellipticCurve,26L
+
+#define SN_sect233r1 "sect233r1"
+#define NID_sect233r1 727
+#define OBJ_sect233r1 OBJ_secg_ellipticCurve,27L
+
+#define SN_sect239k1 "sect239k1"
+#define NID_sect239k1 728
+#define OBJ_sect239k1 OBJ_secg_ellipticCurve,3L
+
+#define SN_sect283k1 "sect283k1"
+#define NID_sect283k1 729
+#define OBJ_sect283k1 OBJ_secg_ellipticCurve,16L
+
+#define SN_sect283r1 "sect283r1"
+#define NID_sect283r1 730
+#define OBJ_sect283r1 OBJ_secg_ellipticCurve,17L
+
+#define SN_sect409k1 "sect409k1"
+#define NID_sect409k1 731
+#define OBJ_sect409k1 OBJ_secg_ellipticCurve,36L
+
+#define SN_sect409r1 "sect409r1"
+#define NID_sect409r1 732
+#define OBJ_sect409r1 OBJ_secg_ellipticCurve,37L
+
+#define SN_sect571k1 "sect571k1"
+#define NID_sect571k1 733
+#define OBJ_sect571k1 OBJ_secg_ellipticCurve,38L
+
+#define SN_sect571r1 "sect571r1"
+#define NID_sect571r1 734
+#define OBJ_sect571r1 OBJ_secg_ellipticCurve,39L
+
+#define OBJ_wap_wsg_idm_ecid OBJ_wap_wsg,4L
+
+#define SN_wap_wsg_idm_ecid_wtls1 "wap-wsg-idm-ecid-wtls1"
+#define NID_wap_wsg_idm_ecid_wtls1 735
+#define OBJ_wap_wsg_idm_ecid_wtls1 OBJ_wap_wsg_idm_ecid,1L
+
+#define SN_wap_wsg_idm_ecid_wtls3 "wap-wsg-idm-ecid-wtls3"
+#define NID_wap_wsg_idm_ecid_wtls3 736
+#define OBJ_wap_wsg_idm_ecid_wtls3 OBJ_wap_wsg_idm_ecid,3L
+
+#define SN_wap_wsg_idm_ecid_wtls4 "wap-wsg-idm-ecid-wtls4"
+#define NID_wap_wsg_idm_ecid_wtls4 737
+#define OBJ_wap_wsg_idm_ecid_wtls4 OBJ_wap_wsg_idm_ecid,4L
+
+#define SN_wap_wsg_idm_ecid_wtls5 "wap-wsg-idm-ecid-wtls5"
+#define NID_wap_wsg_idm_ecid_wtls5 738
+#define OBJ_wap_wsg_idm_ecid_wtls5 OBJ_wap_wsg_idm_ecid,5L
+
+#define SN_wap_wsg_idm_ecid_wtls6 "wap-wsg-idm-ecid-wtls6"
+#define NID_wap_wsg_idm_ecid_wtls6 739
+#define OBJ_wap_wsg_idm_ecid_wtls6 OBJ_wap_wsg_idm_ecid,6L
+
+#define SN_wap_wsg_idm_ecid_wtls7 "wap-wsg-idm-ecid-wtls7"
+#define NID_wap_wsg_idm_ecid_wtls7 740
+#define OBJ_wap_wsg_idm_ecid_wtls7 OBJ_wap_wsg_idm_ecid,7L
+
+#define SN_wap_wsg_idm_ecid_wtls8 "wap-wsg-idm-ecid-wtls8"
+#define NID_wap_wsg_idm_ecid_wtls8 741
+#define OBJ_wap_wsg_idm_ecid_wtls8 OBJ_wap_wsg_idm_ecid,8L
+
+#define SN_wap_wsg_idm_ecid_wtls9 "wap-wsg-idm-ecid-wtls9"
+#define NID_wap_wsg_idm_ecid_wtls9 742
+#define OBJ_wap_wsg_idm_ecid_wtls9 OBJ_wap_wsg_idm_ecid,9L
+
+#define SN_wap_wsg_idm_ecid_wtls10 "wap-wsg-idm-ecid-wtls10"
+#define NID_wap_wsg_idm_ecid_wtls10 743
+#define OBJ_wap_wsg_idm_ecid_wtls10 OBJ_wap_wsg_idm_ecid,10L
+
+#define SN_wap_wsg_idm_ecid_wtls11 "wap-wsg-idm-ecid-wtls11"
+#define NID_wap_wsg_idm_ecid_wtls11 744
+#define OBJ_wap_wsg_idm_ecid_wtls11 OBJ_wap_wsg_idm_ecid,11L
+
+#define SN_wap_wsg_idm_ecid_wtls12 "wap-wsg-idm-ecid-wtls12"
+#define NID_wap_wsg_idm_ecid_wtls12 745
+#define OBJ_wap_wsg_idm_ecid_wtls12 OBJ_wap_wsg_idm_ecid,12L
+
+#define SN_cast5_cbc "CAST5-CBC"
+#define LN_cast5_cbc "cast5-cbc"
+#define NID_cast5_cbc 108
+#define OBJ_cast5_cbc OBJ_ISO_US,113533L,7L,66L,10L
+
+#define SN_cast5_ecb "CAST5-ECB"
+#define LN_cast5_ecb "cast5-ecb"
+#define NID_cast5_ecb 109
+
+#define SN_cast5_cfb64 "CAST5-CFB"
+#define LN_cast5_cfb64 "cast5-cfb"
+#define NID_cast5_cfb64 110
+
+#define SN_cast5_ofb64 "CAST5-OFB"
+#define LN_cast5_ofb64 "cast5-ofb"
+#define NID_cast5_ofb64 111
+
+#define LN_pbeWithMD5AndCast5_CBC "pbeWithMD5AndCast5CBC"
+#define NID_pbeWithMD5AndCast5_CBC 112
+#define OBJ_pbeWithMD5AndCast5_CBC OBJ_ISO_US,113533L,7L,66L,12L
+
+#define SN_id_PasswordBasedMAC "id-PasswordBasedMAC"
+#define LN_id_PasswordBasedMAC "password based MAC"
+#define NID_id_PasswordBasedMAC 782
+#define OBJ_id_PasswordBasedMAC OBJ_ISO_US,113533L,7L,66L,13L
+
+#define SN_id_DHBasedMac "id-DHBasedMac"
+#define LN_id_DHBasedMac "Diffie-Hellman based MAC"
+#define NID_id_DHBasedMac 783
+#define OBJ_id_DHBasedMac OBJ_ISO_US,113533L,7L,66L,30L
+
+#define SN_rsadsi "rsadsi"
+#define LN_rsadsi "RSA Data Security, Inc."
+#define NID_rsadsi 1
+#define OBJ_rsadsi OBJ_ISO_US,113549L
+
+#define SN_pkcs "pkcs"
+#define LN_pkcs "RSA Data Security, Inc. PKCS"
+#define NID_pkcs 2
+#define OBJ_pkcs OBJ_rsadsi,1L
+
+#define SN_pkcs1 "pkcs1"
+#define NID_pkcs1 186
+#define OBJ_pkcs1 OBJ_pkcs,1L
+
+#define LN_rsaEncryption "rsaEncryption"
+#define NID_rsaEncryption 6
+#define OBJ_rsaEncryption OBJ_pkcs1,1L
+
+#define SN_md2WithRSAEncryption "RSA-MD2"
+#define LN_md2WithRSAEncryption "md2WithRSAEncryption"
+#define NID_md2WithRSAEncryption 7
+#define OBJ_md2WithRSAEncryption OBJ_pkcs1,2L
+
+#define SN_md4WithRSAEncryption "RSA-MD4"
+#define LN_md4WithRSAEncryption "md4WithRSAEncryption"
+#define NID_md4WithRSAEncryption 396
+#define OBJ_md4WithRSAEncryption OBJ_pkcs1,3L
+
+#define SN_md5WithRSAEncryption "RSA-MD5"
+#define LN_md5WithRSAEncryption "md5WithRSAEncryption"
+#define NID_md5WithRSAEncryption 8
+#define OBJ_md5WithRSAEncryption OBJ_pkcs1,4L
+
+#define SN_sha1WithRSAEncryption "RSA-SHA1"
+#define LN_sha1WithRSAEncryption "sha1WithRSAEncryption"
+#define NID_sha1WithRSAEncryption 65
+#define OBJ_sha1WithRSAEncryption OBJ_pkcs1,5L
+
+#define SN_rsaesOaep "RSAES-OAEP"
+#define LN_rsaesOaep "rsaesOaep"
+#define NID_rsaesOaep 919
+#define OBJ_rsaesOaep OBJ_pkcs1,7L
+
+#define SN_mgf1 "MGF1"
+#define LN_mgf1 "mgf1"
+#define NID_mgf1 911
+#define OBJ_mgf1 OBJ_pkcs1,8L
+
+#define SN_pSpecified "PSPECIFIED"
+#define LN_pSpecified "pSpecified"
+#define NID_pSpecified 935
+#define OBJ_pSpecified OBJ_pkcs1,9L
+
+#define SN_rsassaPss "RSASSA-PSS"
+#define LN_rsassaPss "rsassaPss"
+#define NID_rsassaPss 912
+#define OBJ_rsassaPss OBJ_pkcs1,10L
+
+#define SN_sha256WithRSAEncryption "RSA-SHA256"
+#define LN_sha256WithRSAEncryption "sha256WithRSAEncryption"
+#define NID_sha256WithRSAEncryption 668
+#define OBJ_sha256WithRSAEncryption OBJ_pkcs1,11L
+
+#define SN_sha384WithRSAEncryption "RSA-SHA384"
+#define LN_sha384WithRSAEncryption "sha384WithRSAEncryption"
+#define NID_sha384WithRSAEncryption 669
+#define OBJ_sha384WithRSAEncryption OBJ_pkcs1,12L
+
+#define SN_sha512WithRSAEncryption "RSA-SHA512"
+#define LN_sha512WithRSAEncryption "sha512WithRSAEncryption"
+#define NID_sha512WithRSAEncryption 670
+#define OBJ_sha512WithRSAEncryption OBJ_pkcs1,13L
+
+#define SN_sha224WithRSAEncryption "RSA-SHA224"
+#define LN_sha224WithRSAEncryption "sha224WithRSAEncryption"
+#define NID_sha224WithRSAEncryption 671
+#define OBJ_sha224WithRSAEncryption OBJ_pkcs1,14L
+
+#define SN_sha512_224WithRSAEncryption "RSA-SHA512/224"
+#define LN_sha512_224WithRSAEncryption "sha512-224WithRSAEncryption"
+#define NID_sha512_224WithRSAEncryption 1145
+#define OBJ_sha512_224WithRSAEncryption OBJ_pkcs1,15L
+
+#define SN_sha512_256WithRSAEncryption "RSA-SHA512/256"
+#define LN_sha512_256WithRSAEncryption "sha512-256WithRSAEncryption"
+#define NID_sha512_256WithRSAEncryption 1146
+#define OBJ_sha512_256WithRSAEncryption OBJ_pkcs1,16L
+
+#define SN_pkcs3 "pkcs3"
+#define NID_pkcs3 27
+#define OBJ_pkcs3 OBJ_pkcs,3L
+
+#define LN_dhKeyAgreement "dhKeyAgreement"
+#define NID_dhKeyAgreement 28
+#define OBJ_dhKeyAgreement OBJ_pkcs3,1L
+
+#define SN_pkcs5 "pkcs5"
+#define NID_pkcs5 187
+#define OBJ_pkcs5 OBJ_pkcs,5L
+
+#define SN_pbeWithMD2AndDES_CBC "PBE-MD2-DES"
+#define LN_pbeWithMD2AndDES_CBC "pbeWithMD2AndDES-CBC"
+#define NID_pbeWithMD2AndDES_CBC 9
+#define OBJ_pbeWithMD2AndDES_CBC OBJ_pkcs5,1L
+
+#define SN_pbeWithMD5AndDES_CBC "PBE-MD5-DES"
+#define LN_pbeWithMD5AndDES_CBC "pbeWithMD5AndDES-CBC"
+#define NID_pbeWithMD5AndDES_CBC 10
+#define OBJ_pbeWithMD5AndDES_CBC OBJ_pkcs5,3L
+
+#define SN_pbeWithMD2AndRC2_CBC "PBE-MD2-RC2-64"
+#define LN_pbeWithMD2AndRC2_CBC "pbeWithMD2AndRC2-CBC"
+#define NID_pbeWithMD2AndRC2_CBC 168
+#define OBJ_pbeWithMD2AndRC2_CBC OBJ_pkcs5,4L
+
+#define SN_pbeWithMD5AndRC2_CBC "PBE-MD5-RC2-64"
+#define LN_pbeWithMD5AndRC2_CBC "pbeWithMD5AndRC2-CBC"
+#define NID_pbeWithMD5AndRC2_CBC 169
+#define OBJ_pbeWithMD5AndRC2_CBC OBJ_pkcs5,6L
+
+#define SN_pbeWithSHA1AndDES_CBC "PBE-SHA1-DES"
+#define LN_pbeWithSHA1AndDES_CBC "pbeWithSHA1AndDES-CBC"
+#define NID_pbeWithSHA1AndDES_CBC 170
+#define OBJ_pbeWithSHA1AndDES_CBC OBJ_pkcs5,10L
+
+#define SN_pbeWithSHA1AndRC2_CBC "PBE-SHA1-RC2-64"
+#define LN_pbeWithSHA1AndRC2_CBC "pbeWithSHA1AndRC2-CBC"
+#define NID_pbeWithSHA1AndRC2_CBC 68
+#define OBJ_pbeWithSHA1AndRC2_CBC OBJ_pkcs5,11L
+
+#define LN_id_pbkdf2 "PBKDF2"
+#define NID_id_pbkdf2 69
+#define OBJ_id_pbkdf2 OBJ_pkcs5,12L
+
+#define LN_pbes2 "PBES2"
+#define NID_pbes2 161
+#define OBJ_pbes2 OBJ_pkcs5,13L
+
+#define LN_pbmac1 "PBMAC1"
+#define NID_pbmac1 162
+#define OBJ_pbmac1 OBJ_pkcs5,14L
+
+#define SN_pkcs7 "pkcs7"
+#define NID_pkcs7 20
+#define OBJ_pkcs7 OBJ_pkcs,7L
+
+#define LN_pkcs7_data "pkcs7-data"
+#define NID_pkcs7_data 21
+#define OBJ_pkcs7_data OBJ_pkcs7,1L
+
+#define LN_pkcs7_signed "pkcs7-signedData"
+#define NID_pkcs7_signed 22
+#define OBJ_pkcs7_signed OBJ_pkcs7,2L
+
+#define LN_pkcs7_enveloped "pkcs7-envelopedData"
+#define NID_pkcs7_enveloped 23
+#define OBJ_pkcs7_enveloped OBJ_pkcs7,3L
+
+#define LN_pkcs7_signedAndEnveloped "pkcs7-signedAndEnvelopedData"
+#define NID_pkcs7_signedAndEnveloped 24
+#define OBJ_pkcs7_signedAndEnveloped OBJ_pkcs7,4L
+
+#define LN_pkcs7_digest "pkcs7-digestData"
+#define NID_pkcs7_digest 25
+#define OBJ_pkcs7_digest OBJ_pkcs7,5L
+
+#define LN_pkcs7_encrypted "pkcs7-encryptedData"
+#define NID_pkcs7_encrypted 26
+#define OBJ_pkcs7_encrypted OBJ_pkcs7,6L
+
+#define SN_pkcs9 "pkcs9"
+#define NID_pkcs9 47
+#define OBJ_pkcs9 OBJ_pkcs,9L
+
+#define LN_pkcs9_emailAddress "emailAddress"
+#define NID_pkcs9_emailAddress 48
+#define OBJ_pkcs9_emailAddress OBJ_pkcs9,1L
+
+#define LN_pkcs9_unstructuredName "unstructuredName"
+#define NID_pkcs9_unstructuredName 49
+#define OBJ_pkcs9_unstructuredName OBJ_pkcs9,2L
+
+#define LN_pkcs9_contentType "contentType"
+#define NID_pkcs9_contentType 50
+#define OBJ_pkcs9_contentType OBJ_pkcs9,3L
+
+#define LN_pkcs9_messageDigest "messageDigest"
+#define NID_pkcs9_messageDigest 51
+#define OBJ_pkcs9_messageDigest OBJ_pkcs9,4L
+
+#define LN_pkcs9_signingTime "signingTime"
+#define NID_pkcs9_signingTime 52
+#define OBJ_pkcs9_signingTime OBJ_pkcs9,5L
+
+#define LN_pkcs9_countersignature "countersignature"
+#define NID_pkcs9_countersignature 53
+#define OBJ_pkcs9_countersignature OBJ_pkcs9,6L
+
+#define LN_pkcs9_challengePassword "challengePassword"
+#define NID_pkcs9_challengePassword 54
+#define OBJ_pkcs9_challengePassword OBJ_pkcs9,7L
+
+#define LN_pkcs9_unstructuredAddress "unstructuredAddress"
+#define NID_pkcs9_unstructuredAddress 55
+#define OBJ_pkcs9_unstructuredAddress OBJ_pkcs9,8L
+
+#define LN_pkcs9_extCertAttributes "extendedCertificateAttributes"
+#define NID_pkcs9_extCertAttributes 56
+#define OBJ_pkcs9_extCertAttributes OBJ_pkcs9,9L
+
+#define SN_ext_req "extReq"
+#define LN_ext_req "Extension Request"
+#define NID_ext_req 172
+#define OBJ_ext_req OBJ_pkcs9,14L
+
+#define SN_SMIMECapabilities "SMIME-CAPS"
+#define LN_SMIMECapabilities "S/MIME Capabilities"
+#define NID_SMIMECapabilities 167
+#define OBJ_SMIMECapabilities OBJ_pkcs9,15L
+
+#define SN_SMIME "SMIME"
+#define LN_SMIME "S/MIME"
+#define NID_SMIME 188
+#define OBJ_SMIME OBJ_pkcs9,16L
+
+#define SN_id_smime_mod "id-smime-mod"
+#define NID_id_smime_mod 189
+#define OBJ_id_smime_mod OBJ_SMIME,0L
+
+#define SN_id_smime_ct "id-smime-ct"
+#define NID_id_smime_ct 190
+#define OBJ_id_smime_ct OBJ_SMIME,1L
+
+#define SN_id_smime_aa "id-smime-aa"
+#define NID_id_smime_aa 191
+#define OBJ_id_smime_aa OBJ_SMIME,2L
+
+#define SN_id_smime_alg "id-smime-alg"
+#define NID_id_smime_alg 192
+#define OBJ_id_smime_alg OBJ_SMIME,3L
+
+#define SN_id_smime_cd "id-smime-cd"
+#define NID_id_smime_cd 193
+#define OBJ_id_smime_cd OBJ_SMIME,4L
+
+#define SN_id_smime_spq "id-smime-spq"
+#define NID_id_smime_spq 194
+#define OBJ_id_smime_spq OBJ_SMIME,5L
+
+#define SN_id_smime_cti "id-smime-cti"
+#define NID_id_smime_cti 195
+#define OBJ_id_smime_cti OBJ_SMIME,6L
+
+#define SN_id_smime_mod_cms "id-smime-mod-cms"
+#define NID_id_smime_mod_cms 196
+#define OBJ_id_smime_mod_cms OBJ_id_smime_mod,1L
+
+#define SN_id_smime_mod_ess "id-smime-mod-ess"
+#define NID_id_smime_mod_ess 197
+#define OBJ_id_smime_mod_ess OBJ_id_smime_mod,2L
+
+#define SN_id_smime_mod_oid "id-smime-mod-oid"
+#define NID_id_smime_mod_oid 198
+#define OBJ_id_smime_mod_oid OBJ_id_smime_mod,3L
+
+#define SN_id_smime_mod_msg_v3 "id-smime-mod-msg-v3"
+#define NID_id_smime_mod_msg_v3 199
+#define OBJ_id_smime_mod_msg_v3 OBJ_id_smime_mod,4L
+
+#define SN_id_smime_mod_ets_eSignature_88 "id-smime-mod-ets-eSignature-88"
+#define NID_id_smime_mod_ets_eSignature_88 200
+#define OBJ_id_smime_mod_ets_eSignature_88 OBJ_id_smime_mod,5L
+
+#define SN_id_smime_mod_ets_eSignature_97 "id-smime-mod-ets-eSignature-97"
+#define NID_id_smime_mod_ets_eSignature_97 201
+#define OBJ_id_smime_mod_ets_eSignature_97 OBJ_id_smime_mod,6L
+
+#define SN_id_smime_mod_ets_eSigPolicy_88 "id-smime-mod-ets-eSigPolicy-88"
+#define NID_id_smime_mod_ets_eSigPolicy_88 202
+#define OBJ_id_smime_mod_ets_eSigPolicy_88 OBJ_id_smime_mod,7L
+
+#define SN_id_smime_mod_ets_eSigPolicy_97 "id-smime-mod-ets-eSigPolicy-97"
+#define NID_id_smime_mod_ets_eSigPolicy_97 203
+#define OBJ_id_smime_mod_ets_eSigPolicy_97 OBJ_id_smime_mod,8L
+
+#define SN_id_smime_ct_receipt "id-smime-ct-receipt"
+#define NID_id_smime_ct_receipt 204
+#define OBJ_id_smime_ct_receipt OBJ_id_smime_ct,1L
+
+#define SN_id_smime_ct_authData "id-smime-ct-authData"
+#define NID_id_smime_ct_authData 205
+#define OBJ_id_smime_ct_authData OBJ_id_smime_ct,2L
+
+#define SN_id_smime_ct_publishCert "id-smime-ct-publishCert"
+#define NID_id_smime_ct_publishCert 206
+#define OBJ_id_smime_ct_publishCert OBJ_id_smime_ct,3L
+
+#define SN_id_smime_ct_TSTInfo "id-smime-ct-TSTInfo"
+#define NID_id_smime_ct_TSTInfo 207
+#define OBJ_id_smime_ct_TSTInfo OBJ_id_smime_ct,4L
+
+#define SN_id_smime_ct_TDTInfo "id-smime-ct-TDTInfo"
+#define NID_id_smime_ct_TDTInfo 208
+#define OBJ_id_smime_ct_TDTInfo OBJ_id_smime_ct,5L
+
+#define SN_id_smime_ct_contentInfo "id-smime-ct-contentInfo"
+#define NID_id_smime_ct_contentInfo 209
+#define OBJ_id_smime_ct_contentInfo OBJ_id_smime_ct,6L
+
+#define SN_id_smime_ct_DVCSRequestData "id-smime-ct-DVCSRequestData"
+#define NID_id_smime_ct_DVCSRequestData 210
+#define OBJ_id_smime_ct_DVCSRequestData OBJ_id_smime_ct,7L
+
+#define SN_id_smime_ct_DVCSResponseData "id-smime-ct-DVCSResponseData"
+#define NID_id_smime_ct_DVCSResponseData 211
+#define OBJ_id_smime_ct_DVCSResponseData OBJ_id_smime_ct,8L
+
+#define SN_id_smime_ct_compressedData "id-smime-ct-compressedData"
+#define NID_id_smime_ct_compressedData 786
+#define OBJ_id_smime_ct_compressedData OBJ_id_smime_ct,9L
+
+#define SN_id_smime_ct_contentCollection "id-smime-ct-contentCollection"
+#define NID_id_smime_ct_contentCollection 1058
+#define OBJ_id_smime_ct_contentCollection OBJ_id_smime_ct,19L
+
+#define SN_id_smime_ct_authEnvelopedData "id-smime-ct-authEnvelopedData"
+#define NID_id_smime_ct_authEnvelopedData 1059
+#define OBJ_id_smime_ct_authEnvelopedData OBJ_id_smime_ct,23L
+
+#define SN_id_ct_routeOriginAuthz "id-ct-routeOriginAuthz"
+#define NID_id_ct_routeOriginAuthz 1234
+#define OBJ_id_ct_routeOriginAuthz OBJ_id_smime_ct,24L
+
+#define SN_id_ct_rpkiManifest "id-ct-rpkiManifest"
+#define NID_id_ct_rpkiManifest 1235
+#define OBJ_id_ct_rpkiManifest OBJ_id_smime_ct,26L
+
+#define SN_id_ct_asciiTextWithCRLF "id-ct-asciiTextWithCRLF"
+#define NID_id_ct_asciiTextWithCRLF 787
+#define OBJ_id_ct_asciiTextWithCRLF OBJ_id_smime_ct,27L
+
+#define SN_id_ct_xml "id-ct-xml"
+#define NID_id_ct_xml 1060
+#define OBJ_id_ct_xml OBJ_id_smime_ct,28L
+
+#define SN_id_ct_rpkiGhostbusters "id-ct-rpkiGhostbusters"
+#define NID_id_ct_rpkiGhostbusters 1236
+#define OBJ_id_ct_rpkiGhostbusters OBJ_id_smime_ct,35L
+
+#define SN_id_ct_resourceTaggedAttest "id-ct-resourceTaggedAttest"
+#define NID_id_ct_resourceTaggedAttest 1237
+#define OBJ_id_ct_resourceTaggedAttest OBJ_id_smime_ct,36L
+
+#define SN_id_ct_geofeedCSVwithCRLF "id-ct-geofeedCSVwithCRLF"
+#define NID_id_ct_geofeedCSVwithCRLF 1246
+#define OBJ_id_ct_geofeedCSVwithCRLF OBJ_id_smime_ct,47L
+
+#define SN_id_ct_signedChecklist "id-ct-signedChecklist"
+#define NID_id_ct_signedChecklist 1247
+#define OBJ_id_ct_signedChecklist OBJ_id_smime_ct,48L
+
+#define SN_id_smime_aa_receiptRequest "id-smime-aa-receiptRequest"
+#define NID_id_smime_aa_receiptRequest 212
+#define OBJ_id_smime_aa_receiptRequest OBJ_id_smime_aa,1L
+
+#define SN_id_smime_aa_securityLabel "id-smime-aa-securityLabel"
+#define NID_id_smime_aa_securityLabel 213
+#define OBJ_id_smime_aa_securityLabel OBJ_id_smime_aa,2L
+
+#define SN_id_smime_aa_mlExpandHistory "id-smime-aa-mlExpandHistory"
+#define NID_id_smime_aa_mlExpandHistory 214
+#define OBJ_id_smime_aa_mlExpandHistory OBJ_id_smime_aa,3L
+
+#define SN_id_smime_aa_contentHint "id-smime-aa-contentHint"
+#define NID_id_smime_aa_contentHint 215
+#define OBJ_id_smime_aa_contentHint OBJ_id_smime_aa,4L
+
+#define SN_id_smime_aa_msgSigDigest "id-smime-aa-msgSigDigest"
+#define NID_id_smime_aa_msgSigDigest 216
+#define OBJ_id_smime_aa_msgSigDigest OBJ_id_smime_aa,5L
+
+#define SN_id_smime_aa_encapContentType "id-smime-aa-encapContentType"
+#define NID_id_smime_aa_encapContentType 217
+#define OBJ_id_smime_aa_encapContentType OBJ_id_smime_aa,6L
+
+#define SN_id_smime_aa_contentIdentifier "id-smime-aa-contentIdentifier"
+#define NID_id_smime_aa_contentIdentifier 218
+#define OBJ_id_smime_aa_contentIdentifier OBJ_id_smime_aa,7L
+
+#define SN_id_smime_aa_macValue "id-smime-aa-macValue"
+#define NID_id_smime_aa_macValue 219
+#define OBJ_id_smime_aa_macValue OBJ_id_smime_aa,8L
+
+#define SN_id_smime_aa_equivalentLabels "id-smime-aa-equivalentLabels"
+#define NID_id_smime_aa_equivalentLabels 220
+#define OBJ_id_smime_aa_equivalentLabels OBJ_id_smime_aa,9L
+
+#define SN_id_smime_aa_contentReference "id-smime-aa-contentReference"
+#define NID_id_smime_aa_contentReference 221
+#define OBJ_id_smime_aa_contentReference OBJ_id_smime_aa,10L
+
+#define SN_id_smime_aa_encrypKeyPref "id-smime-aa-encrypKeyPref"
+#define NID_id_smime_aa_encrypKeyPref 222
+#define OBJ_id_smime_aa_encrypKeyPref OBJ_id_smime_aa,11L
+
+#define SN_id_smime_aa_signingCertificate "id-smime-aa-signingCertificate"
+#define NID_id_smime_aa_signingCertificate 223
+#define OBJ_id_smime_aa_signingCertificate OBJ_id_smime_aa,12L
+
+#define SN_id_smime_aa_smimeEncryptCerts "id-smime-aa-smimeEncryptCerts"
+#define NID_id_smime_aa_smimeEncryptCerts 224
+#define OBJ_id_smime_aa_smimeEncryptCerts OBJ_id_smime_aa,13L
+
+#define SN_id_smime_aa_timeStampToken "id-smime-aa-timeStampToken"
+#define NID_id_smime_aa_timeStampToken 225
+#define OBJ_id_smime_aa_timeStampToken OBJ_id_smime_aa,14L
+
+#define SN_id_smime_aa_ets_sigPolicyId "id-smime-aa-ets-sigPolicyId"
+#define NID_id_smime_aa_ets_sigPolicyId 226
+#define OBJ_id_smime_aa_ets_sigPolicyId OBJ_id_smime_aa,15L
+
+#define SN_id_smime_aa_ets_commitmentType "id-smime-aa-ets-commitmentType"
+#define NID_id_smime_aa_ets_commitmentType 227
+#define OBJ_id_smime_aa_ets_commitmentType OBJ_id_smime_aa,16L
+
+#define SN_id_smime_aa_ets_signerLocation "id-smime-aa-ets-signerLocation"
+#define NID_id_smime_aa_ets_signerLocation 228
+#define OBJ_id_smime_aa_ets_signerLocation OBJ_id_smime_aa,17L
+
+#define SN_id_smime_aa_ets_signerAttr "id-smime-aa-ets-signerAttr"
+#define NID_id_smime_aa_ets_signerAttr 229
+#define OBJ_id_smime_aa_ets_signerAttr OBJ_id_smime_aa,18L
+
+#define SN_id_smime_aa_ets_otherSigCert "id-smime-aa-ets-otherSigCert"
+#define NID_id_smime_aa_ets_otherSigCert 230
+#define OBJ_id_smime_aa_ets_otherSigCert OBJ_id_smime_aa,19L
+
+#define SN_id_smime_aa_ets_contentTimestamp "id-smime-aa-ets-contentTimestamp"
+#define NID_id_smime_aa_ets_contentTimestamp 231
+#define OBJ_id_smime_aa_ets_contentTimestamp OBJ_id_smime_aa,20L
+
+#define SN_id_smime_aa_ets_CertificateRefs "id-smime-aa-ets-CertificateRefs"
+#define NID_id_smime_aa_ets_CertificateRefs 232
+#define OBJ_id_smime_aa_ets_CertificateRefs OBJ_id_smime_aa,21L
+
+#define SN_id_smime_aa_ets_RevocationRefs "id-smime-aa-ets-RevocationRefs"
+#define NID_id_smime_aa_ets_RevocationRefs 233
+#define OBJ_id_smime_aa_ets_RevocationRefs OBJ_id_smime_aa,22L
+
+#define SN_id_smime_aa_ets_certValues "id-smime-aa-ets-certValues"
+#define NID_id_smime_aa_ets_certValues 234
+#define OBJ_id_smime_aa_ets_certValues OBJ_id_smime_aa,23L
+
+#define SN_id_smime_aa_ets_revocationValues "id-smime-aa-ets-revocationValues"
+#define NID_id_smime_aa_ets_revocationValues 235
+#define OBJ_id_smime_aa_ets_revocationValues OBJ_id_smime_aa,24L
+
+#define SN_id_smime_aa_ets_escTimeStamp "id-smime-aa-ets-escTimeStamp"
+#define NID_id_smime_aa_ets_escTimeStamp 236
+#define OBJ_id_smime_aa_ets_escTimeStamp OBJ_id_smime_aa,25L
+
+#define SN_id_smime_aa_ets_certCRLTimestamp "id-smime-aa-ets-certCRLTimestamp"
+#define NID_id_smime_aa_ets_certCRLTimestamp 237
+#define OBJ_id_smime_aa_ets_certCRLTimestamp OBJ_id_smime_aa,26L
+
+#define SN_id_smime_aa_ets_archiveTimeStamp "id-smime-aa-ets-archiveTimeStamp"
+#define NID_id_smime_aa_ets_archiveTimeStamp 238
+#define OBJ_id_smime_aa_ets_archiveTimeStamp OBJ_id_smime_aa,27L
+
+#define SN_id_smime_aa_signatureType "id-smime-aa-signatureType"
+#define NID_id_smime_aa_signatureType 239
+#define OBJ_id_smime_aa_signatureType OBJ_id_smime_aa,28L
+
+#define SN_id_smime_aa_dvcs_dvc "id-smime-aa-dvcs-dvc"
+#define NID_id_smime_aa_dvcs_dvc 240
+#define OBJ_id_smime_aa_dvcs_dvc OBJ_id_smime_aa,29L
+
+#define SN_id_smime_aa_signingCertificateV2 "id-smime-aa-signingCertificateV2"
+#define NID_id_smime_aa_signingCertificateV2 1086
+#define OBJ_id_smime_aa_signingCertificateV2 OBJ_id_smime_aa,47L
+
+#define SN_id_smime_alg_ESDHwith3DES "id-smime-alg-ESDHwith3DES"
+#define NID_id_smime_alg_ESDHwith3DES 241
+#define OBJ_id_smime_alg_ESDHwith3DES OBJ_id_smime_alg,1L
+
+#define SN_id_smime_alg_ESDHwithRC2 "id-smime-alg-ESDHwithRC2"
+#define NID_id_smime_alg_ESDHwithRC2 242
+#define OBJ_id_smime_alg_ESDHwithRC2 OBJ_id_smime_alg,2L
+
+#define SN_id_smime_alg_3DESwrap "id-smime-alg-3DESwrap"
+#define NID_id_smime_alg_3DESwrap 243
+#define OBJ_id_smime_alg_3DESwrap OBJ_id_smime_alg,3L
+
+#define SN_id_smime_alg_RC2wrap "id-smime-alg-RC2wrap"
+#define NID_id_smime_alg_RC2wrap 244
+#define OBJ_id_smime_alg_RC2wrap OBJ_id_smime_alg,4L
+
+#define SN_id_smime_alg_ESDH "id-smime-alg-ESDH"
+#define NID_id_smime_alg_ESDH 245
+#define OBJ_id_smime_alg_ESDH OBJ_id_smime_alg,5L
+
+#define SN_id_smime_alg_CMS3DESwrap "id-smime-alg-CMS3DESwrap"
+#define NID_id_smime_alg_CMS3DESwrap 246
+#define OBJ_id_smime_alg_CMS3DESwrap OBJ_id_smime_alg,6L
+
+#define SN_id_smime_alg_CMSRC2wrap "id-smime-alg-CMSRC2wrap"
+#define NID_id_smime_alg_CMSRC2wrap 247
+#define OBJ_id_smime_alg_CMSRC2wrap OBJ_id_smime_alg,7L
+
+#define SN_id_alg_PWRI_KEK "id-alg-PWRI-KEK"
+#define NID_id_alg_PWRI_KEK 893
+#define OBJ_id_alg_PWRI_KEK OBJ_id_smime_alg,9L
+
+#define SN_id_smime_cd_ldap "id-smime-cd-ldap"
+#define NID_id_smime_cd_ldap 248
+#define OBJ_id_smime_cd_ldap OBJ_id_smime_cd,1L
+
+#define SN_id_smime_spq_ets_sqt_uri "id-smime-spq-ets-sqt-uri"
+#define NID_id_smime_spq_ets_sqt_uri 249
+#define OBJ_id_smime_spq_ets_sqt_uri OBJ_id_smime_spq,1L
+
+#define SN_id_smime_spq_ets_sqt_unotice "id-smime-spq-ets-sqt-unotice"
+#define NID_id_smime_spq_ets_sqt_unotice 250
+#define OBJ_id_smime_spq_ets_sqt_unotice OBJ_id_smime_spq,2L
+
+#define SN_id_smime_cti_ets_proofOfOrigin "id-smime-cti-ets-proofOfOrigin"
+#define NID_id_smime_cti_ets_proofOfOrigin 251
+#define OBJ_id_smime_cti_ets_proofOfOrigin OBJ_id_smime_cti,1L
+
+#define SN_id_smime_cti_ets_proofOfReceipt "id-smime-cti-ets-proofOfReceipt"
+#define NID_id_smime_cti_ets_proofOfReceipt 252
+#define OBJ_id_smime_cti_ets_proofOfReceipt OBJ_id_smime_cti,2L
+
+#define SN_id_smime_cti_ets_proofOfDelivery "id-smime-cti-ets-proofOfDelivery"
+#define NID_id_smime_cti_ets_proofOfDelivery 253
+#define OBJ_id_smime_cti_ets_proofOfDelivery OBJ_id_smime_cti,3L
+
+#define SN_id_smime_cti_ets_proofOfSender "id-smime-cti-ets-proofOfSender"
+#define NID_id_smime_cti_ets_proofOfSender 254
+#define OBJ_id_smime_cti_ets_proofOfSender OBJ_id_smime_cti,4L
+
+#define SN_id_smime_cti_ets_proofOfApproval "id-smime-cti-ets-proofOfApproval"
+#define NID_id_smime_cti_ets_proofOfApproval 255
+#define OBJ_id_smime_cti_ets_proofOfApproval OBJ_id_smime_cti,5L
+
+#define SN_id_smime_cti_ets_proofOfCreation "id-smime-cti-ets-proofOfCreation"
+#define NID_id_smime_cti_ets_proofOfCreation 256
+#define OBJ_id_smime_cti_ets_proofOfCreation OBJ_id_smime_cti,6L
+
+#define LN_friendlyName "friendlyName"
+#define NID_friendlyName 156
+#define OBJ_friendlyName OBJ_pkcs9,20L
+
+#define LN_localKeyID "localKeyID"
+#define NID_localKeyID 157
+#define OBJ_localKeyID OBJ_pkcs9,21L
+
+#define SN_ms_csp_name "CSPName"
+#define LN_ms_csp_name "Microsoft CSP Name"
+#define NID_ms_csp_name 417
+#define OBJ_ms_csp_name 1L,3L,6L,1L,4L,1L,311L,17L,1L
+
+#define SN_LocalKeySet "LocalKeySet"
+#define LN_LocalKeySet "Microsoft Local Key set"
+#define NID_LocalKeySet 856
+#define OBJ_LocalKeySet 1L,3L,6L,1L,4L,1L,311L,17L,2L
+
+#define OBJ_certTypes OBJ_pkcs9,22L
+
+#define LN_x509Certificate "x509Certificate"
+#define NID_x509Certificate 158
+#define OBJ_x509Certificate OBJ_certTypes,1L
+
+#define LN_sdsiCertificate "sdsiCertificate"
+#define NID_sdsiCertificate 159
+#define OBJ_sdsiCertificate OBJ_certTypes,2L
+
+#define OBJ_crlTypes OBJ_pkcs9,23L
+
+#define LN_x509Crl "x509Crl"
+#define NID_x509Crl 160
+#define OBJ_x509Crl OBJ_crlTypes,1L
+
+#define OBJ_pkcs12 OBJ_pkcs,12L
+
+#define OBJ_pkcs12_pbeids OBJ_pkcs12,1L
+
+#define SN_pbe_WithSHA1And128BitRC4 "PBE-SHA1-RC4-128"
+#define LN_pbe_WithSHA1And128BitRC4 "pbeWithSHA1And128BitRC4"
+#define NID_pbe_WithSHA1And128BitRC4 144
+#define OBJ_pbe_WithSHA1And128BitRC4 OBJ_pkcs12_pbeids,1L
+
+#define SN_pbe_WithSHA1And40BitRC4 "PBE-SHA1-RC4-40"
+#define LN_pbe_WithSHA1And40BitRC4 "pbeWithSHA1And40BitRC4"
+#define NID_pbe_WithSHA1And40BitRC4 145
+#define OBJ_pbe_WithSHA1And40BitRC4 OBJ_pkcs12_pbeids,2L
+
+#define SN_pbe_WithSHA1And3_Key_TripleDES_CBC "PBE-SHA1-3DES"
+#define LN_pbe_WithSHA1And3_Key_TripleDES_CBC "pbeWithSHA1And3-KeyTripleDES-CBC"
+#define NID_pbe_WithSHA1And3_Key_TripleDES_CBC 146
+#define OBJ_pbe_WithSHA1And3_Key_TripleDES_CBC OBJ_pkcs12_pbeids,3L
+
+#define SN_pbe_WithSHA1And2_Key_TripleDES_CBC "PBE-SHA1-2DES"
+#define LN_pbe_WithSHA1And2_Key_TripleDES_CBC "pbeWithSHA1And2-KeyTripleDES-CBC"
+#define NID_pbe_WithSHA1And2_Key_TripleDES_CBC 147
+#define OBJ_pbe_WithSHA1And2_Key_TripleDES_CBC OBJ_pkcs12_pbeids,4L
+
+#define SN_pbe_WithSHA1And128BitRC2_CBC "PBE-SHA1-RC2-128"
+#define LN_pbe_WithSHA1And128BitRC2_CBC "pbeWithSHA1And128BitRC2-CBC"
+#define NID_pbe_WithSHA1And128BitRC2_CBC 148
+#define OBJ_pbe_WithSHA1And128BitRC2_CBC OBJ_pkcs12_pbeids,5L
+
+#define SN_pbe_WithSHA1And40BitRC2_CBC "PBE-SHA1-RC2-40"
+#define LN_pbe_WithSHA1And40BitRC2_CBC "pbeWithSHA1And40BitRC2-CBC"
+#define NID_pbe_WithSHA1And40BitRC2_CBC 149
+#define OBJ_pbe_WithSHA1And40BitRC2_CBC OBJ_pkcs12_pbeids,6L
+
+#define OBJ_pkcs12_Version1 OBJ_pkcs12,10L
+
+#define OBJ_pkcs12_BagIds OBJ_pkcs12_Version1,1L
+
+#define LN_keyBag "keyBag"
+#define NID_keyBag 150
+#define OBJ_keyBag OBJ_pkcs12_BagIds,1L
+
+#define LN_pkcs8ShroudedKeyBag "pkcs8ShroudedKeyBag"
+#define NID_pkcs8ShroudedKeyBag 151
+#define OBJ_pkcs8ShroudedKeyBag OBJ_pkcs12_BagIds,2L
+
+#define LN_certBag "certBag"
+#define NID_certBag 152
+#define OBJ_certBag OBJ_pkcs12_BagIds,3L
+
+#define LN_crlBag "crlBag"
+#define NID_crlBag 153
+#define OBJ_crlBag OBJ_pkcs12_BagIds,4L
+
+#define LN_secretBag "secretBag"
+#define NID_secretBag 154
+#define OBJ_secretBag OBJ_pkcs12_BagIds,5L
+
+#define LN_safeContentsBag "safeContentsBag"
+#define NID_safeContentsBag 155
+#define OBJ_safeContentsBag OBJ_pkcs12_BagIds,6L
+
+#define SN_md2 "MD2"
+#define LN_md2 "md2"
+#define NID_md2 3
+#define OBJ_md2 OBJ_rsadsi,2L,2L
+
+#define SN_md4 "MD4"
+#define LN_md4 "md4"
+#define NID_md4 257
+#define OBJ_md4 OBJ_rsadsi,2L,4L
+
+#define SN_md5 "MD5"
+#define LN_md5 "md5"
+#define NID_md5 4
+#define OBJ_md5 OBJ_rsadsi,2L,5L
+
+#define SN_md5_sha1 "MD5-SHA1"
+#define LN_md5_sha1 "md5-sha1"
+#define NID_md5_sha1 114
+
+#define LN_hmacWithMD5 "hmacWithMD5"
+#define NID_hmacWithMD5 797
+#define OBJ_hmacWithMD5 OBJ_rsadsi,2L,6L
+
+#define LN_hmacWithSHA1 "hmacWithSHA1"
+#define NID_hmacWithSHA1 163
+#define OBJ_hmacWithSHA1 OBJ_rsadsi,2L,7L
+
+#define SN_sm2 "SM2"
+#define LN_sm2 "sm2"
+#define NID_sm2 1172
+#define OBJ_sm2 OBJ_sm_scheme,301L
+
+#define SN_sm3 "SM3"
+#define LN_sm3 "sm3"
+#define NID_sm3 1143
+#define OBJ_sm3 OBJ_sm_scheme,401L
+
+#define SN_sm3WithRSAEncryption "RSA-SM3"
+#define LN_sm3WithRSAEncryption "sm3WithRSAEncryption"
+#define NID_sm3WithRSAEncryption 1144
+#define OBJ_sm3WithRSAEncryption OBJ_sm_scheme,504L
+
+#define SN_SM2_with_SM3 "SM2-SM3"
+#define LN_SM2_with_SM3 "SM2-with-SM3"
+#define NID_SM2_with_SM3 1204
+#define OBJ_SM2_with_SM3 OBJ_sm_scheme,501L
+
+#define LN_hmacWithSHA224 "hmacWithSHA224"
+#define NID_hmacWithSHA224 798
+#define OBJ_hmacWithSHA224 OBJ_rsadsi,2L,8L
+
+#define LN_hmacWithSHA256 "hmacWithSHA256"
+#define NID_hmacWithSHA256 799
+#define OBJ_hmacWithSHA256 OBJ_rsadsi,2L,9L
+
+#define LN_hmacWithSHA384 "hmacWithSHA384"
+#define NID_hmacWithSHA384 800
+#define OBJ_hmacWithSHA384 OBJ_rsadsi,2L,10L
+
+#define LN_hmacWithSHA512 "hmacWithSHA512"
+#define NID_hmacWithSHA512 801
+#define OBJ_hmacWithSHA512 OBJ_rsadsi,2L,11L
+
+#define LN_hmacWithSHA512_224 "hmacWithSHA512-224"
+#define NID_hmacWithSHA512_224 1193
+#define OBJ_hmacWithSHA512_224 OBJ_rsadsi,2L,12L
+
+#define LN_hmacWithSHA512_256 "hmacWithSHA512-256"
+#define NID_hmacWithSHA512_256 1194
+#define OBJ_hmacWithSHA512_256 OBJ_rsadsi,2L,13L
+
+#define SN_rc2_cbc "RC2-CBC"
+#define LN_rc2_cbc "rc2-cbc"
+#define NID_rc2_cbc 37
+#define OBJ_rc2_cbc OBJ_rsadsi,3L,2L
+
+#define SN_rc2_ecb "RC2-ECB"
+#define LN_rc2_ecb "rc2-ecb"
+#define NID_rc2_ecb 38
+
+#define SN_rc2_cfb64 "RC2-CFB"
+#define LN_rc2_cfb64 "rc2-cfb"
+#define NID_rc2_cfb64 39
+
+#define SN_rc2_ofb64 "RC2-OFB"
+#define LN_rc2_ofb64 "rc2-ofb"
+#define NID_rc2_ofb64 40
+
+#define SN_rc2_40_cbc "RC2-40-CBC"
+#define LN_rc2_40_cbc "rc2-40-cbc"
+#define NID_rc2_40_cbc 98
+
+#define SN_rc2_64_cbc "RC2-64-CBC"
+#define LN_rc2_64_cbc "rc2-64-cbc"
+#define NID_rc2_64_cbc 166
+
+#define SN_rc4 "RC4"
+#define LN_rc4 "rc4"
+#define NID_rc4 5
+#define OBJ_rc4 OBJ_rsadsi,3L,4L
+
+#define SN_rc4_40 "RC4-40"
+#define LN_rc4_40 "rc4-40"
+#define NID_rc4_40 97
+
+#define SN_des_ede3_cbc "DES-EDE3-CBC"
+#define LN_des_ede3_cbc "des-ede3-cbc"
+#define NID_des_ede3_cbc 44
+#define OBJ_des_ede3_cbc OBJ_rsadsi,3L,7L
+
+#define SN_rc5_cbc "RC5-CBC"
+#define LN_rc5_cbc "rc5-cbc"
+#define NID_rc5_cbc 120
+#define OBJ_rc5_cbc OBJ_rsadsi,3L,8L
+
+#define SN_rc5_ecb "RC5-ECB"
+#define LN_rc5_ecb "rc5-ecb"
+#define NID_rc5_ecb 121
+
+#define SN_rc5_cfb64 "RC5-CFB"
+#define LN_rc5_cfb64 "rc5-cfb"
+#define NID_rc5_cfb64 122
+
+#define SN_rc5_ofb64 "RC5-OFB"
+#define LN_rc5_ofb64 "rc5-ofb"
+#define NID_rc5_ofb64 123
+
+#define SN_ms_ext_req "msExtReq"
+#define LN_ms_ext_req "Microsoft Extension Request"
+#define NID_ms_ext_req 171
+#define OBJ_ms_ext_req 1L,3L,6L,1L,4L,1L,311L,2L,1L,14L
+
+#define SN_ms_code_ind "msCodeInd"
+#define LN_ms_code_ind "Microsoft Individual Code Signing"
+#define NID_ms_code_ind 134
+#define OBJ_ms_code_ind 1L,3L,6L,1L,4L,1L,311L,2L,1L,21L
+
+#define SN_ms_code_com "msCodeCom"
+#define LN_ms_code_com "Microsoft Commercial Code Signing"
+#define NID_ms_code_com 135
+#define OBJ_ms_code_com 1L,3L,6L,1L,4L,1L,311L,2L,1L,22L
+
+#define SN_ms_ctl_sign "msCTLSign"
+#define LN_ms_ctl_sign "Microsoft Trust List Signing"
+#define NID_ms_ctl_sign 136
+#define OBJ_ms_ctl_sign 1L,3L,6L,1L,4L,1L,311L,10L,3L,1L
+
+#define SN_ms_sgc "msSGC"
+#define LN_ms_sgc "Microsoft Server Gated Crypto"
+#define NID_ms_sgc 137
+#define OBJ_ms_sgc 1L,3L,6L,1L,4L,1L,311L,10L,3L,3L
+
+#define SN_ms_efs "msEFS"
+#define LN_ms_efs "Microsoft Encrypted File System"
+#define NID_ms_efs 138
+#define OBJ_ms_efs 1L,3L,6L,1L,4L,1L,311L,10L,3L,4L
+
+#define SN_ms_smartcard_login "msSmartcardLogin"
+#define LN_ms_smartcard_login "Microsoft Smartcard Login"
+#define NID_ms_smartcard_login 648
+#define OBJ_ms_smartcard_login 1L,3L,6L,1L,4L,1L,311L,20L,2L,2L
+
+#define SN_ms_upn "msUPN"
+#define LN_ms_upn "Microsoft User Principal Name"
+#define NID_ms_upn 649
+#define OBJ_ms_upn 1L,3L,6L,1L,4L,1L,311L,20L,2L,3L
+
+#define SN_idea_cbc "IDEA-CBC"
+#define LN_idea_cbc "idea-cbc"
+#define NID_idea_cbc 34
+#define OBJ_idea_cbc 1L,3L,6L,1L,4L,1L,188L,7L,1L,1L,2L
+
+#define SN_idea_ecb "IDEA-ECB"
+#define LN_idea_ecb "idea-ecb"
+#define NID_idea_ecb 36
+
+#define SN_idea_cfb64 "IDEA-CFB"
+#define LN_idea_cfb64 "idea-cfb"
+#define NID_idea_cfb64 35
+
+#define SN_idea_ofb64 "IDEA-OFB"
+#define LN_idea_ofb64 "idea-ofb"
+#define NID_idea_ofb64 46
+
+#define SN_bf_cbc "BF-CBC"
+#define LN_bf_cbc "bf-cbc"
+#define NID_bf_cbc 91
+#define OBJ_bf_cbc 1L,3L,6L,1L,4L,1L,3029L,1L,2L
+
+#define SN_bf_ecb "BF-ECB"
+#define LN_bf_ecb "bf-ecb"
+#define NID_bf_ecb 92
+
+#define SN_bf_cfb64 "BF-CFB"
+#define LN_bf_cfb64 "bf-cfb"
+#define NID_bf_cfb64 93
+
+#define SN_bf_ofb64 "BF-OFB"
+#define LN_bf_ofb64 "bf-ofb"
+#define NID_bf_ofb64 94
+
+#define SN_id_pkix "PKIX"
+#define NID_id_pkix 127
+#define OBJ_id_pkix 1L,3L,6L,1L,5L,5L,7L
+
+#define SN_id_pkix_mod "id-pkix-mod"
+#define NID_id_pkix_mod 258
+#define OBJ_id_pkix_mod OBJ_id_pkix,0L
+
+#define SN_id_pe "id-pe"
+#define NID_id_pe 175
+#define OBJ_id_pe OBJ_id_pkix,1L
+
+#define SN_id_qt "id-qt"
+#define NID_id_qt 259
+#define OBJ_id_qt OBJ_id_pkix,2L
+
+#define SN_id_kp "id-kp"
+#define NID_id_kp 128
+#define OBJ_id_kp OBJ_id_pkix,3L
+
+#define SN_id_it "id-it"
+#define NID_id_it 260
+#define OBJ_id_it OBJ_id_pkix,4L
+
+#define SN_id_pkip "id-pkip"
+#define NID_id_pkip 261
+#define OBJ_id_pkip OBJ_id_pkix,5L
+
+#define SN_id_alg "id-alg"
+#define NID_id_alg 262
+#define OBJ_id_alg OBJ_id_pkix,6L
+
+#define SN_id_cmc "id-cmc"
+#define NID_id_cmc 263
+#define OBJ_id_cmc OBJ_id_pkix,7L
+
+#define SN_id_on "id-on"
+#define NID_id_on 264
+#define OBJ_id_on OBJ_id_pkix,8L
+
+#define SN_id_pda "id-pda"
+#define NID_id_pda 265
+#define OBJ_id_pda OBJ_id_pkix,9L
+
+#define SN_id_aca "id-aca"
+#define NID_id_aca 266
+#define OBJ_id_aca OBJ_id_pkix,10L
+
+#define SN_id_qcs "id-qcs"
+#define NID_id_qcs 267
+#define OBJ_id_qcs OBJ_id_pkix,11L
+
+#define SN_id_cp "id-cp"
+#define NID_id_cp 1238
+#define OBJ_id_cp OBJ_id_pkix,14L
+
+#define SN_id_cct "id-cct"
+#define NID_id_cct 268
+#define OBJ_id_cct OBJ_id_pkix,12L
+
+#define SN_id_ppl "id-ppl"
+#define NID_id_ppl 662
+#define OBJ_id_ppl OBJ_id_pkix,21L
+
+#define SN_id_ad "id-ad"
+#define NID_id_ad 176
+#define OBJ_id_ad OBJ_id_pkix,48L
+
+#define SN_id_pkix1_explicit_88 "id-pkix1-explicit-88"
+#define NID_id_pkix1_explicit_88 269
+#define OBJ_id_pkix1_explicit_88 OBJ_id_pkix_mod,1L
+
+#define SN_id_pkix1_implicit_88 "id-pkix1-implicit-88"
+#define NID_id_pkix1_implicit_88 270
+#define OBJ_id_pkix1_implicit_88 OBJ_id_pkix_mod,2L
+
+#define SN_id_pkix1_explicit_93 "id-pkix1-explicit-93"
+#define NID_id_pkix1_explicit_93 271
+#define OBJ_id_pkix1_explicit_93 OBJ_id_pkix_mod,3L
+
+#define SN_id_pkix1_implicit_93 "id-pkix1-implicit-93"
+#define NID_id_pkix1_implicit_93 272
+#define OBJ_id_pkix1_implicit_93 OBJ_id_pkix_mod,4L
+
+#define SN_id_mod_crmf "id-mod-crmf"
+#define NID_id_mod_crmf 273
+#define OBJ_id_mod_crmf OBJ_id_pkix_mod,5L
+
+#define SN_id_mod_cmc "id-mod-cmc"
+#define NID_id_mod_cmc 274
+#define OBJ_id_mod_cmc OBJ_id_pkix_mod,6L
+
+#define SN_id_mod_kea_profile_88 "id-mod-kea-profile-88"
+#define NID_id_mod_kea_profile_88 275
+#define OBJ_id_mod_kea_profile_88 OBJ_id_pkix_mod,7L
+
+#define SN_id_mod_kea_profile_93 "id-mod-kea-profile-93"
+#define NID_id_mod_kea_profile_93 276
+#define OBJ_id_mod_kea_profile_93 OBJ_id_pkix_mod,8L
+
+#define SN_id_mod_cmp "id-mod-cmp"
+#define NID_id_mod_cmp 277
+#define OBJ_id_mod_cmp OBJ_id_pkix_mod,9L
+
+#define SN_id_mod_qualified_cert_88 "id-mod-qualified-cert-88"
+#define NID_id_mod_qualified_cert_88 278
+#define OBJ_id_mod_qualified_cert_88 OBJ_id_pkix_mod,10L
+
+#define SN_id_mod_qualified_cert_93 "id-mod-qualified-cert-93"
+#define NID_id_mod_qualified_cert_93 279
+#define OBJ_id_mod_qualified_cert_93 OBJ_id_pkix_mod,11L
+
+#define SN_id_mod_attribute_cert "id-mod-attribute-cert"
+#define NID_id_mod_attribute_cert 280
+#define OBJ_id_mod_attribute_cert OBJ_id_pkix_mod,12L
+
+#define SN_id_mod_timestamp_protocol "id-mod-timestamp-protocol"
+#define NID_id_mod_timestamp_protocol 281
+#define OBJ_id_mod_timestamp_protocol OBJ_id_pkix_mod,13L
+
+#define SN_id_mod_ocsp "id-mod-ocsp"
+#define NID_id_mod_ocsp 282
+#define OBJ_id_mod_ocsp OBJ_id_pkix_mod,14L
+
+#define SN_id_mod_dvcs "id-mod-dvcs"
+#define NID_id_mod_dvcs 283
+#define OBJ_id_mod_dvcs OBJ_id_pkix_mod,15L
+
+#define SN_id_mod_cmp2000 "id-mod-cmp2000"
+#define NID_id_mod_cmp2000 284
+#define OBJ_id_mod_cmp2000 OBJ_id_pkix_mod,16L
+
+#define SN_info_access "authorityInfoAccess"
+#define LN_info_access "Authority Information Access"
+#define NID_info_access 177
+#define OBJ_info_access OBJ_id_pe,1L
+
+#define SN_biometricInfo "biometricInfo"
+#define LN_biometricInfo "Biometric Info"
+#define NID_biometricInfo 285
+#define OBJ_biometricInfo OBJ_id_pe,2L
+
+#define SN_qcStatements "qcStatements"
+#define NID_qcStatements 286
+#define OBJ_qcStatements OBJ_id_pe,3L
+
+#define SN_ac_auditEntity "ac-auditEntity"
+#define NID_ac_auditEntity 287
+#define OBJ_ac_auditEntity OBJ_id_pe,4L
+
+#define SN_ac_targeting "ac-targeting"
+#define NID_ac_targeting 288
+#define OBJ_ac_targeting OBJ_id_pe,5L
+
+#define SN_aaControls "aaControls"
+#define NID_aaControls 289
+#define OBJ_aaControls OBJ_id_pe,6L
+
+#define SN_sbgp_ipAddrBlock "sbgp-ipAddrBlock"
+#define NID_sbgp_ipAddrBlock 290
+#define OBJ_sbgp_ipAddrBlock OBJ_id_pe,7L
+
+#define SN_sbgp_autonomousSysNum "sbgp-autonomousSysNum"
+#define NID_sbgp_autonomousSysNum 291
+#define OBJ_sbgp_autonomousSysNum OBJ_id_pe,8L
+
+#define SN_sbgp_routerIdentifier "sbgp-routerIdentifier"
+#define NID_sbgp_routerIdentifier 292
+#define OBJ_sbgp_routerIdentifier OBJ_id_pe,9L
+
+#define SN_ac_proxying "ac-proxying"
+#define NID_ac_proxying 397
+#define OBJ_ac_proxying OBJ_id_pe,10L
+
+#define SN_sinfo_access "subjectInfoAccess"
+#define LN_sinfo_access "Subject Information Access"
+#define NID_sinfo_access 398
+#define OBJ_sinfo_access OBJ_id_pe,11L
+
+#define SN_proxyCertInfo "proxyCertInfo"
+#define LN_proxyCertInfo "Proxy Certificate Information"
+#define NID_proxyCertInfo 663
+#define OBJ_proxyCertInfo OBJ_id_pe,14L
+
+#define SN_tlsfeature "tlsfeature"
+#define LN_tlsfeature "TLS Feature"
+#define NID_tlsfeature 1020
+#define OBJ_tlsfeature OBJ_id_pe,24L
+
+#define SN_sbgp_ipAddrBlockv2 "sbgp-ipAddrBlockv2"
+#define NID_sbgp_ipAddrBlockv2 1239
+#define OBJ_sbgp_ipAddrBlockv2 OBJ_id_pe,28L
+
+#define SN_sbgp_autonomousSysNumv2 "sbgp-autonomousSysNumv2"
+#define NID_sbgp_autonomousSysNumv2 1240
+#define OBJ_sbgp_autonomousSysNumv2 OBJ_id_pe,29L
+
+#define SN_id_qt_cps "id-qt-cps"
+#define LN_id_qt_cps "Policy Qualifier CPS"
+#define NID_id_qt_cps 164
+#define OBJ_id_qt_cps OBJ_id_qt,1L
+
+#define SN_id_qt_unotice "id-qt-unotice"
+#define LN_id_qt_unotice "Policy Qualifier User Notice"
+#define NID_id_qt_unotice 165
+#define OBJ_id_qt_unotice OBJ_id_qt,2L
+
+#define SN_textNotice "textNotice"
+#define NID_textNotice 293
+#define OBJ_textNotice OBJ_id_qt,3L
+
+#define SN_server_auth "serverAuth"
+#define LN_server_auth "TLS Web Server Authentication"
+#define NID_server_auth 129
+#define OBJ_server_auth OBJ_id_kp,1L
+
+#define SN_client_auth "clientAuth"
+#define LN_client_auth "TLS Web Client Authentication"
+#define NID_client_auth 130
+#define OBJ_client_auth OBJ_id_kp,2L
+
+#define SN_code_sign "codeSigning"
+#define LN_code_sign "Code Signing"
+#define NID_code_sign 131
+#define OBJ_code_sign OBJ_id_kp,3L
+
+#define SN_email_protect "emailProtection"
+#define LN_email_protect "E-mail Protection"
+#define NID_email_protect 132
+#define OBJ_email_protect OBJ_id_kp,4L
+
+#define SN_ipsecEndSystem "ipsecEndSystem"
+#define LN_ipsecEndSystem "IPSec End System"
+#define NID_ipsecEndSystem 294
+#define OBJ_ipsecEndSystem OBJ_id_kp,5L
+
+#define SN_ipsecTunnel "ipsecTunnel"
+#define LN_ipsecTunnel "IPSec Tunnel"
+#define NID_ipsecTunnel 295
+#define OBJ_ipsecTunnel OBJ_id_kp,6L
+
+#define SN_ipsecUser "ipsecUser"
+#define LN_ipsecUser "IPSec User"
+#define NID_ipsecUser 296
+#define OBJ_ipsecUser OBJ_id_kp,7L
+
+#define SN_time_stamp "timeStamping"
+#define LN_time_stamp "Time Stamping"
+#define NID_time_stamp 133
+#define OBJ_time_stamp OBJ_id_kp,8L
+
+#define SN_OCSP_sign "OCSPSigning"
+#define LN_OCSP_sign "OCSP Signing"
+#define NID_OCSP_sign 180
+#define OBJ_OCSP_sign OBJ_id_kp,9L
+
+#define SN_dvcs "DVCS"
+#define LN_dvcs "dvcs"
+#define NID_dvcs 297
+#define OBJ_dvcs OBJ_id_kp,10L
+
+#define SN_ipsec_IKE "ipsecIKE"
+#define LN_ipsec_IKE "ipsec Internet Key Exchange"
+#define NID_ipsec_IKE 1022
+#define OBJ_ipsec_IKE OBJ_id_kp,17L
+
+#define SN_capwapAC "capwapAC"
+#define LN_capwapAC "Ctrl/provision WAP Access"
+#define NID_capwapAC 1023
+#define OBJ_capwapAC OBJ_id_kp,18L
+
+#define SN_capwapWTP "capwapWTP"
+#define LN_capwapWTP "Ctrl/Provision WAP Termination"
+#define NID_capwapWTP 1024
+#define OBJ_capwapWTP OBJ_id_kp,19L
+
+#define SN_sshClient "secureShellClient"
+#define LN_sshClient "SSH Client"
+#define NID_sshClient 1025
+#define OBJ_sshClient OBJ_id_kp,21L
+
+#define SN_sshServer "secureShellServer"
+#define LN_sshServer "SSH Server"
+#define NID_sshServer 1026
+#define OBJ_sshServer OBJ_id_kp,22L
+
+#define SN_sendRouter "sendRouter"
+#define LN_sendRouter "Send Router"
+#define NID_sendRouter 1027
+#define OBJ_sendRouter OBJ_id_kp,23L
+
+#define SN_sendProxiedRouter "sendProxiedRouter"
+#define LN_sendProxiedRouter "Send Proxied Router"
+#define NID_sendProxiedRouter 1028
+#define OBJ_sendProxiedRouter OBJ_id_kp,24L
+
+#define SN_sendOwner "sendOwner"
+#define LN_sendOwner "Send Owner"
+#define NID_sendOwner 1029
+#define OBJ_sendOwner OBJ_id_kp,25L
+
+#define SN_sendProxiedOwner "sendProxiedOwner"
+#define LN_sendProxiedOwner "Send Proxied Owner"
+#define NID_sendProxiedOwner 1030
+#define OBJ_sendProxiedOwner OBJ_id_kp,26L
+
+#define SN_cmcCA "cmcCA"
+#define LN_cmcCA "CMC Certificate Authority"
+#define NID_cmcCA 1131
+#define OBJ_cmcCA OBJ_id_kp,27L
+
+#define SN_cmcRA "cmcRA"
+#define LN_cmcRA "CMC Registration Authority"
+#define NID_cmcRA 1132
+#define OBJ_cmcRA OBJ_id_kp,28L
+
+#define SN_cmcArchive "cmcArchive"
+#define LN_cmcArchive "CMC Archive Server"
+#define NID_cmcArchive 1219
+#define OBJ_cmcArchive OBJ_id_kp,29L
+
+#define SN_id_kp_bgpsec_router "id-kp-bgpsec-router"
+#define LN_id_kp_bgpsec_router "BGPsec Router"
+#define NID_id_kp_bgpsec_router 1220
+#define OBJ_id_kp_bgpsec_router OBJ_id_kp,30L
+
+#define SN_id_kp_BrandIndicatorforMessageIdentification "id-kp-BrandIndicatorforMessageIdentification"
+#define LN_id_kp_BrandIndicatorforMessageIdentification "Brand Indicator for Message Identification"
+#define NID_id_kp_BrandIndicatorforMessageIdentification 1221
+#define OBJ_id_kp_BrandIndicatorforMessageIdentification OBJ_id_kp,31L
+
+#define SN_cmKGA "cmKGA"
+#define LN_cmKGA "Certificate Management Key Generation Authority"
+#define NID_cmKGA 1222
+#define OBJ_cmKGA OBJ_id_kp,32L
+
+#define SN_id_it_caProtEncCert "id-it-caProtEncCert"
+#define NID_id_it_caProtEncCert 298
+#define OBJ_id_it_caProtEncCert OBJ_id_it,1L
+
+#define SN_id_it_signKeyPairTypes "id-it-signKeyPairTypes"
+#define NID_id_it_signKeyPairTypes 299
+#define OBJ_id_it_signKeyPairTypes OBJ_id_it,2L
+
+#define SN_id_it_encKeyPairTypes "id-it-encKeyPairTypes"
+#define NID_id_it_encKeyPairTypes 300
+#define OBJ_id_it_encKeyPairTypes OBJ_id_it,3L
+
+#define SN_id_it_preferredSymmAlg "id-it-preferredSymmAlg"
+#define NID_id_it_preferredSymmAlg 301
+#define OBJ_id_it_preferredSymmAlg OBJ_id_it,4L
+
+#define SN_id_it_caKeyUpdateInfo "id-it-caKeyUpdateInfo"
+#define NID_id_it_caKeyUpdateInfo 302
+#define OBJ_id_it_caKeyUpdateInfo OBJ_id_it,5L
+
+#define SN_id_it_currentCRL "id-it-currentCRL"
+#define NID_id_it_currentCRL 303
+#define OBJ_id_it_currentCRL OBJ_id_it,6L
+
+#define SN_id_it_unsupportedOIDs "id-it-unsupportedOIDs"
+#define NID_id_it_unsupportedOIDs 304
+#define OBJ_id_it_unsupportedOIDs OBJ_id_it,7L
+
+#define SN_id_it_subscriptionRequest "id-it-subscriptionRequest"
+#define NID_id_it_subscriptionRequest 305
+#define OBJ_id_it_subscriptionRequest OBJ_id_it,8L
+
+#define SN_id_it_subscriptionResponse "id-it-subscriptionResponse"
+#define NID_id_it_subscriptionResponse 306
+#define OBJ_id_it_subscriptionResponse OBJ_id_it,9L
+
+#define SN_id_it_keyPairParamReq "id-it-keyPairParamReq"
+#define NID_id_it_keyPairParamReq 307
+#define OBJ_id_it_keyPairParamReq OBJ_id_it,10L
+
+#define SN_id_it_keyPairParamRep "id-it-keyPairParamRep"
+#define NID_id_it_keyPairParamRep 308
+#define OBJ_id_it_keyPairParamRep OBJ_id_it,11L
+
+#define SN_id_it_revPassphrase "id-it-revPassphrase"
+#define NID_id_it_revPassphrase 309
+#define OBJ_id_it_revPassphrase OBJ_id_it,12L
+
+#define SN_id_it_implicitConfirm "id-it-implicitConfirm"
+#define NID_id_it_implicitConfirm 310
+#define OBJ_id_it_implicitConfirm OBJ_id_it,13L
+
+#define SN_id_it_confirmWaitTime "id-it-confirmWaitTime"
+#define NID_id_it_confirmWaitTime 311
+#define OBJ_id_it_confirmWaitTime OBJ_id_it,14L
+
+#define SN_id_it_origPKIMessage "id-it-origPKIMessage"
+#define NID_id_it_origPKIMessage 312
+#define OBJ_id_it_origPKIMessage OBJ_id_it,15L
+
+#define SN_id_it_suppLangTags "id-it-suppLangTags"
+#define NID_id_it_suppLangTags 784
+#define OBJ_id_it_suppLangTags OBJ_id_it,16L
+
+#define SN_id_it_caCerts "id-it-caCerts"
+#define NID_id_it_caCerts 1223
+#define OBJ_id_it_caCerts OBJ_id_it,17L
+
+#define SN_id_it_rootCaKeyUpdate "id-it-rootCaKeyUpdate"
+#define NID_id_it_rootCaKeyUpdate 1224
+#define OBJ_id_it_rootCaKeyUpdate OBJ_id_it,18L
+
+#define SN_id_it_certReqTemplate "id-it-certReqTemplate"
+#define NID_id_it_certReqTemplate 1225
+#define OBJ_id_it_certReqTemplate OBJ_id_it,19L
+
+#define SN_id_regCtrl "id-regCtrl"
+#define NID_id_regCtrl 313
+#define OBJ_id_regCtrl OBJ_id_pkip,1L
+
+#define SN_id_regInfo "id-regInfo"
+#define NID_id_regInfo 314
+#define OBJ_id_regInfo OBJ_id_pkip,2L
+
+#define SN_id_regCtrl_regToken "id-regCtrl-regToken"
+#define NID_id_regCtrl_regToken 315
+#define OBJ_id_regCtrl_regToken OBJ_id_regCtrl,1L
+
+#define SN_id_regCtrl_authenticator "id-regCtrl-authenticator"
+#define NID_id_regCtrl_authenticator 316
+#define OBJ_id_regCtrl_authenticator OBJ_id_regCtrl,2L
+
+#define SN_id_regCtrl_pkiPublicationInfo "id-regCtrl-pkiPublicationInfo"
+#define NID_id_regCtrl_pkiPublicationInfo 317
+#define OBJ_id_regCtrl_pkiPublicationInfo OBJ_id_regCtrl,3L
+
+#define SN_id_regCtrl_pkiArchiveOptions "id-regCtrl-pkiArchiveOptions"
+#define NID_id_regCtrl_pkiArchiveOptions 318
+#define OBJ_id_regCtrl_pkiArchiveOptions OBJ_id_regCtrl,4L
+
+#define SN_id_regCtrl_oldCertID "id-regCtrl-oldCertID"
+#define NID_id_regCtrl_oldCertID 319
+#define OBJ_id_regCtrl_oldCertID OBJ_id_regCtrl,5L
+
+#define SN_id_regCtrl_protocolEncrKey "id-regCtrl-protocolEncrKey"
+#define NID_id_regCtrl_protocolEncrKey 320
+#define OBJ_id_regCtrl_protocolEncrKey OBJ_id_regCtrl,6L
+
+#define SN_id_regInfo_utf8Pairs "id-regInfo-utf8Pairs"
+#define NID_id_regInfo_utf8Pairs 321
+#define OBJ_id_regInfo_utf8Pairs OBJ_id_regInfo,1L
+
+#define SN_id_regInfo_certReq "id-regInfo-certReq"
+#define NID_id_regInfo_certReq 322
+#define OBJ_id_regInfo_certReq OBJ_id_regInfo,2L
+
+#define SN_id_alg_des40 "id-alg-des40"
+#define NID_id_alg_des40 323
+#define OBJ_id_alg_des40 OBJ_id_alg,1L
+
+#define SN_id_alg_noSignature "id-alg-noSignature"
+#define NID_id_alg_noSignature 324
+#define OBJ_id_alg_noSignature OBJ_id_alg,2L
+
+#define SN_id_alg_dh_sig_hmac_sha1 "id-alg-dh-sig-hmac-sha1"
+#define NID_id_alg_dh_sig_hmac_sha1 325
+#define OBJ_id_alg_dh_sig_hmac_sha1 OBJ_id_alg,3L
+
+#define SN_id_alg_dh_pop "id-alg-dh-pop"
+#define NID_id_alg_dh_pop 326
+#define OBJ_id_alg_dh_pop OBJ_id_alg,4L
+
+#define SN_id_cmc_statusInfo "id-cmc-statusInfo"
+#define NID_id_cmc_statusInfo 327
+#define OBJ_id_cmc_statusInfo OBJ_id_cmc,1L
+
+#define SN_id_cmc_identification "id-cmc-identification"
+#define NID_id_cmc_identification 328
+#define OBJ_id_cmc_identification OBJ_id_cmc,2L
+
+#define SN_id_cmc_identityProof "id-cmc-identityProof"
+#define NID_id_cmc_identityProof 329
+#define OBJ_id_cmc_identityProof OBJ_id_cmc,3L
+
+#define SN_id_cmc_dataReturn "id-cmc-dataReturn"
+#define NID_id_cmc_dataReturn 330
+#define OBJ_id_cmc_dataReturn OBJ_id_cmc,4L
+
+#define SN_id_cmc_transactionId "id-cmc-transactionId"
+#define NID_id_cmc_transactionId 331
+#define OBJ_id_cmc_transactionId OBJ_id_cmc,5L
+
+#define SN_id_cmc_senderNonce "id-cmc-senderNonce"
+#define NID_id_cmc_senderNonce 332
+#define OBJ_id_cmc_senderNonce OBJ_id_cmc,6L
+
+#define SN_id_cmc_recipientNonce "id-cmc-recipientNonce"
+#define NID_id_cmc_recipientNonce 333
+#define OBJ_id_cmc_recipientNonce OBJ_id_cmc,7L
+
+#define SN_id_cmc_addExtensions "id-cmc-addExtensions"
+#define NID_id_cmc_addExtensions 334
+#define OBJ_id_cmc_addExtensions OBJ_id_cmc,8L
+
+#define SN_id_cmc_encryptedPOP "id-cmc-encryptedPOP"
+#define NID_id_cmc_encryptedPOP 335
+#define OBJ_id_cmc_encryptedPOP OBJ_id_cmc,9L
+
+#define SN_id_cmc_decryptedPOP "id-cmc-decryptedPOP"
+#define NID_id_cmc_decryptedPOP 336
+#define OBJ_id_cmc_decryptedPOP OBJ_id_cmc,10L
+
+#define SN_id_cmc_lraPOPWitness "id-cmc-lraPOPWitness"
+#define NID_id_cmc_lraPOPWitness 337
+#define OBJ_id_cmc_lraPOPWitness OBJ_id_cmc,11L
+
+#define SN_id_cmc_getCert "id-cmc-getCert"
+#define NID_id_cmc_getCert 338
+#define OBJ_id_cmc_getCert OBJ_id_cmc,15L
+
+#define SN_id_cmc_getCRL "id-cmc-getCRL"
+#define NID_id_cmc_getCRL 339
+#define OBJ_id_cmc_getCRL OBJ_id_cmc,16L
+
+#define SN_id_cmc_revokeRequest "id-cmc-revokeRequest"
+#define NID_id_cmc_revokeRequest 340
+#define OBJ_id_cmc_revokeRequest OBJ_id_cmc,17L
+
+#define SN_id_cmc_regInfo "id-cmc-regInfo"
+#define NID_id_cmc_regInfo 341
+#define OBJ_id_cmc_regInfo OBJ_id_cmc,18L
+
+#define SN_id_cmc_responseInfo "id-cmc-responseInfo"
+#define NID_id_cmc_responseInfo 342
+#define OBJ_id_cmc_responseInfo OBJ_id_cmc,19L
+
+#define SN_id_cmc_queryPending "id-cmc-queryPending"
+#define NID_id_cmc_queryPending 343
+#define OBJ_id_cmc_queryPending OBJ_id_cmc,21L
+
+#define SN_id_cmc_popLinkRandom "id-cmc-popLinkRandom"
+#define NID_id_cmc_popLinkRandom 344
+#define OBJ_id_cmc_popLinkRandom OBJ_id_cmc,22L
+
+#define SN_id_cmc_popLinkWitness "id-cmc-popLinkWitness"
+#define NID_id_cmc_popLinkWitness 345
+#define OBJ_id_cmc_popLinkWitness OBJ_id_cmc,23L
+
+#define SN_id_cmc_confirmCertAcceptance "id-cmc-confirmCertAcceptance"
+#define NID_id_cmc_confirmCertAcceptance 346
+#define OBJ_id_cmc_confirmCertAcceptance OBJ_id_cmc,24L
+
+#define SN_id_on_personalData "id-on-personalData"
+#define NID_id_on_personalData 347
+#define OBJ_id_on_personalData OBJ_id_on,1L
+
+#define SN_id_on_permanentIdentifier "id-on-permanentIdentifier"
+#define LN_id_on_permanentIdentifier "Permanent Identifier"
+#define NID_id_on_permanentIdentifier 858
+#define OBJ_id_on_permanentIdentifier OBJ_id_on,3L
+
+#define SN_XmppAddr "id-on-xmppAddr"
+#define LN_XmppAddr "XmppAddr"
+#define NID_XmppAddr 1209
+#define OBJ_XmppAddr OBJ_id_on,5L
+
+#define SN_SRVName "id-on-dnsSRV"
+#define LN_SRVName "SRVName"
+#define NID_SRVName 1210
+#define OBJ_SRVName OBJ_id_on,7L
+
+#define SN_NAIRealm "id-on-NAIRealm"
+#define LN_NAIRealm "NAIRealm"
+#define NID_NAIRealm 1211
+#define OBJ_NAIRealm OBJ_id_on,8L
+
+#define SN_id_on_SmtpUTF8Mailbox "id-on-SmtpUTF8Mailbox"
+#define LN_id_on_SmtpUTF8Mailbox "Smtp UTF8 Mailbox"
+#define NID_id_on_SmtpUTF8Mailbox 1208
+#define OBJ_id_on_SmtpUTF8Mailbox OBJ_id_on,9L
+
+#define SN_id_pda_dateOfBirth "id-pda-dateOfBirth"
+#define NID_id_pda_dateOfBirth 348
+#define OBJ_id_pda_dateOfBirth OBJ_id_pda,1L
+
+#define SN_id_pda_placeOfBirth "id-pda-placeOfBirth"
+#define NID_id_pda_placeOfBirth 349
+#define OBJ_id_pda_placeOfBirth OBJ_id_pda,2L
+
+#define SN_id_pda_gender "id-pda-gender"
+#define NID_id_pda_gender 351
+#define OBJ_id_pda_gender OBJ_id_pda,3L
+
+#define SN_id_pda_countryOfCitizenship "id-pda-countryOfCitizenship"
+#define NID_id_pda_countryOfCitizenship 352
+#define OBJ_id_pda_countryOfCitizenship OBJ_id_pda,4L
+
+#define SN_id_pda_countryOfResidence "id-pda-countryOfResidence"
+#define NID_id_pda_countryOfResidence 353
+#define OBJ_id_pda_countryOfResidence OBJ_id_pda,5L
+
+#define SN_id_aca_authenticationInfo "id-aca-authenticationInfo"
+#define NID_id_aca_authenticationInfo 354
+#define OBJ_id_aca_authenticationInfo OBJ_id_aca,1L
+
+#define SN_id_aca_accessIdentity "id-aca-accessIdentity"
+#define NID_id_aca_accessIdentity 355
+#define OBJ_id_aca_accessIdentity OBJ_id_aca,2L
+
+#define SN_id_aca_chargingIdentity "id-aca-chargingIdentity"
+#define NID_id_aca_chargingIdentity 356
+#define OBJ_id_aca_chargingIdentity OBJ_id_aca,3L
+
+#define SN_id_aca_group "id-aca-group"
+#define NID_id_aca_group 357
+#define OBJ_id_aca_group OBJ_id_aca,4L
+
+#define SN_id_aca_role "id-aca-role"
+#define NID_id_aca_role 358
+#define OBJ_id_aca_role OBJ_id_aca,5L
+
+#define SN_id_aca_encAttrs "id-aca-encAttrs"
+#define NID_id_aca_encAttrs 399
+#define OBJ_id_aca_encAttrs OBJ_id_aca,6L
+
+#define SN_id_qcs_pkixQCSyntax_v1 "id-qcs-pkixQCSyntax-v1"
+#define NID_id_qcs_pkixQCSyntax_v1 359
+#define OBJ_id_qcs_pkixQCSyntax_v1 OBJ_id_qcs,1L
+
+#define SN_ipAddr_asNumber "ipAddr-asNumber"
+#define NID_ipAddr_asNumber 1241
+#define OBJ_ipAddr_asNumber OBJ_id_cp,2L
+
+#define SN_ipAddr_asNumberv2 "ipAddr-asNumberv2"
+#define NID_ipAddr_asNumberv2 1242
+#define OBJ_ipAddr_asNumberv2 OBJ_id_cp,3L
+
+#define SN_id_cct_crs "id-cct-crs"
+#define NID_id_cct_crs 360
+#define OBJ_id_cct_crs OBJ_id_cct,1L
+
+#define SN_id_cct_PKIData "id-cct-PKIData"
+#define NID_id_cct_PKIData 361
+#define OBJ_id_cct_PKIData OBJ_id_cct,2L
+
+#define SN_id_cct_PKIResponse "id-cct-PKIResponse"
+#define NID_id_cct_PKIResponse 362
+#define OBJ_id_cct_PKIResponse OBJ_id_cct,3L
+
+#define SN_id_ppl_anyLanguage "id-ppl-anyLanguage"
+#define LN_id_ppl_anyLanguage "Any language"
+#define NID_id_ppl_anyLanguage 664
+#define OBJ_id_ppl_anyLanguage OBJ_id_ppl,0L
+
+#define SN_id_ppl_inheritAll "id-ppl-inheritAll"
+#define LN_id_ppl_inheritAll "Inherit all"
+#define NID_id_ppl_inheritAll 665
+#define OBJ_id_ppl_inheritAll OBJ_id_ppl,1L
+
+#define SN_Independent "id-ppl-independent"
+#define LN_Independent "Independent"
+#define NID_Independent 667
+#define OBJ_Independent OBJ_id_ppl,2L
+
+#define SN_ad_OCSP "OCSP"
+#define LN_ad_OCSP "OCSP"
+#define NID_ad_OCSP 178
+#define OBJ_ad_OCSP OBJ_id_ad,1L
+
+#define SN_ad_ca_issuers "caIssuers"
+#define LN_ad_ca_issuers "CA Issuers"
+#define NID_ad_ca_issuers 179
+#define OBJ_ad_ca_issuers OBJ_id_ad,2L
+
+#define SN_ad_timeStamping "ad_timestamping"
+#define LN_ad_timeStamping "AD Time Stamping"
+#define NID_ad_timeStamping 363
+#define OBJ_ad_timeStamping OBJ_id_ad,3L
+
+#define SN_ad_dvcs "AD_DVCS"
+#define LN_ad_dvcs "ad dvcs"
+#define NID_ad_dvcs 364
+#define OBJ_ad_dvcs OBJ_id_ad,4L
+
+#define SN_caRepository "caRepository"
+#define LN_caRepository "CA Repository"
+#define NID_caRepository 785
+#define OBJ_caRepository OBJ_id_ad,5L
+
+#define SN_rpkiManifest "rpkiManifest"
+#define LN_rpkiManifest "RPKI Manifest"
+#define NID_rpkiManifest 1243
+#define OBJ_rpkiManifest OBJ_id_ad,10L
+
+#define SN_signedObject "signedObject"
+#define LN_signedObject "Signed Object"
+#define NID_signedObject 1244
+#define OBJ_signedObject OBJ_id_ad,11L
+
+#define SN_rpkiNotify "rpkiNotify"
+#define LN_rpkiNotify "RPKI Notify"
+#define NID_rpkiNotify 1245
+#define OBJ_rpkiNotify OBJ_id_ad,13L
+
+#define OBJ_id_pkix_OCSP OBJ_ad_OCSP
+
+#define SN_id_pkix_OCSP_basic "basicOCSPResponse"
+#define LN_id_pkix_OCSP_basic "Basic OCSP Response"
+#define NID_id_pkix_OCSP_basic 365
+#define OBJ_id_pkix_OCSP_basic OBJ_id_pkix_OCSP,1L
+
+#define SN_id_pkix_OCSP_Nonce "Nonce"
+#define LN_id_pkix_OCSP_Nonce "OCSP Nonce"
+#define NID_id_pkix_OCSP_Nonce 366
+#define OBJ_id_pkix_OCSP_Nonce OBJ_id_pkix_OCSP,2L
+
+#define SN_id_pkix_OCSP_CrlID "CrlID"
+#define LN_id_pkix_OCSP_CrlID "OCSP CRL ID"
+#define NID_id_pkix_OCSP_CrlID 367
+#define OBJ_id_pkix_OCSP_CrlID OBJ_id_pkix_OCSP,3L
+
+#define SN_id_pkix_OCSP_acceptableResponses "acceptableResponses"
+#define LN_id_pkix_OCSP_acceptableResponses "Acceptable OCSP Responses"
+#define NID_id_pkix_OCSP_acceptableResponses 368
+#define OBJ_id_pkix_OCSP_acceptableResponses OBJ_id_pkix_OCSP,4L
+
+#define SN_id_pkix_OCSP_noCheck "noCheck"
+#define LN_id_pkix_OCSP_noCheck "OCSP No Check"
+#define NID_id_pkix_OCSP_noCheck 369
+#define OBJ_id_pkix_OCSP_noCheck OBJ_id_pkix_OCSP,5L
+
+#define SN_id_pkix_OCSP_archiveCutoff "archiveCutoff"
+#define LN_id_pkix_OCSP_archiveCutoff "OCSP Archive Cutoff"
+#define NID_id_pkix_OCSP_archiveCutoff 370
+#define OBJ_id_pkix_OCSP_archiveCutoff OBJ_id_pkix_OCSP,6L
+
+#define SN_id_pkix_OCSP_serviceLocator "serviceLocator"
+#define LN_id_pkix_OCSP_serviceLocator "OCSP Service Locator"
+#define NID_id_pkix_OCSP_serviceLocator 371
+#define OBJ_id_pkix_OCSP_serviceLocator OBJ_id_pkix_OCSP,7L
+
+#define SN_id_pkix_OCSP_extendedStatus "extendedStatus"
+#define LN_id_pkix_OCSP_extendedStatus "Extended OCSP Status"
+#define NID_id_pkix_OCSP_extendedStatus 372
+#define OBJ_id_pkix_OCSP_extendedStatus OBJ_id_pkix_OCSP,8L
+
+#define SN_id_pkix_OCSP_valid "valid"
+#define NID_id_pkix_OCSP_valid 373
+#define OBJ_id_pkix_OCSP_valid OBJ_id_pkix_OCSP,9L
+
+#define SN_id_pkix_OCSP_path "path"
+#define NID_id_pkix_OCSP_path 374
+#define OBJ_id_pkix_OCSP_path OBJ_id_pkix_OCSP,10L
+
+#define SN_id_pkix_OCSP_trustRoot "trustRoot"
+#define LN_id_pkix_OCSP_trustRoot "Trust Root"
+#define NID_id_pkix_OCSP_trustRoot 375
+#define OBJ_id_pkix_OCSP_trustRoot OBJ_id_pkix_OCSP,11L
+
+#define SN_algorithm "algorithm"
+#define LN_algorithm "algorithm"
+#define NID_algorithm 376
+#define OBJ_algorithm 1L,3L,14L,3L,2L
+
+#define SN_md5WithRSA "RSA-NP-MD5"
+#define LN_md5WithRSA "md5WithRSA"
+#define NID_md5WithRSA 104
+#define OBJ_md5WithRSA OBJ_algorithm,3L
+
+#define SN_des_ecb "DES-ECB"
+#define LN_des_ecb "des-ecb"
+#define NID_des_ecb 29
+#define OBJ_des_ecb OBJ_algorithm,6L
+
+#define SN_des_cbc "DES-CBC"
+#define LN_des_cbc "des-cbc"
+#define NID_des_cbc 31
+#define OBJ_des_cbc OBJ_algorithm,7L
+
+#define SN_des_ofb64 "DES-OFB"
+#define LN_des_ofb64 "des-ofb"
+#define NID_des_ofb64 45
+#define OBJ_des_ofb64 OBJ_algorithm,8L
+
+#define SN_des_cfb64 "DES-CFB"
+#define LN_des_cfb64 "des-cfb"
+#define NID_des_cfb64 30
+#define OBJ_des_cfb64 OBJ_algorithm,9L
+
+#define SN_rsaSignature "rsaSignature"
+#define NID_rsaSignature 377
+#define OBJ_rsaSignature OBJ_algorithm,11L
+
+#define SN_dsa_2 "DSA-old"
+#define LN_dsa_2 "dsaEncryption-old"
+#define NID_dsa_2 67
+#define OBJ_dsa_2 OBJ_algorithm,12L
+
+#define SN_dsaWithSHA "DSA-SHA"
+#define LN_dsaWithSHA "dsaWithSHA"
+#define NID_dsaWithSHA 66
+#define OBJ_dsaWithSHA OBJ_algorithm,13L
+
+#define SN_shaWithRSAEncryption "RSA-SHA"
+#define LN_shaWithRSAEncryption "shaWithRSAEncryption"
+#define NID_shaWithRSAEncryption 42
+#define OBJ_shaWithRSAEncryption OBJ_algorithm,15L
+
+#define SN_des_ede_ecb "DES-EDE"
+#define LN_des_ede_ecb "des-ede"
+#define NID_des_ede_ecb 32
+#define OBJ_des_ede_ecb OBJ_algorithm,17L
+
+#define SN_des_ede3_ecb "DES-EDE3"
+#define LN_des_ede3_ecb "des-ede3"
+#define NID_des_ede3_ecb 33
+
+#define SN_des_ede_cbc "DES-EDE-CBC"
+#define LN_des_ede_cbc "des-ede-cbc"
+#define NID_des_ede_cbc 43
+
+#define SN_des_ede_cfb64 "DES-EDE-CFB"
+#define LN_des_ede_cfb64 "des-ede-cfb"
+#define NID_des_ede_cfb64 60
+
+#define SN_des_ede3_cfb64 "DES-EDE3-CFB"
+#define LN_des_ede3_cfb64 "des-ede3-cfb"
+#define NID_des_ede3_cfb64 61
+
+#define SN_des_ede_ofb64 "DES-EDE-OFB"
+#define LN_des_ede_ofb64 "des-ede-ofb"
+#define NID_des_ede_ofb64 62
+
+#define SN_des_ede3_ofb64 "DES-EDE3-OFB"
+#define LN_des_ede3_ofb64 "des-ede3-ofb"
+#define NID_des_ede3_ofb64 63
+
+#define SN_desx_cbc "DESX-CBC"
+#define LN_desx_cbc "desx-cbc"
+#define NID_desx_cbc 80
+
+#define SN_sha "SHA"
+#define LN_sha "sha"
+#define NID_sha 41
+#define OBJ_sha OBJ_algorithm,18L
+
+#define SN_sha1 "SHA1"
+#define LN_sha1 "sha1"
+#define NID_sha1 64
+#define OBJ_sha1 OBJ_algorithm,26L
+
+#define SN_dsaWithSHA1_2 "DSA-SHA1-old"
+#define LN_dsaWithSHA1_2 "dsaWithSHA1-old"
+#define NID_dsaWithSHA1_2 70
+#define OBJ_dsaWithSHA1_2 OBJ_algorithm,27L
+
+#define SN_sha1WithRSA "RSA-SHA1-2"
+#define LN_sha1WithRSA "sha1WithRSA"
+#define NID_sha1WithRSA 115
+#define OBJ_sha1WithRSA OBJ_algorithm,29L
+
+#define SN_ripemd160 "RIPEMD160"
+#define LN_ripemd160 "ripemd160"
+#define NID_ripemd160 117
+#define OBJ_ripemd160 1L,3L,36L,3L,2L,1L
+
+#define SN_ripemd160WithRSA "RSA-RIPEMD160"
+#define LN_ripemd160WithRSA "ripemd160WithRSA"
+#define NID_ripemd160WithRSA 119
+#define OBJ_ripemd160WithRSA 1L,3L,36L,3L,3L,1L,2L
+
+#define SN_blake2bmac "BLAKE2BMAC"
+#define LN_blake2bmac "blake2bmac"
+#define NID_blake2bmac 1201
+#define OBJ_blake2bmac 1L,3L,6L,1L,4L,1L,1722L,12L,2L,1L
+
+#define SN_blake2smac "BLAKE2SMAC"
+#define LN_blake2smac "blake2smac"
+#define NID_blake2smac 1202
+#define OBJ_blake2smac 1L,3L,6L,1L,4L,1L,1722L,12L,2L,2L
+
+#define SN_blake2b512 "BLAKE2b512"
+#define LN_blake2b512 "blake2b512"
+#define NID_blake2b512 1056
+#define OBJ_blake2b512 OBJ_blake2bmac,16L
+
+#define SN_blake2s256 "BLAKE2s256"
+#define LN_blake2s256 "blake2s256"
+#define NID_blake2s256 1057
+#define OBJ_blake2s256 OBJ_blake2smac,8L
+
+#define SN_sxnet "SXNetID"
+#define LN_sxnet "Strong Extranet ID"
+#define NID_sxnet 143
+#define OBJ_sxnet 1L,3L,101L,1L,4L,1L
+
+#define SN_X500 "X500"
+#define LN_X500 "directory services (X.500)"
+#define NID_X500 11
+#define OBJ_X500 2L,5L
+
+#define SN_X509 "X509"
+#define NID_X509 12
+#define OBJ_X509 OBJ_X500,4L
+
+#define SN_commonName "CN"
+#define LN_commonName "commonName"
+#define NID_commonName 13
+#define OBJ_commonName OBJ_X509,3L
+
+#define SN_surname "SN"
+#define LN_surname "surname"
+#define NID_surname 100
+#define OBJ_surname OBJ_X509,4L
+
+#define LN_serialNumber "serialNumber"
+#define NID_serialNumber 105
+#define OBJ_serialNumber OBJ_X509,5L
+
+#define SN_countryName "C"
+#define LN_countryName "countryName"
+#define NID_countryName 14
+#define OBJ_countryName OBJ_X509,6L
+
+#define SN_localityName "L"
+#define LN_localityName "localityName"
+#define NID_localityName 15
+#define OBJ_localityName OBJ_X509,7L
+
+#define SN_stateOrProvinceName "ST"
+#define LN_stateOrProvinceName "stateOrProvinceName"
+#define NID_stateOrProvinceName 16
+#define OBJ_stateOrProvinceName OBJ_X509,8L
+
+#define SN_streetAddress "street"
+#define LN_streetAddress "streetAddress"
+#define NID_streetAddress 660
+#define OBJ_streetAddress OBJ_X509,9L
+
+#define SN_organizationName "O"
+#define LN_organizationName "organizationName"
+#define NID_organizationName 17
+#define OBJ_organizationName OBJ_X509,10L
+
+#define SN_organizationalUnitName "OU"
+#define LN_organizationalUnitName "organizationalUnitName"
+#define NID_organizationalUnitName 18
+#define OBJ_organizationalUnitName OBJ_X509,11L
+
+#define SN_title "title"
+#define LN_title "title"
+#define NID_title 106
+#define OBJ_title OBJ_X509,12L
+
+#define LN_description "description"
+#define NID_description 107
+#define OBJ_description OBJ_X509,13L
+
+#define LN_searchGuide "searchGuide"
+#define NID_searchGuide 859
+#define OBJ_searchGuide OBJ_X509,14L
+
+#define LN_businessCategory "businessCategory"
+#define NID_businessCategory 860
+#define OBJ_businessCategory OBJ_X509,15L
+
+#define LN_postalAddress "postalAddress"
+#define NID_postalAddress 861
+#define OBJ_postalAddress OBJ_X509,16L
+
+#define LN_postalCode "postalCode"
+#define NID_postalCode 661
+#define OBJ_postalCode OBJ_X509,17L
+
+#define LN_postOfficeBox "postOfficeBox"
+#define NID_postOfficeBox 862
+#define OBJ_postOfficeBox OBJ_X509,18L
+
+#define LN_physicalDeliveryOfficeName "physicalDeliveryOfficeName"
+#define NID_physicalDeliveryOfficeName 863
+#define OBJ_physicalDeliveryOfficeName OBJ_X509,19L
+
+#define LN_telephoneNumber "telephoneNumber"
+#define NID_telephoneNumber 864
+#define OBJ_telephoneNumber OBJ_X509,20L
+
+#define LN_telexNumber "telexNumber"
+#define NID_telexNumber 865
+#define OBJ_telexNumber OBJ_X509,21L
+
+#define LN_teletexTerminalIdentifier "teletexTerminalIdentifier"
+#define NID_teletexTerminalIdentifier 866
+#define OBJ_teletexTerminalIdentifier OBJ_X509,22L
+
+#define LN_facsimileTelephoneNumber "facsimileTelephoneNumber"
+#define NID_facsimileTelephoneNumber 867
+#define OBJ_facsimileTelephoneNumber OBJ_X509,23L
+
+#define LN_x121Address "x121Address"
+#define NID_x121Address 868
+#define OBJ_x121Address OBJ_X509,24L
+
+#define LN_internationaliSDNNumber "internationaliSDNNumber"
+#define NID_internationaliSDNNumber 869
+#define OBJ_internationaliSDNNumber OBJ_X509,25L
+
+#define LN_registeredAddress "registeredAddress"
+#define NID_registeredAddress 870
+#define OBJ_registeredAddress OBJ_X509,26L
+
+#define LN_destinationIndicator "destinationIndicator"
+#define NID_destinationIndicator 871
+#define OBJ_destinationIndicator OBJ_X509,27L
+
+#define LN_preferredDeliveryMethod "preferredDeliveryMethod"
+#define NID_preferredDeliveryMethod 872
+#define OBJ_preferredDeliveryMethod OBJ_X509,28L
+
+#define LN_presentationAddress "presentationAddress"
+#define NID_presentationAddress 873
+#define OBJ_presentationAddress OBJ_X509,29L
+
+#define LN_supportedApplicationContext "supportedApplicationContext"
+#define NID_supportedApplicationContext 874
+#define OBJ_supportedApplicationContext OBJ_X509,30L
+
+#define SN_member "member"
+#define NID_member 875
+#define OBJ_member OBJ_X509,31L
+
+#define SN_owner "owner"
+#define NID_owner 876
+#define OBJ_owner OBJ_X509,32L
+
+#define LN_roleOccupant "roleOccupant"
+#define NID_roleOccupant 877
+#define OBJ_roleOccupant OBJ_X509,33L
+
+#define SN_seeAlso "seeAlso"
+#define NID_seeAlso 878
+#define OBJ_seeAlso OBJ_X509,34L
+
+#define LN_userPassword "userPassword"
+#define NID_userPassword 879
+#define OBJ_userPassword OBJ_X509,35L
+
+#define LN_userCertificate "userCertificate"
+#define NID_userCertificate 880
+#define OBJ_userCertificate OBJ_X509,36L
+
+#define LN_cACertificate "cACertificate"
+#define NID_cACertificate 881
+#define OBJ_cACertificate OBJ_X509,37L
+
+#define LN_authorityRevocationList "authorityRevocationList"
+#define NID_authorityRevocationList 882
+#define OBJ_authorityRevocationList OBJ_X509,38L
+
+#define LN_certificateRevocationList "certificateRevocationList"
+#define NID_certificateRevocationList 883
+#define OBJ_certificateRevocationList OBJ_X509,39L
+
+#define LN_crossCertificatePair "crossCertificatePair"
+#define NID_crossCertificatePair 884
+#define OBJ_crossCertificatePair OBJ_X509,40L
+
+#define SN_name "name"
+#define LN_name "name"
+#define NID_name 173
+#define OBJ_name OBJ_X509,41L
+
+#define SN_givenName "GN"
+#define LN_givenName "givenName"
+#define NID_givenName 99
+#define OBJ_givenName OBJ_X509,42L
+
+#define SN_initials "initials"
+#define LN_initials "initials"
+#define NID_initials 101
+#define OBJ_initials OBJ_X509,43L
+
+#define LN_generationQualifier "generationQualifier"
+#define NID_generationQualifier 509
+#define OBJ_generationQualifier OBJ_X509,44L
+
+#define LN_x500UniqueIdentifier "x500UniqueIdentifier"
+#define NID_x500UniqueIdentifier 503
+#define OBJ_x500UniqueIdentifier OBJ_X509,45L
+
+#define SN_dnQualifier "dnQualifier"
+#define LN_dnQualifier "dnQualifier"
+#define NID_dnQualifier 174
+#define OBJ_dnQualifier OBJ_X509,46L
+
+#define LN_enhancedSearchGuide "enhancedSearchGuide"
+#define NID_enhancedSearchGuide 885
+#define OBJ_enhancedSearchGuide OBJ_X509,47L
+
+#define LN_protocolInformation "protocolInformation"
+#define NID_protocolInformation 886
+#define OBJ_protocolInformation OBJ_X509,48L
+
+#define LN_distinguishedName "distinguishedName"
+#define NID_distinguishedName 887
+#define OBJ_distinguishedName OBJ_X509,49L
+
+#define LN_uniqueMember "uniqueMember"
+#define NID_uniqueMember 888
+#define OBJ_uniqueMember OBJ_X509,50L
+
+#define LN_houseIdentifier "houseIdentifier"
+#define NID_houseIdentifier 889
+#define OBJ_houseIdentifier OBJ_X509,51L
+
+#define LN_supportedAlgorithms "supportedAlgorithms"
+#define NID_supportedAlgorithms 890
+#define OBJ_supportedAlgorithms OBJ_X509,52L
+
+#define LN_deltaRevocationList "deltaRevocationList"
+#define NID_deltaRevocationList 891
+#define OBJ_deltaRevocationList OBJ_X509,53L
+
+#define SN_dmdName "dmdName"
+#define NID_dmdName 892
+#define OBJ_dmdName OBJ_X509,54L
+
+#define LN_pseudonym "pseudonym"
+#define NID_pseudonym 510
+#define OBJ_pseudonym OBJ_X509,65L
+
+#define SN_role "role"
+#define LN_role "role"
+#define NID_role 400
+#define OBJ_role OBJ_X509,72L
+
+#define LN_organizationIdentifier "organizationIdentifier"
+#define NID_organizationIdentifier 1089
+#define OBJ_organizationIdentifier OBJ_X509,97L
+
+#define SN_countryCode3c "c3"
+#define LN_countryCode3c "countryCode3c"
+#define NID_countryCode3c 1090
+#define OBJ_countryCode3c OBJ_X509,98L
+
+#define SN_countryCode3n "n3"
+#define LN_countryCode3n "countryCode3n"
+#define NID_countryCode3n 1091
+#define OBJ_countryCode3n OBJ_X509,99L
+
+#define LN_dnsName "dnsName"
+#define NID_dnsName 1092
+#define OBJ_dnsName OBJ_X509,100L
+
+#define SN_X500algorithms "X500algorithms"
+#define LN_X500algorithms "directory services - algorithms"
+#define NID_X500algorithms 378
+#define OBJ_X500algorithms OBJ_X500,8L
+
+#define SN_rsa "RSA"
+#define LN_rsa "rsa"
+#define NID_rsa 19
+#define OBJ_rsa OBJ_X500algorithms,1L,1L
+
+#define SN_mdc2WithRSA "RSA-MDC2"
+#define LN_mdc2WithRSA "mdc2WithRSA"
+#define NID_mdc2WithRSA 96
+#define OBJ_mdc2WithRSA OBJ_X500algorithms,3L,100L
+
+#define SN_mdc2 "MDC2"
+#define LN_mdc2 "mdc2"
+#define NID_mdc2 95
+#define OBJ_mdc2 OBJ_X500algorithms,3L,101L
+
+#define SN_id_ce "id-ce"
+#define NID_id_ce 81
+#define OBJ_id_ce OBJ_X500,29L
+
+#define SN_subject_directory_attributes "subjectDirectoryAttributes"
+#define LN_subject_directory_attributes "X509v3 Subject Directory Attributes"
+#define NID_subject_directory_attributes 769
+#define OBJ_subject_directory_attributes OBJ_id_ce,9L
+
+#define SN_subject_key_identifier "subjectKeyIdentifier"
+#define LN_subject_key_identifier "X509v3 Subject Key Identifier"
+#define NID_subject_key_identifier 82
+#define OBJ_subject_key_identifier OBJ_id_ce,14L
+
+#define SN_key_usage "keyUsage"
+#define LN_key_usage "X509v3 Key Usage"
+#define NID_key_usage 83
+#define OBJ_key_usage OBJ_id_ce,15L
+
+#define SN_private_key_usage_period "privateKeyUsagePeriod"
+#define LN_private_key_usage_period "X509v3 Private Key Usage Period"
+#define NID_private_key_usage_period 84
+#define OBJ_private_key_usage_period OBJ_id_ce,16L
+
+#define SN_subject_alt_name "subjectAltName"
+#define LN_subject_alt_name "X509v3 Subject Alternative Name"
+#define NID_subject_alt_name 85
+#define OBJ_subject_alt_name OBJ_id_ce,17L
+
+#define SN_issuer_alt_name "issuerAltName"
+#define LN_issuer_alt_name "X509v3 Issuer Alternative Name"
+#define NID_issuer_alt_name 86
+#define OBJ_issuer_alt_name OBJ_id_ce,18L
+
+#define SN_basic_constraints "basicConstraints"
+#define LN_basic_constraints "X509v3 Basic Constraints"
+#define NID_basic_constraints 87
+#define OBJ_basic_constraints OBJ_id_ce,19L
+
+#define SN_crl_number "crlNumber"
+#define LN_crl_number "X509v3 CRL Number"
+#define NID_crl_number 88
+#define OBJ_crl_number OBJ_id_ce,20L
+
+#define SN_crl_reason "CRLReason"
+#define LN_crl_reason "X509v3 CRL Reason Code"
+#define NID_crl_reason 141
+#define OBJ_crl_reason OBJ_id_ce,21L
+
+#define SN_invalidity_date "invalidityDate"
+#define LN_invalidity_date "Invalidity Date"
+#define NID_invalidity_date 142
+#define OBJ_invalidity_date OBJ_id_ce,24L
+
+#define SN_delta_crl "deltaCRL"
+#define LN_delta_crl "X509v3 Delta CRL Indicator"
+#define NID_delta_crl 140
+#define OBJ_delta_crl OBJ_id_ce,27L
+
+#define SN_issuing_distribution_point "issuingDistributionPoint"
+#define LN_issuing_distribution_point "X509v3 Issuing Distribution Point"
+#define NID_issuing_distribution_point 770
+#define OBJ_issuing_distribution_point OBJ_id_ce,28L
+
+#define SN_certificate_issuer "certificateIssuer"
+#define LN_certificate_issuer "X509v3 Certificate Issuer"
+#define NID_certificate_issuer 771
+#define OBJ_certificate_issuer OBJ_id_ce,29L
+
+#define SN_name_constraints "nameConstraints"
+#define LN_name_constraints "X509v3 Name Constraints"
+#define NID_name_constraints 666
+#define OBJ_name_constraints OBJ_id_ce,30L
+
+#define SN_crl_distribution_points "crlDistributionPoints"
+#define LN_crl_distribution_points "X509v3 CRL Distribution Points"
+#define NID_crl_distribution_points 103
+#define OBJ_crl_distribution_points OBJ_id_ce,31L
+
+#define SN_certificate_policies "certificatePolicies"
+#define LN_certificate_policies "X509v3 Certificate Policies"
+#define NID_certificate_policies 89
+#define OBJ_certificate_policies OBJ_id_ce,32L
+
+#define SN_any_policy "anyPolicy"
+#define LN_any_policy "X509v3 Any Policy"
+#define NID_any_policy 746
+#define OBJ_any_policy OBJ_certificate_policies,0L
+
+#define SN_policy_mappings "policyMappings"
+#define LN_policy_mappings "X509v3 Policy Mappings"
+#define NID_policy_mappings 747
+#define OBJ_policy_mappings OBJ_id_ce,33L
+
+#define SN_authority_key_identifier "authorityKeyIdentifier"
+#define LN_authority_key_identifier "X509v3 Authority Key Identifier"
+#define NID_authority_key_identifier 90
+#define OBJ_authority_key_identifier OBJ_id_ce,35L
+
+#define SN_policy_constraints "policyConstraints"
+#define LN_policy_constraints "X509v3 Policy Constraints"
+#define NID_policy_constraints 401
+#define OBJ_policy_constraints OBJ_id_ce,36L
+
+#define SN_ext_key_usage "extendedKeyUsage"
+#define LN_ext_key_usage "X509v3 Extended Key Usage"
+#define NID_ext_key_usage 126
+#define OBJ_ext_key_usage OBJ_id_ce,37L
+
+#define SN_freshest_crl "freshestCRL"
+#define LN_freshest_crl "X509v3 Freshest CRL"
+#define NID_freshest_crl 857
+#define OBJ_freshest_crl OBJ_id_ce,46L
+
+#define SN_inhibit_any_policy "inhibitAnyPolicy"
+#define LN_inhibit_any_policy "X509v3 Inhibit Any Policy"
+#define NID_inhibit_any_policy 748
+#define OBJ_inhibit_any_policy OBJ_id_ce,54L
+
+#define SN_target_information "targetInformation"
+#define LN_target_information "X509v3 AC Targeting"
+#define NID_target_information 402
+#define OBJ_target_information OBJ_id_ce,55L
+
+#define SN_no_rev_avail "noRevAvail"
+#define LN_no_rev_avail "X509v3 No Revocation Available"
+#define NID_no_rev_avail 403
+#define OBJ_no_rev_avail OBJ_id_ce,56L
+
+#define SN_anyExtendedKeyUsage "anyExtendedKeyUsage"
+#define LN_anyExtendedKeyUsage "Any Extended Key Usage"
+#define NID_anyExtendedKeyUsage 910
+#define OBJ_anyExtendedKeyUsage OBJ_ext_key_usage,0L
+
+#define SN_netscape "Netscape"
+#define LN_netscape "Netscape Communications Corp."
+#define NID_netscape 57
+#define OBJ_netscape 2L,16L,840L,1L,113730L
+
+#define SN_netscape_cert_extension "nsCertExt"
+#define LN_netscape_cert_extension "Netscape Certificate Extension"
+#define NID_netscape_cert_extension 58
+#define OBJ_netscape_cert_extension OBJ_netscape,1L
+
+#define SN_netscape_data_type "nsDataType"
+#define LN_netscape_data_type "Netscape Data Type"
+#define NID_netscape_data_type 59
+#define OBJ_netscape_data_type OBJ_netscape,2L
+
+#define SN_netscape_cert_type "nsCertType"
+#define LN_netscape_cert_type "Netscape Cert Type"
+#define NID_netscape_cert_type 71
+#define OBJ_netscape_cert_type OBJ_netscape_cert_extension,1L
+
+#define SN_netscape_base_url "nsBaseUrl"
+#define LN_netscape_base_url "Netscape Base Url"
+#define NID_netscape_base_url 72
+#define OBJ_netscape_base_url OBJ_netscape_cert_extension,2L
+
+#define SN_netscape_revocation_url "nsRevocationUrl"
+#define LN_netscape_revocation_url "Netscape Revocation Url"
+#define NID_netscape_revocation_url 73
+#define OBJ_netscape_revocation_url OBJ_netscape_cert_extension,3L
+
+#define SN_netscape_ca_revocation_url "nsCaRevocationUrl"
+#define LN_netscape_ca_revocation_url "Netscape CA Revocation Url"
+#define NID_netscape_ca_revocation_url 74
+#define OBJ_netscape_ca_revocation_url OBJ_netscape_cert_extension,4L
+
+#define SN_netscape_renewal_url "nsRenewalUrl"
+#define LN_netscape_renewal_url "Netscape Renewal Url"
+#define NID_netscape_renewal_url 75
+#define OBJ_netscape_renewal_url OBJ_netscape_cert_extension,7L
+
+#define SN_netscape_ca_policy_url "nsCaPolicyUrl"
+#define LN_netscape_ca_policy_url "Netscape CA Policy Url"
+#define NID_netscape_ca_policy_url 76
+#define OBJ_netscape_ca_policy_url OBJ_netscape_cert_extension,8L
+
+#define SN_netscape_ssl_server_name "nsSslServerName"
+#define LN_netscape_ssl_server_name "Netscape SSL Server Name"
+#define NID_netscape_ssl_server_name 77
+#define OBJ_netscape_ssl_server_name OBJ_netscape_cert_extension,12L
+
+#define SN_netscape_comment "nsComment"
+#define LN_netscape_comment "Netscape Comment"
+#define NID_netscape_comment 78
+#define OBJ_netscape_comment OBJ_netscape_cert_extension,13L
+
+#define SN_netscape_cert_sequence "nsCertSequence"
+#define LN_netscape_cert_sequence "Netscape Certificate Sequence"
+#define NID_netscape_cert_sequence 79
+#define OBJ_netscape_cert_sequence OBJ_netscape_data_type,5L
+
+#define SN_ns_sgc "nsSGC"
+#define LN_ns_sgc "Netscape Server Gated Crypto"
+#define NID_ns_sgc 139
+#define OBJ_ns_sgc OBJ_netscape,4L,1L
+
+#define SN_org "ORG"
+#define LN_org "org"
+#define NID_org 379
+#define OBJ_org OBJ_iso,3L
+
+#define SN_dod "DOD"
+#define LN_dod "dod"
+#define NID_dod 380
+#define OBJ_dod OBJ_org,6L
+
+#define SN_iana "IANA"
+#define LN_iana "iana"
+#define NID_iana 381
+#define OBJ_iana OBJ_dod,1L
+
+#define OBJ_internet OBJ_iana
+
+#define SN_Directory "directory"
+#define LN_Directory "Directory"
+#define NID_Directory 382
+#define OBJ_Directory OBJ_internet,1L
+
+#define SN_Management "mgmt"
+#define LN_Management "Management"
+#define NID_Management 383
+#define OBJ_Management OBJ_internet,2L
+
+#define SN_Experimental "experimental"
+#define LN_Experimental "Experimental"
+#define NID_Experimental 384
+#define OBJ_Experimental OBJ_internet,3L
+
+#define SN_Private "private"
+#define LN_Private "Private"
+#define NID_Private 385
+#define OBJ_Private OBJ_internet,4L
+
+#define SN_Security "security"
+#define LN_Security "Security"
+#define NID_Security 386
+#define OBJ_Security OBJ_internet,5L
+
+#define SN_SNMPv2 "snmpv2"
+#define LN_SNMPv2 "SNMPv2"
+#define NID_SNMPv2 387
+#define OBJ_SNMPv2 OBJ_internet,6L
+
+#define LN_Mail "Mail"
+#define NID_Mail 388
+#define OBJ_Mail OBJ_internet,7L
+
+#define SN_Enterprises "enterprises"
+#define LN_Enterprises "Enterprises"
+#define NID_Enterprises 389
+#define OBJ_Enterprises OBJ_Private,1L
+
+#define SN_dcObject "dcobject"
+#define LN_dcObject "dcObject"
+#define NID_dcObject 390
+#define OBJ_dcObject OBJ_Enterprises,1466L,344L
+
+#define SN_mime_mhs "mime-mhs"
+#define LN_mime_mhs "MIME MHS"
+#define NID_mime_mhs 504
+#define OBJ_mime_mhs OBJ_Mail,1L
+
+#define SN_mime_mhs_headings "mime-mhs-headings"
+#define LN_mime_mhs_headings "mime-mhs-headings"
+#define NID_mime_mhs_headings 505
+#define OBJ_mime_mhs_headings OBJ_mime_mhs,1L
+
+#define SN_mime_mhs_bodies "mime-mhs-bodies"
+#define LN_mime_mhs_bodies "mime-mhs-bodies"
+#define NID_mime_mhs_bodies 506
+#define OBJ_mime_mhs_bodies OBJ_mime_mhs,2L
+
+#define SN_id_hex_partial_message "id-hex-partial-message"
+#define LN_id_hex_partial_message "id-hex-partial-message"
+#define NID_id_hex_partial_message 507
+#define OBJ_id_hex_partial_message OBJ_mime_mhs_headings,1L
+
+#define SN_id_hex_multipart_message "id-hex-multipart-message"
+#define LN_id_hex_multipart_message "id-hex-multipart-message"
+#define NID_id_hex_multipart_message 508
+#define OBJ_id_hex_multipart_message OBJ_mime_mhs_headings,2L
+
+#define SN_zlib_compression "ZLIB"
+#define LN_zlib_compression "zlib compression"
+#define NID_zlib_compression 125
+#define OBJ_zlib_compression OBJ_id_smime_alg,8L
+
+#define OBJ_csor 2L,16L,840L,1L,101L,3L
+
+#define OBJ_nistAlgorithms OBJ_csor,4L
+
+#define OBJ_aes OBJ_nistAlgorithms,1L
+
+#define SN_aes_128_ecb "AES-128-ECB"
+#define LN_aes_128_ecb "aes-128-ecb"
+#define NID_aes_128_ecb 418
+#define OBJ_aes_128_ecb OBJ_aes,1L
+
+#define SN_aes_128_cbc "AES-128-CBC"
+#define LN_aes_128_cbc "aes-128-cbc"
+#define NID_aes_128_cbc 419
+#define OBJ_aes_128_cbc OBJ_aes,2L
+
+#define SN_aes_128_ofb128 "AES-128-OFB"
+#define LN_aes_128_ofb128 "aes-128-ofb"
+#define NID_aes_128_ofb128 420
+#define OBJ_aes_128_ofb128 OBJ_aes,3L
+
+#define SN_aes_128_cfb128 "AES-128-CFB"
+#define LN_aes_128_cfb128 "aes-128-cfb"
+#define NID_aes_128_cfb128 421
+#define OBJ_aes_128_cfb128 OBJ_aes,4L
+
+#define SN_id_aes128_wrap "id-aes128-wrap"
+#define NID_id_aes128_wrap 788
+#define OBJ_id_aes128_wrap OBJ_aes,5L
+
+#define SN_aes_128_gcm "id-aes128-GCM"
+#define LN_aes_128_gcm "aes-128-gcm"
+#define NID_aes_128_gcm 895
+#define OBJ_aes_128_gcm OBJ_aes,6L
+
+#define SN_aes_128_ccm "id-aes128-CCM"
+#define LN_aes_128_ccm "aes-128-ccm"
+#define NID_aes_128_ccm 896
+#define OBJ_aes_128_ccm OBJ_aes,7L
+
+#define SN_id_aes128_wrap_pad "id-aes128-wrap-pad"
+#define NID_id_aes128_wrap_pad 897
+#define OBJ_id_aes128_wrap_pad OBJ_aes,8L
+
+#define SN_aes_192_ecb "AES-192-ECB"
+#define LN_aes_192_ecb "aes-192-ecb"
+#define NID_aes_192_ecb 422
+#define OBJ_aes_192_ecb OBJ_aes,21L
+
+#define SN_aes_192_cbc "AES-192-CBC"
+#define LN_aes_192_cbc "aes-192-cbc"
+#define NID_aes_192_cbc 423
+#define OBJ_aes_192_cbc OBJ_aes,22L
+
+#define SN_aes_192_ofb128 "AES-192-OFB"
+#define LN_aes_192_ofb128 "aes-192-ofb"
+#define NID_aes_192_ofb128 424
+#define OBJ_aes_192_ofb128 OBJ_aes,23L
+
+#define SN_aes_192_cfb128 "AES-192-CFB"
+#define LN_aes_192_cfb128 "aes-192-cfb"
+#define NID_aes_192_cfb128 425
+#define OBJ_aes_192_cfb128 OBJ_aes,24L
+
+#define SN_id_aes192_wrap "id-aes192-wrap"
+#define NID_id_aes192_wrap 789
+#define OBJ_id_aes192_wrap OBJ_aes,25L
+
+#define SN_aes_192_gcm "id-aes192-GCM"
+#define LN_aes_192_gcm "aes-192-gcm"
+#define NID_aes_192_gcm 898
+#define OBJ_aes_192_gcm OBJ_aes,26L
+
+#define SN_aes_192_ccm "id-aes192-CCM"
+#define LN_aes_192_ccm "aes-192-ccm"
+#define NID_aes_192_ccm 899
+#define OBJ_aes_192_ccm OBJ_aes,27L
+
+#define SN_id_aes192_wrap_pad "id-aes192-wrap-pad"
+#define NID_id_aes192_wrap_pad 900
+#define OBJ_id_aes192_wrap_pad OBJ_aes,28L
+
+#define SN_aes_256_ecb "AES-256-ECB"
+#define LN_aes_256_ecb "aes-256-ecb"
+#define NID_aes_256_ecb 426
+#define OBJ_aes_256_ecb OBJ_aes,41L
+
+#define SN_aes_256_cbc "AES-256-CBC"
+#define LN_aes_256_cbc "aes-256-cbc"
+#define NID_aes_256_cbc 427
+#define OBJ_aes_256_cbc OBJ_aes,42L
+
+#define SN_aes_256_ofb128 "AES-256-OFB"
+#define LN_aes_256_ofb128 "aes-256-ofb"
+#define NID_aes_256_ofb128 428
+#define OBJ_aes_256_ofb128 OBJ_aes,43L
+
+#define SN_aes_256_cfb128 "AES-256-CFB"
+#define LN_aes_256_cfb128 "aes-256-cfb"
+#define NID_aes_256_cfb128 429
+#define OBJ_aes_256_cfb128 OBJ_aes,44L
+
+#define SN_id_aes256_wrap "id-aes256-wrap"
+#define NID_id_aes256_wrap 790
+#define OBJ_id_aes256_wrap OBJ_aes,45L
+
+#define SN_aes_256_gcm "id-aes256-GCM"
+#define LN_aes_256_gcm "aes-256-gcm"
+#define NID_aes_256_gcm 901
+#define OBJ_aes_256_gcm OBJ_aes,46L
+
+#define SN_aes_256_ccm "id-aes256-CCM"
+#define LN_aes_256_ccm "aes-256-ccm"
+#define NID_aes_256_ccm 902
+#define OBJ_aes_256_ccm OBJ_aes,47L
+
+#define SN_id_aes256_wrap_pad "id-aes256-wrap-pad"
+#define NID_id_aes256_wrap_pad 903
+#define OBJ_id_aes256_wrap_pad OBJ_aes,48L
+
+#define SN_aes_128_xts "AES-128-XTS"
+#define LN_aes_128_xts "aes-128-xts"
+#define NID_aes_128_xts 913
+#define OBJ_aes_128_xts OBJ_ieee_siswg,0L,1L,1L
+
+#define SN_aes_256_xts "AES-256-XTS"
+#define LN_aes_256_xts "aes-256-xts"
+#define NID_aes_256_xts 914
+#define OBJ_aes_256_xts OBJ_ieee_siswg,0L,1L,2L
+
+#define SN_aes_128_cfb1 "AES-128-CFB1"
+#define LN_aes_128_cfb1 "aes-128-cfb1"
+#define NID_aes_128_cfb1 650
+
+#define SN_aes_192_cfb1 "AES-192-CFB1"
+#define LN_aes_192_cfb1 "aes-192-cfb1"
+#define NID_aes_192_cfb1 651
+
+#define SN_aes_256_cfb1 "AES-256-CFB1"
+#define LN_aes_256_cfb1 "aes-256-cfb1"
+#define NID_aes_256_cfb1 652
+
+#define SN_aes_128_cfb8 "AES-128-CFB8"
+#define LN_aes_128_cfb8 "aes-128-cfb8"
+#define NID_aes_128_cfb8 653
+
+#define SN_aes_192_cfb8 "AES-192-CFB8"
+#define LN_aes_192_cfb8 "aes-192-cfb8"
+#define NID_aes_192_cfb8 654
+
+#define SN_aes_256_cfb8 "AES-256-CFB8"
+#define LN_aes_256_cfb8 "aes-256-cfb8"
+#define NID_aes_256_cfb8 655
+
+#define SN_aes_128_ctr "AES-128-CTR"
+#define LN_aes_128_ctr "aes-128-ctr"
+#define NID_aes_128_ctr 904
+
+#define SN_aes_192_ctr "AES-192-CTR"
+#define LN_aes_192_ctr "aes-192-ctr"
+#define NID_aes_192_ctr 905
+
+#define SN_aes_256_ctr "AES-256-CTR"
+#define LN_aes_256_ctr "aes-256-ctr"
+#define NID_aes_256_ctr 906
+
+#define SN_aes_128_ocb "AES-128-OCB"
+#define LN_aes_128_ocb "aes-128-ocb"
+#define NID_aes_128_ocb 958
+
+#define SN_aes_192_ocb "AES-192-OCB"
+#define LN_aes_192_ocb "aes-192-ocb"
+#define NID_aes_192_ocb 959
+
+#define SN_aes_256_ocb "AES-256-OCB"
+#define LN_aes_256_ocb "aes-256-ocb"
+#define NID_aes_256_ocb 960
+
+#define SN_des_cfb1 "DES-CFB1"
+#define LN_des_cfb1 "des-cfb1"
+#define NID_des_cfb1 656
+
+#define SN_des_cfb8 "DES-CFB8"
+#define LN_des_cfb8 "des-cfb8"
+#define NID_des_cfb8 657
+
+#define SN_des_ede3_cfb1 "DES-EDE3-CFB1"
+#define LN_des_ede3_cfb1 "des-ede3-cfb1"
+#define NID_des_ede3_cfb1 658
+
+#define SN_des_ede3_cfb8 "DES-EDE3-CFB8"
+#define LN_des_ede3_cfb8 "des-ede3-cfb8"
+#define NID_des_ede3_cfb8 659
+
+#define OBJ_nist_hashalgs OBJ_nistAlgorithms,2L
+
+#define SN_sha256 "SHA256"
+#define LN_sha256 "sha256"
+#define NID_sha256 672
+#define OBJ_sha256 OBJ_nist_hashalgs,1L
+
+#define SN_sha384 "SHA384"
+#define LN_sha384 "sha384"
+#define NID_sha384 673
+#define OBJ_sha384 OBJ_nist_hashalgs,2L
+
+#define SN_sha512 "SHA512"
+#define LN_sha512 "sha512"
+#define NID_sha512 674
+#define OBJ_sha512 OBJ_nist_hashalgs,3L
+
+#define SN_sha224 "SHA224"
+#define LN_sha224 "sha224"
+#define NID_sha224 675
+#define OBJ_sha224 OBJ_nist_hashalgs,4L
+
+#define SN_sha512_224 "SHA512-224"
+#define LN_sha512_224 "sha512-224"
+#define NID_sha512_224 1094
+#define OBJ_sha512_224 OBJ_nist_hashalgs,5L
+
+#define SN_sha512_256 "SHA512-256"
+#define LN_sha512_256 "sha512-256"
+#define NID_sha512_256 1095
+#define OBJ_sha512_256 OBJ_nist_hashalgs,6L
+
+#define SN_sha3_224 "SHA3-224"
+#define LN_sha3_224 "sha3-224"
+#define NID_sha3_224 1096
+#define OBJ_sha3_224 OBJ_nist_hashalgs,7L
+
+#define SN_sha3_256 "SHA3-256"
+#define LN_sha3_256 "sha3-256"
+#define NID_sha3_256 1097
+#define OBJ_sha3_256 OBJ_nist_hashalgs,8L
+
+#define SN_sha3_384 "SHA3-384"
+#define LN_sha3_384 "sha3-384"
+#define NID_sha3_384 1098
+#define OBJ_sha3_384 OBJ_nist_hashalgs,9L
+
+#define SN_sha3_512 "SHA3-512"
+#define LN_sha3_512 "sha3-512"
+#define NID_sha3_512 1099
+#define OBJ_sha3_512 OBJ_nist_hashalgs,10L
+
+#define SN_shake128 "SHAKE128"
+#define LN_shake128 "shake128"
+#define NID_shake128 1100
+#define OBJ_shake128 OBJ_nist_hashalgs,11L
+
+#define SN_shake256 "SHAKE256"
+#define LN_shake256 "shake256"
+#define NID_shake256 1101
+#define OBJ_shake256 OBJ_nist_hashalgs,12L
+
+#define SN_hmac_sha3_224 "id-hmacWithSHA3-224"
+#define LN_hmac_sha3_224 "hmac-sha3-224"
+#define NID_hmac_sha3_224 1102
+#define OBJ_hmac_sha3_224 OBJ_nist_hashalgs,13L
+
+#define SN_hmac_sha3_256 "id-hmacWithSHA3-256"
+#define LN_hmac_sha3_256 "hmac-sha3-256"
+#define NID_hmac_sha3_256 1103
+#define OBJ_hmac_sha3_256 OBJ_nist_hashalgs,14L
+
+#define SN_hmac_sha3_384 "id-hmacWithSHA3-384"
+#define LN_hmac_sha3_384 "hmac-sha3-384"
+#define NID_hmac_sha3_384 1104
+#define OBJ_hmac_sha3_384 OBJ_nist_hashalgs,15L
+
+#define SN_hmac_sha3_512 "id-hmacWithSHA3-512"
+#define LN_hmac_sha3_512 "hmac-sha3-512"
+#define NID_hmac_sha3_512 1105
+#define OBJ_hmac_sha3_512 OBJ_nist_hashalgs,16L
+
+#define SN_kmac128 "KMAC128"
+#define LN_kmac128 "kmac128"
+#define NID_kmac128 1196
+#define OBJ_kmac128 OBJ_nist_hashalgs,19L
+
+#define SN_kmac256 "KMAC256"
+#define LN_kmac256 "kmac256"
+#define NID_kmac256 1197
+#define OBJ_kmac256 OBJ_nist_hashalgs,20L
+
+#define OBJ_dsa_with_sha2 OBJ_nistAlgorithms,3L
+
+#define SN_dsa_with_SHA224 "dsa_with_SHA224"
+#define NID_dsa_with_SHA224 802
+#define OBJ_dsa_with_SHA224 OBJ_dsa_with_sha2,1L
+
+#define SN_dsa_with_SHA256 "dsa_with_SHA256"
+#define NID_dsa_with_SHA256 803
+#define OBJ_dsa_with_SHA256 OBJ_dsa_with_sha2,2L
+
+#define OBJ_sigAlgs OBJ_nistAlgorithms,3L
+
+#define SN_dsa_with_SHA384 "id-dsa-with-sha384"
+#define LN_dsa_with_SHA384 "dsa_with_SHA384"
+#define NID_dsa_with_SHA384 1106
+#define OBJ_dsa_with_SHA384 OBJ_sigAlgs,3L
+
+#define SN_dsa_with_SHA512 "id-dsa-with-sha512"
+#define LN_dsa_with_SHA512 "dsa_with_SHA512"
+#define NID_dsa_with_SHA512 1107
+#define OBJ_dsa_with_SHA512 OBJ_sigAlgs,4L
+
+#define SN_dsa_with_SHA3_224 "id-dsa-with-sha3-224"
+#define LN_dsa_with_SHA3_224 "dsa_with_SHA3-224"
+#define NID_dsa_with_SHA3_224 1108
+#define OBJ_dsa_with_SHA3_224 OBJ_sigAlgs,5L
+
+#define SN_dsa_with_SHA3_256 "id-dsa-with-sha3-256"
+#define LN_dsa_with_SHA3_256 "dsa_with_SHA3-256"
+#define NID_dsa_with_SHA3_256 1109
+#define OBJ_dsa_with_SHA3_256 OBJ_sigAlgs,6L
+
+#define SN_dsa_with_SHA3_384 "id-dsa-with-sha3-384"
+#define LN_dsa_with_SHA3_384 "dsa_with_SHA3-384"
+#define NID_dsa_with_SHA3_384 1110
+#define OBJ_dsa_with_SHA3_384 OBJ_sigAlgs,7L
+
+#define SN_dsa_with_SHA3_512 "id-dsa-with-sha3-512"
+#define LN_dsa_with_SHA3_512 "dsa_with_SHA3-512"
+#define NID_dsa_with_SHA3_512 1111
+#define OBJ_dsa_with_SHA3_512 OBJ_sigAlgs,8L
+
+#define SN_ecdsa_with_SHA3_224 "id-ecdsa-with-sha3-224"
+#define LN_ecdsa_with_SHA3_224 "ecdsa_with_SHA3-224"
+#define NID_ecdsa_with_SHA3_224 1112
+#define OBJ_ecdsa_with_SHA3_224 OBJ_sigAlgs,9L
+
+#define SN_ecdsa_with_SHA3_256 "id-ecdsa-with-sha3-256"
+#define LN_ecdsa_with_SHA3_256 "ecdsa_with_SHA3-256"
+#define NID_ecdsa_with_SHA3_256 1113
+#define OBJ_ecdsa_with_SHA3_256 OBJ_sigAlgs,10L
+
+#define SN_ecdsa_with_SHA3_384 "id-ecdsa-with-sha3-384"
+#define LN_ecdsa_with_SHA3_384 "ecdsa_with_SHA3-384"
+#define NID_ecdsa_with_SHA3_384 1114
+#define OBJ_ecdsa_with_SHA3_384 OBJ_sigAlgs,11L
+
+#define SN_ecdsa_with_SHA3_512 "id-ecdsa-with-sha3-512"
+#define LN_ecdsa_with_SHA3_512 "ecdsa_with_SHA3-512"
+#define NID_ecdsa_with_SHA3_512 1115
+#define OBJ_ecdsa_with_SHA3_512 OBJ_sigAlgs,12L
+
+#define SN_RSA_SHA3_224 "id-rsassa-pkcs1-v1_5-with-sha3-224"
+#define LN_RSA_SHA3_224 "RSA-SHA3-224"
+#define NID_RSA_SHA3_224 1116
+#define OBJ_RSA_SHA3_224 OBJ_sigAlgs,13L
+
+#define SN_RSA_SHA3_256 "id-rsassa-pkcs1-v1_5-with-sha3-256"
+#define LN_RSA_SHA3_256 "RSA-SHA3-256"
+#define NID_RSA_SHA3_256 1117
+#define OBJ_RSA_SHA3_256 OBJ_sigAlgs,14L
+
+#define SN_RSA_SHA3_384 "id-rsassa-pkcs1-v1_5-with-sha3-384"
+#define LN_RSA_SHA3_384 "RSA-SHA3-384"
+#define NID_RSA_SHA3_384 1118
+#define OBJ_RSA_SHA3_384 OBJ_sigAlgs,15L
+
+#define SN_RSA_SHA3_512 "id-rsassa-pkcs1-v1_5-with-sha3-512"
+#define LN_RSA_SHA3_512 "RSA-SHA3-512"
+#define NID_RSA_SHA3_512 1119
+#define OBJ_RSA_SHA3_512 OBJ_sigAlgs,16L
+
+#define SN_hold_instruction_code "holdInstructionCode"
+#define LN_hold_instruction_code "Hold Instruction Code"
+#define NID_hold_instruction_code 430
+#define OBJ_hold_instruction_code OBJ_id_ce,23L
+
+#define OBJ_holdInstruction OBJ_X9_57,2L
+
+#define SN_hold_instruction_none "holdInstructionNone"
+#define LN_hold_instruction_none "Hold Instruction None"
+#define NID_hold_instruction_none 431
+#define OBJ_hold_instruction_none OBJ_holdInstruction,1L
+
+#define SN_hold_instruction_call_issuer "holdInstructionCallIssuer"
+#define LN_hold_instruction_call_issuer "Hold Instruction Call Issuer"
+#define NID_hold_instruction_call_issuer 432
+#define OBJ_hold_instruction_call_issuer OBJ_holdInstruction,2L
+
+#define SN_hold_instruction_reject "holdInstructionReject"
+#define LN_hold_instruction_reject "Hold Instruction Reject"
+#define NID_hold_instruction_reject 433
+#define OBJ_hold_instruction_reject OBJ_holdInstruction,3L
+
+#define SN_data "data"
+#define NID_data 434
+#define OBJ_data OBJ_itu_t,9L
+
+#define SN_pss "pss"
+#define NID_pss 435
+#define OBJ_pss OBJ_data,2342L
+
+#define SN_ucl "ucl"
+#define NID_ucl 436
+#define OBJ_ucl OBJ_pss,19200300L
+
+#define SN_pilot "pilot"
+#define NID_pilot 437
+#define OBJ_pilot OBJ_ucl,100L
+
+#define LN_pilotAttributeType "pilotAttributeType"
+#define NID_pilotAttributeType 438
+#define OBJ_pilotAttributeType OBJ_pilot,1L
+
+#define LN_pilotAttributeSyntax "pilotAttributeSyntax"
+#define NID_pilotAttributeSyntax 439
+#define OBJ_pilotAttributeSyntax OBJ_pilot,3L
+
+#define LN_pilotObjectClass "pilotObjectClass"
+#define NID_pilotObjectClass 440
+#define OBJ_pilotObjectClass OBJ_pilot,4L
+
+#define LN_pilotGroups "pilotGroups"
+#define NID_pilotGroups 441
+#define OBJ_pilotGroups OBJ_pilot,10L
+
+#define LN_iA5StringSyntax "iA5StringSyntax"
+#define NID_iA5StringSyntax 442
+#define OBJ_iA5StringSyntax OBJ_pilotAttributeSyntax,4L
+
+#define LN_caseIgnoreIA5StringSyntax "caseIgnoreIA5StringSyntax"
+#define NID_caseIgnoreIA5StringSyntax 443
+#define OBJ_caseIgnoreIA5StringSyntax OBJ_pilotAttributeSyntax,5L
+
+#define LN_pilotObject "pilotObject"
+#define NID_pilotObject 444
+#define OBJ_pilotObject OBJ_pilotObjectClass,3L
+
+#define LN_pilotPerson "pilotPerson"
+#define NID_pilotPerson 445
+#define OBJ_pilotPerson OBJ_pilotObjectClass,4L
+
+#define SN_account "account"
+#define NID_account 446
+#define OBJ_account OBJ_pilotObjectClass,5L
+
+#define SN_document "document"
+#define NID_document 447
+#define OBJ_document OBJ_pilotObjectClass,6L
+
+#define SN_room "room"
+#define NID_room 448
+#define OBJ_room OBJ_pilotObjectClass,7L
+
+#define LN_documentSeries "documentSeries"
+#define NID_documentSeries 449
+#define OBJ_documentSeries OBJ_pilotObjectClass,9L
+
+#define SN_Domain "domain"
+#define LN_Domain "Domain"
+#define NID_Domain 392
+#define OBJ_Domain OBJ_pilotObjectClass,13L
+
+#define LN_rFC822localPart "rFC822localPart"
+#define NID_rFC822localPart 450
+#define OBJ_rFC822localPart OBJ_pilotObjectClass,14L
+
+#define LN_dNSDomain "dNSDomain"
+#define NID_dNSDomain 451
+#define OBJ_dNSDomain OBJ_pilotObjectClass,15L
+
+#define LN_domainRelatedObject "domainRelatedObject"
+#define NID_domainRelatedObject 452
+#define OBJ_domainRelatedObject OBJ_pilotObjectClass,17L
+
+#define LN_friendlyCountry "friendlyCountry"
+#define NID_friendlyCountry 453
+#define OBJ_friendlyCountry OBJ_pilotObjectClass,18L
+
+#define LN_simpleSecurityObject "simpleSecurityObject"
+#define NID_simpleSecurityObject 454
+#define OBJ_simpleSecurityObject OBJ_pilotObjectClass,19L
+
+#define LN_pilotOrganization "pilotOrganization"
+#define NID_pilotOrganization 455
+#define OBJ_pilotOrganization OBJ_pilotObjectClass,20L
+
+#define LN_pilotDSA "pilotDSA"
+#define NID_pilotDSA 456
+#define OBJ_pilotDSA OBJ_pilotObjectClass,21L
+
+#define LN_qualityLabelledData "qualityLabelledData"
+#define NID_qualityLabelledData 457
+#define OBJ_qualityLabelledData OBJ_pilotObjectClass,22L
+
+#define SN_userId "UID"
+#define LN_userId "userId"
+#define NID_userId 458
+#define OBJ_userId OBJ_pilotAttributeType,1L
+
+#define LN_textEncodedORAddress "textEncodedORAddress"
+#define NID_textEncodedORAddress 459
+#define OBJ_textEncodedORAddress OBJ_pilotAttributeType,2L
+
+#define SN_rfc822Mailbox "mail"
+#define LN_rfc822Mailbox "rfc822Mailbox"
+#define NID_rfc822Mailbox 460
+#define OBJ_rfc822Mailbox OBJ_pilotAttributeType,3L
+
+#define SN_info "info"
+#define NID_info 461
+#define OBJ_info OBJ_pilotAttributeType,4L
+
+#define LN_favouriteDrink "favouriteDrink"
+#define NID_favouriteDrink 462
+#define OBJ_favouriteDrink OBJ_pilotAttributeType,5L
+
+#define LN_roomNumber "roomNumber"
+#define NID_roomNumber 463
+#define OBJ_roomNumber OBJ_pilotAttributeType,6L
+
+#define SN_photo "photo"
+#define NID_photo 464
+#define OBJ_photo OBJ_pilotAttributeType,7L
+
+#define LN_userClass "userClass"
+#define NID_userClass 465
+#define OBJ_userClass OBJ_pilotAttributeType,8L
+
+#define SN_host "host"
+#define NID_host 466
+#define OBJ_host OBJ_pilotAttributeType,9L
+
+#define SN_manager "manager"
+#define NID_manager 467
+#define OBJ_manager OBJ_pilotAttributeType,10L
+
+#define LN_documentIdentifier "documentIdentifier"
+#define NID_documentIdentifier 468
+#define OBJ_documentIdentifier OBJ_pilotAttributeType,11L
+
+#define LN_documentTitle "documentTitle"
+#define NID_documentTitle 469
+#define OBJ_documentTitle OBJ_pilotAttributeType,12L
+
+#define LN_documentVersion "documentVersion"
+#define NID_documentVersion 470
+#define OBJ_documentVersion OBJ_pilotAttributeType,13L
+
+#define LN_documentAuthor "documentAuthor"
+#define NID_documentAuthor 471
+#define OBJ_documentAuthor OBJ_pilotAttributeType,14L
+
+#define LN_documentLocation "documentLocation"
+#define NID_documentLocation 472
+#define OBJ_documentLocation OBJ_pilotAttributeType,15L
+
+#define LN_homeTelephoneNumber "homeTelephoneNumber"
+#define NID_homeTelephoneNumber 473
+#define OBJ_homeTelephoneNumber OBJ_pilotAttributeType,20L
+
+#define SN_secretary "secretary"
+#define NID_secretary 474
+#define OBJ_secretary OBJ_pilotAttributeType,21L
+
+#define LN_otherMailbox "otherMailbox"
+#define NID_otherMailbox 475
+#define OBJ_otherMailbox OBJ_pilotAttributeType,22L
+
+#define LN_lastModifiedTime "lastModifiedTime"
+#define NID_lastModifiedTime 476
+#define OBJ_lastModifiedTime OBJ_pilotAttributeType,23L
+
+#define LN_lastModifiedBy "lastModifiedBy"
+#define NID_lastModifiedBy 477
+#define OBJ_lastModifiedBy OBJ_pilotAttributeType,24L
+
+#define SN_domainComponent "DC"
+#define LN_domainComponent "domainComponent"
+#define NID_domainComponent 391
+#define OBJ_domainComponent OBJ_pilotAttributeType,25L
+
+#define LN_aRecord "aRecord"
+#define NID_aRecord 478
+#define OBJ_aRecord OBJ_pilotAttributeType,26L
+
+#define LN_pilotAttributeType27 "pilotAttributeType27"
+#define NID_pilotAttributeType27 479
+#define OBJ_pilotAttributeType27 OBJ_pilotAttributeType,27L
+
+#define LN_mXRecord "mXRecord"
+#define NID_mXRecord 480
+#define OBJ_mXRecord OBJ_pilotAttributeType,28L
+
+#define LN_nSRecord "nSRecord"
+#define NID_nSRecord 481
+#define OBJ_nSRecord OBJ_pilotAttributeType,29L
+
+#define LN_sOARecord "sOARecord"
+#define NID_sOARecord 482
+#define OBJ_sOARecord OBJ_pilotAttributeType,30L
+
+#define LN_cNAMERecord "cNAMERecord"
+#define NID_cNAMERecord 483
+#define OBJ_cNAMERecord OBJ_pilotAttributeType,31L
+
+#define LN_associatedDomain "associatedDomain"
+#define NID_associatedDomain 484
+#define OBJ_associatedDomain OBJ_pilotAttributeType,37L
+
+#define LN_associatedName "associatedName"
+#define NID_associatedName 485
+#define OBJ_associatedName OBJ_pilotAttributeType,38L
+
+#define LN_homePostalAddress "homePostalAddress"
+#define NID_homePostalAddress 486
+#define OBJ_homePostalAddress OBJ_pilotAttributeType,39L
+
+#define LN_personalTitle "personalTitle"
+#define NID_personalTitle 487
+#define OBJ_personalTitle OBJ_pilotAttributeType,40L
+
+#define LN_mobileTelephoneNumber "mobileTelephoneNumber"
+#define NID_mobileTelephoneNumber 488
+#define OBJ_mobileTelephoneNumber OBJ_pilotAttributeType,41L
+
+#define LN_pagerTelephoneNumber "pagerTelephoneNumber"
+#define NID_pagerTelephoneNumber 489
+#define OBJ_pagerTelephoneNumber OBJ_pilotAttributeType,42L
+
+#define LN_friendlyCountryName "friendlyCountryName"
+#define NID_friendlyCountryName 490
+#define OBJ_friendlyCountryName OBJ_pilotAttributeType,43L
+
+#define SN_uniqueIdentifier "uid"
+#define LN_uniqueIdentifier "uniqueIdentifier"
+#define NID_uniqueIdentifier 102
+#define OBJ_uniqueIdentifier OBJ_pilotAttributeType,44L
+
+#define LN_organizationalStatus "organizationalStatus"
+#define NID_organizationalStatus 491
+#define OBJ_organizationalStatus OBJ_pilotAttributeType,45L
+
+#define LN_janetMailbox "janetMailbox"
+#define NID_janetMailbox 492
+#define OBJ_janetMailbox OBJ_pilotAttributeType,46L
+
+#define LN_mailPreferenceOption "mailPreferenceOption"
+#define NID_mailPreferenceOption 493
+#define OBJ_mailPreferenceOption OBJ_pilotAttributeType,47L
+
+#define LN_buildingName "buildingName"
+#define NID_buildingName 494
+#define OBJ_buildingName OBJ_pilotAttributeType,48L
+
+#define LN_dSAQuality "dSAQuality"
+#define NID_dSAQuality 495
+#define OBJ_dSAQuality OBJ_pilotAttributeType,49L
+
+#define LN_singleLevelQuality "singleLevelQuality"
+#define NID_singleLevelQuality 496
+#define OBJ_singleLevelQuality OBJ_pilotAttributeType,50L
+
+#define LN_subtreeMinimumQuality "subtreeMinimumQuality"
+#define NID_subtreeMinimumQuality 497
+#define OBJ_subtreeMinimumQuality OBJ_pilotAttributeType,51L
+
+#define LN_subtreeMaximumQuality "subtreeMaximumQuality"
+#define NID_subtreeMaximumQuality 498
+#define OBJ_subtreeMaximumQuality OBJ_pilotAttributeType,52L
+
+#define LN_personalSignature "personalSignature"
+#define NID_personalSignature 499
+#define OBJ_personalSignature OBJ_pilotAttributeType,53L
+
+#define LN_dITRedirect "dITRedirect"
+#define NID_dITRedirect 500
+#define OBJ_dITRedirect OBJ_pilotAttributeType,54L
+
+#define SN_audio "audio"
+#define NID_audio 501
+#define OBJ_audio OBJ_pilotAttributeType,55L
+
+#define LN_documentPublisher "documentPublisher"
+#define NID_documentPublisher 502
+#define OBJ_documentPublisher OBJ_pilotAttributeType,56L
+
+#define SN_id_set "id-set"
+#define LN_id_set "Secure Electronic Transactions"
+#define NID_id_set 512
+#define OBJ_id_set OBJ_international_organizations,42L
+
+#define SN_set_ctype "set-ctype"
+#define LN_set_ctype "content types"
+#define NID_set_ctype 513
+#define OBJ_set_ctype OBJ_id_set,0L
+
+#define SN_set_msgExt "set-msgExt"
+#define LN_set_msgExt "message extensions"
+#define NID_set_msgExt 514
+#define OBJ_set_msgExt OBJ_id_set,1L
+
+#define SN_set_attr "set-attr"
+#define NID_set_attr 515
+#define OBJ_set_attr OBJ_id_set,3L
+
+#define SN_set_policy "set-policy"
+#define NID_set_policy 516
+#define OBJ_set_policy OBJ_id_set,5L
+
+#define SN_set_certExt "set-certExt"
+#define LN_set_certExt "certificate extensions"
+#define NID_set_certExt 517
+#define OBJ_set_certExt OBJ_id_set,7L
+
+#define SN_set_brand "set-brand"
+#define NID_set_brand 518
+#define OBJ_set_brand OBJ_id_set,8L
+
+#define SN_setct_PANData "setct-PANData"
+#define NID_setct_PANData 519
+#define OBJ_setct_PANData OBJ_set_ctype,0L
+
+#define SN_setct_PANToken "setct-PANToken"
+#define NID_setct_PANToken 520
+#define OBJ_setct_PANToken OBJ_set_ctype,1L
+
+#define SN_setct_PANOnly "setct-PANOnly"
+#define NID_setct_PANOnly 521
+#define OBJ_setct_PANOnly OBJ_set_ctype,2L
+
+#define SN_setct_OIData "setct-OIData"
+#define NID_setct_OIData 522
+#define OBJ_setct_OIData OBJ_set_ctype,3L
+
+#define SN_setct_PI "setct-PI"
+#define NID_setct_PI 523
+#define OBJ_setct_PI OBJ_set_ctype,4L
+
+#define SN_setct_PIData "setct-PIData"
+#define NID_setct_PIData 524
+#define OBJ_setct_PIData OBJ_set_ctype,5L
+
+#define SN_setct_PIDataUnsigned "setct-PIDataUnsigned"
+#define NID_setct_PIDataUnsigned 525
+#define OBJ_setct_PIDataUnsigned OBJ_set_ctype,6L
+
+#define SN_setct_HODInput "setct-HODInput"
+#define NID_setct_HODInput 526
+#define OBJ_setct_HODInput OBJ_set_ctype,7L
+
+#define SN_setct_AuthResBaggage "setct-AuthResBaggage"
+#define NID_setct_AuthResBaggage 527
+#define OBJ_setct_AuthResBaggage OBJ_set_ctype,8L
+
+#define SN_setct_AuthRevReqBaggage "setct-AuthRevReqBaggage"
+#define NID_setct_AuthRevReqBaggage 528
+#define OBJ_setct_AuthRevReqBaggage OBJ_set_ctype,9L
+
+#define SN_setct_AuthRevResBaggage "setct-AuthRevResBaggage"
+#define NID_setct_AuthRevResBaggage 529
+#define OBJ_setct_AuthRevResBaggage OBJ_set_ctype,10L
+
+#define SN_setct_CapTokenSeq "setct-CapTokenSeq"
+#define NID_setct_CapTokenSeq 530
+#define OBJ_setct_CapTokenSeq OBJ_set_ctype,11L
+
+#define SN_setct_PInitResData "setct-PInitResData"
+#define NID_setct_PInitResData 531
+#define OBJ_setct_PInitResData OBJ_set_ctype,12L
+
+#define SN_setct_PI_TBS "setct-PI-TBS"
+#define NID_setct_PI_TBS 532
+#define OBJ_setct_PI_TBS OBJ_set_ctype,13L
+
+#define SN_setct_PResData "setct-PResData"
+#define NID_setct_PResData 533
+#define OBJ_setct_PResData OBJ_set_ctype,14L
+
+#define SN_setct_AuthReqTBS "setct-AuthReqTBS"
+#define NID_setct_AuthReqTBS 534
+#define OBJ_setct_AuthReqTBS OBJ_set_ctype,16L
+
+#define SN_setct_AuthResTBS "setct-AuthResTBS"
+#define NID_setct_AuthResTBS 535
+#define OBJ_setct_AuthResTBS OBJ_set_ctype,17L
+
+#define SN_setct_AuthResTBSX "setct-AuthResTBSX"
+#define NID_setct_AuthResTBSX 536
+#define OBJ_setct_AuthResTBSX OBJ_set_ctype,18L
+
+#define SN_setct_AuthTokenTBS "setct-AuthTokenTBS"
+#define NID_setct_AuthTokenTBS 537
+#define OBJ_setct_AuthTokenTBS OBJ_set_ctype,19L
+
+#define SN_setct_CapTokenData "setct-CapTokenData"
+#define NID_setct_CapTokenData 538
+#define OBJ_setct_CapTokenData OBJ_set_ctype,20L
+
+#define SN_setct_CapTokenTBS "setct-CapTokenTBS"
+#define NID_setct_CapTokenTBS 539
+#define OBJ_setct_CapTokenTBS OBJ_set_ctype,21L
+
+#define SN_setct_AcqCardCodeMsg "setct-AcqCardCodeMsg"
+#define NID_setct_AcqCardCodeMsg 540
+#define OBJ_setct_AcqCardCodeMsg OBJ_set_ctype,22L
+
+#define SN_setct_AuthRevReqTBS "setct-AuthRevReqTBS"
+#define NID_setct_AuthRevReqTBS 541
+#define OBJ_setct_AuthRevReqTBS OBJ_set_ctype,23L
+
+#define SN_setct_AuthRevResData "setct-AuthRevResData"
+#define NID_setct_AuthRevResData 542
+#define OBJ_setct_AuthRevResData OBJ_set_ctype,24L
+
+#define SN_setct_AuthRevResTBS "setct-AuthRevResTBS"
+#define NID_setct_AuthRevResTBS 543
+#define OBJ_setct_AuthRevResTBS OBJ_set_ctype,25L
+
+#define SN_setct_CapReqTBS "setct-CapReqTBS"
+#define NID_setct_CapReqTBS 544
+#define OBJ_setct_CapReqTBS OBJ_set_ctype,26L
+
+#define SN_setct_CapReqTBSX "setct-CapReqTBSX"
+#define NID_setct_CapReqTBSX 545
+#define OBJ_setct_CapReqTBSX OBJ_set_ctype,27L
+
+#define SN_setct_CapResData "setct-CapResData"
+#define NID_setct_CapResData 546
+#define OBJ_setct_CapResData OBJ_set_ctype,28L
+
+#define SN_setct_CapRevReqTBS "setct-CapRevReqTBS"
+#define NID_setct_CapRevReqTBS 547
+#define OBJ_setct_CapRevReqTBS OBJ_set_ctype,29L
+
+#define SN_setct_CapRevReqTBSX "setct-CapRevReqTBSX"
+#define NID_setct_CapRevReqTBSX 548
+#define OBJ_setct_CapRevReqTBSX OBJ_set_ctype,30L
+
+#define SN_setct_CapRevResData "setct-CapRevResData"
+#define NID_setct_CapRevResData 549
+#define OBJ_setct_CapRevResData OBJ_set_ctype,31L
+
+#define SN_setct_CredReqTBS "setct-CredReqTBS"
+#define NID_setct_CredReqTBS 550
+#define OBJ_setct_CredReqTBS OBJ_set_ctype,32L
+
+#define SN_setct_CredReqTBSX "setct-CredReqTBSX"
+#define NID_setct_CredReqTBSX 551
+#define OBJ_setct_CredReqTBSX OBJ_set_ctype,33L
+
+#define SN_setct_CredResData "setct-CredResData"
+#define NID_setct_CredResData 552
+#define OBJ_setct_CredResData OBJ_set_ctype,34L
+
+#define SN_setct_CredRevReqTBS "setct-CredRevReqTBS"
+#define NID_setct_CredRevReqTBS 553
+#define OBJ_setct_CredRevReqTBS OBJ_set_ctype,35L
+
+#define SN_setct_CredRevReqTBSX "setct-CredRevReqTBSX"
+#define NID_setct_CredRevReqTBSX 554
+#define OBJ_setct_CredRevReqTBSX OBJ_set_ctype,36L
+
+#define SN_setct_CredRevResData "setct-CredRevResData"
+#define NID_setct_CredRevResData 555
+#define OBJ_setct_CredRevResData OBJ_set_ctype,37L
+
+#define SN_setct_PCertReqData "setct-PCertReqData"
+#define NID_setct_PCertReqData 556
+#define OBJ_setct_PCertReqData OBJ_set_ctype,38L
+
+#define SN_setct_PCertResTBS "setct-PCertResTBS"
+#define NID_setct_PCertResTBS 557
+#define OBJ_setct_PCertResTBS OBJ_set_ctype,39L
+
+#define SN_setct_BatchAdminReqData "setct-BatchAdminReqData"
+#define NID_setct_BatchAdminReqData 558
+#define OBJ_setct_BatchAdminReqData OBJ_set_ctype,40L
+
+#define SN_setct_BatchAdminResData "setct-BatchAdminResData"
+#define NID_setct_BatchAdminResData 559
+#define OBJ_setct_BatchAdminResData OBJ_set_ctype,41L
+
+#define SN_setct_CardCInitResTBS "setct-CardCInitResTBS"
+#define NID_setct_CardCInitResTBS 560
+#define OBJ_setct_CardCInitResTBS OBJ_set_ctype,42L
+
+#define SN_setct_MeAqCInitResTBS "setct-MeAqCInitResTBS"
+#define NID_setct_MeAqCInitResTBS 561
+#define OBJ_setct_MeAqCInitResTBS OBJ_set_ctype,43L
+
+#define SN_setct_RegFormResTBS "setct-RegFormResTBS"
+#define NID_setct_RegFormResTBS 562
+#define OBJ_setct_RegFormResTBS OBJ_set_ctype,44L
+
+#define SN_setct_CertReqData "setct-CertReqData"
+#define NID_setct_CertReqData 563
+#define OBJ_setct_CertReqData OBJ_set_ctype,45L
+
+#define SN_setct_CertReqTBS "setct-CertReqTBS"
+#define NID_setct_CertReqTBS 564
+#define OBJ_setct_CertReqTBS OBJ_set_ctype,46L
+
+#define SN_setct_CertResData "setct-CertResData"
+#define NID_setct_CertResData 565
+#define OBJ_setct_CertResData OBJ_set_ctype,47L
+
+#define SN_setct_CertInqReqTBS "setct-CertInqReqTBS"
+#define NID_setct_CertInqReqTBS 566
+#define OBJ_setct_CertInqReqTBS OBJ_set_ctype,48L
+
+#define SN_setct_ErrorTBS "setct-ErrorTBS"
+#define NID_setct_ErrorTBS 567
+#define OBJ_setct_ErrorTBS OBJ_set_ctype,49L
+
+#define SN_setct_PIDualSignedTBE "setct-PIDualSignedTBE"
+#define NID_setct_PIDualSignedTBE 568
+#define OBJ_setct_PIDualSignedTBE OBJ_set_ctype,50L
+
+#define SN_setct_PIUnsignedTBE "setct-PIUnsignedTBE"
+#define NID_setct_PIUnsignedTBE 569
+#define OBJ_setct_PIUnsignedTBE OBJ_set_ctype,51L
+
+#define SN_setct_AuthReqTBE "setct-AuthReqTBE"
+#define NID_setct_AuthReqTBE 570
+#define OBJ_setct_AuthReqTBE OBJ_set_ctype,52L
+
+#define SN_setct_AuthResTBE "setct-AuthResTBE"
+#define NID_setct_AuthResTBE 571
+#define OBJ_setct_AuthResTBE OBJ_set_ctype,53L
+
+#define SN_setct_AuthResTBEX "setct-AuthResTBEX"
+#define NID_setct_AuthResTBEX 572
+#define OBJ_setct_AuthResTBEX OBJ_set_ctype,54L
+
+#define SN_setct_AuthTokenTBE "setct-AuthTokenTBE"
+#define NID_setct_AuthTokenTBE 573
+#define OBJ_setct_AuthTokenTBE OBJ_set_ctype,55L
+
+#define SN_setct_CapTokenTBE "setct-CapTokenTBE"
+#define NID_setct_CapTokenTBE 574
+#define OBJ_setct_CapTokenTBE OBJ_set_ctype,56L
+
+#define SN_setct_CapTokenTBEX "setct-CapTokenTBEX"
+#define NID_setct_CapTokenTBEX 575
+#define OBJ_setct_CapTokenTBEX OBJ_set_ctype,57L
+
+#define SN_setct_AcqCardCodeMsgTBE "setct-AcqCardCodeMsgTBE"
+#define NID_setct_AcqCardCodeMsgTBE 576
+#define OBJ_setct_AcqCardCodeMsgTBE OBJ_set_ctype,58L
+
+#define SN_setct_AuthRevReqTBE "setct-AuthRevReqTBE"
+#define NID_setct_AuthRevReqTBE 577
+#define OBJ_setct_AuthRevReqTBE OBJ_set_ctype,59L
+
+#define SN_setct_AuthRevResTBE "setct-AuthRevResTBE"
+#define NID_setct_AuthRevResTBE 578
+#define OBJ_setct_AuthRevResTBE OBJ_set_ctype,60L
+
+#define SN_setct_AuthRevResTBEB "setct-AuthRevResTBEB"
+#define NID_setct_AuthRevResTBEB 579
+#define OBJ_setct_AuthRevResTBEB OBJ_set_ctype,61L
+
+#define SN_setct_CapReqTBE "setct-CapReqTBE"
+#define NID_setct_CapReqTBE 580
+#define OBJ_setct_CapReqTBE OBJ_set_ctype,62L
+
+#define SN_setct_CapReqTBEX "setct-CapReqTBEX"
+#define NID_setct_CapReqTBEX 581
+#define OBJ_setct_CapReqTBEX OBJ_set_ctype,63L
+
+#define SN_setct_CapResTBE "setct-CapResTBE"
+#define NID_setct_CapResTBE 582
+#define OBJ_setct_CapResTBE OBJ_set_ctype,64L
+
+#define SN_setct_CapRevReqTBE "setct-CapRevReqTBE"
+#define NID_setct_CapRevReqTBE 583
+#define OBJ_setct_CapRevReqTBE OBJ_set_ctype,65L
+
+#define SN_setct_CapRevReqTBEX "setct-CapRevReqTBEX"
+#define NID_setct_CapRevReqTBEX 584
+#define OBJ_setct_CapRevReqTBEX OBJ_set_ctype,66L
+
+#define SN_setct_CapRevResTBE "setct-CapRevResTBE"
+#define NID_setct_CapRevResTBE 585
+#define OBJ_setct_CapRevResTBE OBJ_set_ctype,67L
+
+#define SN_setct_CredReqTBE "setct-CredReqTBE"
+#define NID_setct_CredReqTBE 586
+#define OBJ_setct_CredReqTBE OBJ_set_ctype,68L
+
+#define SN_setct_CredReqTBEX "setct-CredReqTBEX"
+#define NID_setct_CredReqTBEX 587
+#define OBJ_setct_CredReqTBEX OBJ_set_ctype,69L
+
+#define SN_setct_CredResTBE "setct-CredResTBE"
+#define NID_setct_CredResTBE 588
+#define OBJ_setct_CredResTBE OBJ_set_ctype,70L
+
+#define SN_setct_CredRevReqTBE "setct-CredRevReqTBE"
+#define NID_setct_CredRevReqTBE 589
+#define OBJ_setct_CredRevReqTBE OBJ_set_ctype,71L
+
+#define SN_setct_CredRevReqTBEX "setct-CredRevReqTBEX"
+#define NID_setct_CredRevReqTBEX 590
+#define OBJ_setct_CredRevReqTBEX OBJ_set_ctype,72L
+
+#define SN_setct_CredRevResTBE "setct-CredRevResTBE"
+#define NID_setct_CredRevResTBE 591
+#define OBJ_setct_CredRevResTBE OBJ_set_ctype,73L
+
+#define SN_setct_BatchAdminReqTBE "setct-BatchAdminReqTBE"
+#define NID_setct_BatchAdminReqTBE 592
+#define OBJ_setct_BatchAdminReqTBE OBJ_set_ctype,74L
+
+#define SN_setct_BatchAdminResTBE "setct-BatchAdminResTBE"
+#define NID_setct_BatchAdminResTBE 593
+#define OBJ_setct_BatchAdminResTBE OBJ_set_ctype,75L
+
+#define SN_setct_RegFormReqTBE "setct-RegFormReqTBE"
+#define NID_setct_RegFormReqTBE 594
+#define OBJ_setct_RegFormReqTBE OBJ_set_ctype,76L
+
+#define SN_setct_CertReqTBE "setct-CertReqTBE"
+#define NID_setct_CertReqTBE 595
+#define OBJ_setct_CertReqTBE OBJ_set_ctype,77L
+
+#define SN_setct_CertReqTBEX "setct-CertReqTBEX"
+#define NID_setct_CertReqTBEX 596
+#define OBJ_setct_CertReqTBEX OBJ_set_ctype,78L
+
+#define SN_setct_CertResTBE "setct-CertResTBE"
+#define NID_setct_CertResTBE 597
+#define OBJ_setct_CertResTBE OBJ_set_ctype,79L
+
+#define SN_setct_CRLNotificationTBS "setct-CRLNotificationTBS"
+#define NID_setct_CRLNotificationTBS 598
+#define OBJ_setct_CRLNotificationTBS OBJ_set_ctype,80L
+
+#define SN_setct_CRLNotificationResTBS "setct-CRLNotificationResTBS"
+#define NID_setct_CRLNotificationResTBS 599
+#define OBJ_setct_CRLNotificationResTBS OBJ_set_ctype,81L
+
+#define SN_setct_BCIDistributionTBS "setct-BCIDistributionTBS"
+#define NID_setct_BCIDistributionTBS 600
+#define OBJ_setct_BCIDistributionTBS OBJ_set_ctype,82L
+
+#define SN_setext_genCrypt "setext-genCrypt"
+#define LN_setext_genCrypt "generic cryptogram"
+#define NID_setext_genCrypt 601
+#define OBJ_setext_genCrypt OBJ_set_msgExt,1L
+
+#define SN_setext_miAuth "setext-miAuth"
+#define LN_setext_miAuth "merchant initiated auth"
+#define NID_setext_miAuth 602
+#define OBJ_setext_miAuth OBJ_set_msgExt,3L
+
+#define SN_setext_pinSecure "setext-pinSecure"
+#define NID_setext_pinSecure 603
+#define OBJ_setext_pinSecure OBJ_set_msgExt,4L
+
+#define SN_setext_pinAny "setext-pinAny"
+#define NID_setext_pinAny 604
+#define OBJ_setext_pinAny OBJ_set_msgExt,5L
+
+#define SN_setext_track2 "setext-track2"
+#define NID_setext_track2 605
+#define OBJ_setext_track2 OBJ_set_msgExt,7L
+
+#define SN_setext_cv "setext-cv"
+#define LN_setext_cv "additional verification"
+#define NID_setext_cv 606
+#define OBJ_setext_cv OBJ_set_msgExt,8L
+
+#define SN_set_policy_root "set-policy-root"
+#define NID_set_policy_root 607
+#define OBJ_set_policy_root OBJ_set_policy,0L
+
+#define SN_setCext_hashedRoot "setCext-hashedRoot"
+#define NID_setCext_hashedRoot 608
+#define OBJ_setCext_hashedRoot OBJ_set_certExt,0L
+
+#define SN_setCext_certType "setCext-certType"
+#define NID_setCext_certType 609
+#define OBJ_setCext_certType OBJ_set_certExt,1L
+
+#define SN_setCext_merchData "setCext-merchData"
+#define NID_setCext_merchData 610
+#define OBJ_setCext_merchData OBJ_set_certExt,2L
+
+#define SN_setCext_cCertRequired "setCext-cCertRequired"
+#define NID_setCext_cCertRequired 611
+#define OBJ_setCext_cCertRequired OBJ_set_certExt,3L
+
+#define SN_setCext_tunneling "setCext-tunneling"
+#define NID_setCext_tunneling 612
+#define OBJ_setCext_tunneling OBJ_set_certExt,4L
+
+#define SN_setCext_setExt "setCext-setExt"
+#define NID_setCext_setExt 613
+#define OBJ_setCext_setExt OBJ_set_certExt,5L
+
+#define SN_setCext_setQualf "setCext-setQualf"
+#define NID_setCext_setQualf 614
+#define OBJ_setCext_setQualf OBJ_set_certExt,6L
+
+#define SN_setCext_PGWYcapabilities "setCext-PGWYcapabilities"
+#define NID_setCext_PGWYcapabilities 615
+#define OBJ_setCext_PGWYcapabilities OBJ_set_certExt,7L
+
+#define SN_setCext_TokenIdentifier "setCext-TokenIdentifier"
+#define NID_setCext_TokenIdentifier 616
+#define OBJ_setCext_TokenIdentifier OBJ_set_certExt,8L
+
+#define SN_setCext_Track2Data "setCext-Track2Data"
+#define NID_setCext_Track2Data 617
+#define OBJ_setCext_Track2Data OBJ_set_certExt,9L
+
+#define SN_setCext_TokenType "setCext-TokenType"
+#define NID_setCext_TokenType 618
+#define OBJ_setCext_TokenType OBJ_set_certExt,10L
+
+#define SN_setCext_IssuerCapabilities "setCext-IssuerCapabilities"
+#define NID_setCext_IssuerCapabilities 619
+#define OBJ_setCext_IssuerCapabilities OBJ_set_certExt,11L
+
+#define SN_setAttr_Cert "setAttr-Cert"
+#define NID_setAttr_Cert 620
+#define OBJ_setAttr_Cert OBJ_set_attr,0L
+
+#define SN_setAttr_PGWYcap "setAttr-PGWYcap"
+#define LN_setAttr_PGWYcap "payment gateway capabilities"
+#define NID_setAttr_PGWYcap 621
+#define OBJ_setAttr_PGWYcap OBJ_set_attr,1L
+
+#define SN_setAttr_TokenType "setAttr-TokenType"
+#define NID_setAttr_TokenType 622
+#define OBJ_setAttr_TokenType OBJ_set_attr,2L
+
+#define SN_setAttr_IssCap "setAttr-IssCap"
+#define LN_setAttr_IssCap "issuer capabilities"
+#define NID_setAttr_IssCap 623
+#define OBJ_setAttr_IssCap OBJ_set_attr,3L
+
+#define SN_set_rootKeyThumb "set-rootKeyThumb"
+#define NID_set_rootKeyThumb 624
+#define OBJ_set_rootKeyThumb OBJ_setAttr_Cert,0L
+
+#define SN_set_addPolicy "set-addPolicy"
+#define NID_set_addPolicy 625
+#define OBJ_set_addPolicy OBJ_setAttr_Cert,1L
+
+#define SN_setAttr_Token_EMV "setAttr-Token-EMV"
+#define NID_setAttr_Token_EMV 626
+#define OBJ_setAttr_Token_EMV OBJ_setAttr_TokenType,1L
+
+#define SN_setAttr_Token_B0Prime "setAttr-Token-B0Prime"
+#define NID_setAttr_Token_B0Prime 627
+#define OBJ_setAttr_Token_B0Prime OBJ_setAttr_TokenType,2L
+
+#define SN_setAttr_IssCap_CVM "setAttr-IssCap-CVM"
+#define NID_setAttr_IssCap_CVM 628
+#define OBJ_setAttr_IssCap_CVM OBJ_setAttr_IssCap,3L
+
+#define SN_setAttr_IssCap_T2 "setAttr-IssCap-T2"
+#define NID_setAttr_IssCap_T2 629
+#define OBJ_setAttr_IssCap_T2 OBJ_setAttr_IssCap,4L
+
+#define SN_setAttr_IssCap_Sig "setAttr-IssCap-Sig"
+#define NID_setAttr_IssCap_Sig 630
+#define OBJ_setAttr_IssCap_Sig OBJ_setAttr_IssCap,5L
+
+#define SN_setAttr_GenCryptgrm "setAttr-GenCryptgrm"
+#define LN_setAttr_GenCryptgrm "generate cryptogram"
+#define NID_setAttr_GenCryptgrm 631
+#define OBJ_setAttr_GenCryptgrm OBJ_setAttr_IssCap_CVM,1L
+
+#define SN_setAttr_T2Enc "setAttr-T2Enc"
+#define LN_setAttr_T2Enc "encrypted track 2"
+#define NID_setAttr_T2Enc 632
+#define OBJ_setAttr_T2Enc OBJ_setAttr_IssCap_T2,1L
+
+#define SN_setAttr_T2cleartxt "setAttr-T2cleartxt"
+#define LN_setAttr_T2cleartxt "cleartext track 2"
+#define NID_setAttr_T2cleartxt 633
+#define OBJ_setAttr_T2cleartxt OBJ_setAttr_IssCap_T2,2L
+
+#define SN_setAttr_TokICCsig "setAttr-TokICCsig"
+#define LN_setAttr_TokICCsig "ICC or token signature"
+#define NID_setAttr_TokICCsig 634
+#define OBJ_setAttr_TokICCsig OBJ_setAttr_IssCap_Sig,1L
+
+#define SN_setAttr_SecDevSig "setAttr-SecDevSig"
+#define LN_setAttr_SecDevSig "secure device signature"
+#define NID_setAttr_SecDevSig 635
+#define OBJ_setAttr_SecDevSig OBJ_setAttr_IssCap_Sig,2L
+
+#define SN_set_brand_IATA_ATA "set-brand-IATA-ATA"
+#define NID_set_brand_IATA_ATA 636
+#define OBJ_set_brand_IATA_ATA OBJ_set_brand,1L
+
+#define SN_set_brand_Diners "set-brand-Diners"
+#define NID_set_brand_Diners 637
+#define OBJ_set_brand_Diners OBJ_set_brand,30L
+
+#define SN_set_brand_AmericanExpress "set-brand-AmericanExpress"
+#define NID_set_brand_AmericanExpress 638
+#define OBJ_set_brand_AmericanExpress OBJ_set_brand,34L
+
+#define SN_set_brand_JCB "set-brand-JCB"
+#define NID_set_brand_JCB 639
+#define OBJ_set_brand_JCB OBJ_set_brand,35L
+
+#define SN_set_brand_Visa "set-brand-Visa"
+#define NID_set_brand_Visa 640
+#define OBJ_set_brand_Visa OBJ_set_brand,4L
+
+#define SN_set_brand_MasterCard "set-brand-MasterCard"
+#define NID_set_brand_MasterCard 641
+#define OBJ_set_brand_MasterCard OBJ_set_brand,5L
+
+#define SN_set_brand_Novus "set-brand-Novus"
+#define NID_set_brand_Novus 642
+#define OBJ_set_brand_Novus OBJ_set_brand,6011L
+
+#define SN_des_cdmf "DES-CDMF"
+#define LN_des_cdmf "des-cdmf"
+#define NID_des_cdmf 643
+#define OBJ_des_cdmf OBJ_rsadsi,3L,10L
+
+#define SN_rsaOAEPEncryptionSET "rsaOAEPEncryptionSET"
+#define NID_rsaOAEPEncryptionSET 644
+#define OBJ_rsaOAEPEncryptionSET OBJ_rsadsi,1L,1L,6L
+
+#define SN_ipsec3 "Oakley-EC2N-3"
+#define LN_ipsec3 "ipsec3"
+#define NID_ipsec3 749
+
+#define SN_ipsec4 "Oakley-EC2N-4"
+#define LN_ipsec4 "ipsec4"
+#define NID_ipsec4 750
+
+#define SN_whirlpool "whirlpool"
+#define NID_whirlpool 804
+#define OBJ_whirlpool OBJ_iso,0L,10118L,3L,0L,55L
+
+#define SN_cryptopro "cryptopro"
+#define NID_cryptopro 805
+#define OBJ_cryptopro OBJ_member_body,643L,2L,2L
+
+#define SN_cryptocom "cryptocom"
+#define NID_cryptocom 806
+#define OBJ_cryptocom OBJ_member_body,643L,2L,9L
+
+#define SN_id_tc26 "id-tc26"
+#define NID_id_tc26 974
+#define OBJ_id_tc26 OBJ_member_body,643L,7L,1L
+
+#define SN_id_GostR3411_94_with_GostR3410_2001 "id-GostR3411-94-with-GostR3410-2001"
+#define LN_id_GostR3411_94_with_GostR3410_2001 "GOST R 34.11-94 with GOST R 34.10-2001"
+#define NID_id_GostR3411_94_with_GostR3410_2001 807
+#define OBJ_id_GostR3411_94_with_GostR3410_2001 OBJ_cryptopro,3L
+
+#define SN_id_GostR3411_94_with_GostR3410_94 "id-GostR3411-94-with-GostR3410-94"
+#define LN_id_GostR3411_94_with_GostR3410_94 "GOST R 34.11-94 with GOST R 34.10-94"
+#define NID_id_GostR3411_94_with_GostR3410_94 808
+#define OBJ_id_GostR3411_94_with_GostR3410_94 OBJ_cryptopro,4L
+
+#define SN_id_GostR3411_94 "md_gost94"
+#define LN_id_GostR3411_94 "GOST R 34.11-94"
+#define NID_id_GostR3411_94 809
+#define OBJ_id_GostR3411_94 OBJ_cryptopro,9L
+
+#define SN_id_HMACGostR3411_94 "id-HMACGostR3411-94"
+#define LN_id_HMACGostR3411_94 "HMAC GOST 34.11-94"
+#define NID_id_HMACGostR3411_94 810
+#define OBJ_id_HMACGostR3411_94 OBJ_cryptopro,10L
+
+#define SN_id_GostR3410_2001 "gost2001"
+#define LN_id_GostR3410_2001 "GOST R 34.10-2001"
+#define NID_id_GostR3410_2001 811
+#define OBJ_id_GostR3410_2001 OBJ_cryptopro,19L
+
+#define SN_id_GostR3410_94 "gost94"
+#define LN_id_GostR3410_94 "GOST R 34.10-94"
+#define NID_id_GostR3410_94 812
+#define OBJ_id_GostR3410_94 OBJ_cryptopro,20L
+
+#define SN_id_Gost28147_89 "gost89"
+#define LN_id_Gost28147_89 "GOST 28147-89"
+#define NID_id_Gost28147_89 813
+#define OBJ_id_Gost28147_89 OBJ_cryptopro,21L
+
+#define SN_gost89_cnt "gost89-cnt"
+#define NID_gost89_cnt 814
+
+#define SN_gost89_cnt_12 "gost89-cnt-12"
+#define NID_gost89_cnt_12 975
+
+#define SN_gost89_cbc "gost89-cbc"
+#define NID_gost89_cbc 1009
+
+#define SN_gost89_ecb "gost89-ecb"
+#define NID_gost89_ecb 1010
+
+#define SN_gost89_ctr "gost89-ctr"
+#define NID_gost89_ctr 1011
+
+#define SN_id_Gost28147_89_MAC "gost-mac"
+#define LN_id_Gost28147_89_MAC "GOST 28147-89 MAC"
+#define NID_id_Gost28147_89_MAC 815
+#define OBJ_id_Gost28147_89_MAC OBJ_cryptopro,22L
+
+#define SN_gost_mac_12 "gost-mac-12"
+#define NID_gost_mac_12 976
+
+#define SN_id_GostR3411_94_prf "prf-gostr3411-94"
+#define LN_id_GostR3411_94_prf "GOST R 34.11-94 PRF"
+#define NID_id_GostR3411_94_prf 816
+#define OBJ_id_GostR3411_94_prf OBJ_cryptopro,23L
+
+#define SN_id_GostR3410_2001DH "id-GostR3410-2001DH"
+#define LN_id_GostR3410_2001DH "GOST R 34.10-2001 DH"
+#define NID_id_GostR3410_2001DH 817
+#define OBJ_id_GostR3410_2001DH OBJ_cryptopro,98L
+
+#define SN_id_GostR3410_94DH "id-GostR3410-94DH"
+#define LN_id_GostR3410_94DH "GOST R 34.10-94 DH"
+#define NID_id_GostR3410_94DH 818
+#define OBJ_id_GostR3410_94DH OBJ_cryptopro,99L
+
+#define SN_id_Gost28147_89_CryptoPro_KeyMeshing "id-Gost28147-89-CryptoPro-KeyMeshing"
+#define NID_id_Gost28147_89_CryptoPro_KeyMeshing 819
+#define OBJ_id_Gost28147_89_CryptoPro_KeyMeshing OBJ_cryptopro,14L,1L
+
+#define SN_id_Gost28147_89_None_KeyMeshing "id-Gost28147-89-None-KeyMeshing"
+#define NID_id_Gost28147_89_None_KeyMeshing 820
+#define OBJ_id_Gost28147_89_None_KeyMeshing OBJ_cryptopro,14L,0L
+
+#define SN_id_GostR3411_94_TestParamSet "id-GostR3411-94-TestParamSet"
+#define NID_id_GostR3411_94_TestParamSet 821
+#define OBJ_id_GostR3411_94_TestParamSet OBJ_cryptopro,30L,0L
+
+#define SN_id_GostR3411_94_CryptoProParamSet "id-GostR3411-94-CryptoProParamSet"
+#define NID_id_GostR3411_94_CryptoProParamSet 822
+#define OBJ_id_GostR3411_94_CryptoProParamSet OBJ_cryptopro,30L,1L
+
+#define SN_id_Gost28147_89_TestParamSet "id-Gost28147-89-TestParamSet"
+#define NID_id_Gost28147_89_TestParamSet 823
+#define OBJ_id_Gost28147_89_TestParamSet OBJ_cryptopro,31L,0L
+
+#define SN_id_Gost28147_89_CryptoPro_A_ParamSet "id-Gost28147-89-CryptoPro-A-ParamSet"
+#define NID_id_Gost28147_89_CryptoPro_A_ParamSet 824
+#define OBJ_id_Gost28147_89_CryptoPro_A_ParamSet OBJ_cryptopro,31L,1L
+
+#define SN_id_Gost28147_89_CryptoPro_B_ParamSet "id-Gost28147-89-CryptoPro-B-ParamSet"
+#define NID_id_Gost28147_89_CryptoPro_B_ParamSet 825
+#define OBJ_id_Gost28147_89_CryptoPro_B_ParamSet OBJ_cryptopro,31L,2L
+
+#define SN_id_Gost28147_89_CryptoPro_C_ParamSet "id-Gost28147-89-CryptoPro-C-ParamSet"
+#define NID_id_Gost28147_89_CryptoPro_C_ParamSet 826
+#define OBJ_id_Gost28147_89_CryptoPro_C_ParamSet OBJ_cryptopro,31L,3L
+
+#define SN_id_Gost28147_89_CryptoPro_D_ParamSet "id-Gost28147-89-CryptoPro-D-ParamSet"
+#define NID_id_Gost28147_89_CryptoPro_D_ParamSet 827
+#define OBJ_id_Gost28147_89_CryptoPro_D_ParamSet OBJ_cryptopro,31L,4L
+
+#define SN_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet "id-Gost28147-89-CryptoPro-Oscar-1-1-ParamSet"
+#define NID_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet 828
+#define OBJ_id_Gost28147_89_CryptoPro_Oscar_1_1_ParamSet OBJ_cryptopro,31L,5L
+
+#define SN_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet "id-Gost28147-89-CryptoPro-Oscar-1-0-ParamSet"
+#define NID_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet 829
+#define OBJ_id_Gost28147_89_CryptoPro_Oscar_1_0_ParamSet OBJ_cryptopro,31L,6L
+
+#define SN_id_Gost28147_89_CryptoPro_RIC_1_ParamSet "id-Gost28147-89-CryptoPro-RIC-1-ParamSet"
+#define NID_id_Gost28147_89_CryptoPro_RIC_1_ParamSet 830
+#define OBJ_id_Gost28147_89_CryptoPro_RIC_1_ParamSet OBJ_cryptopro,31L,7L
+
+#define SN_id_GostR3410_94_TestParamSet "id-GostR3410-94-TestParamSet"
+#define NID_id_GostR3410_94_TestParamSet 831
+#define OBJ_id_GostR3410_94_TestParamSet OBJ_cryptopro,32L,0L
+
+#define SN_id_GostR3410_94_CryptoPro_A_ParamSet "id-GostR3410-94-CryptoPro-A-ParamSet"
+#define NID_id_GostR3410_94_CryptoPro_A_ParamSet 832
+#define OBJ_id_GostR3410_94_CryptoPro_A_ParamSet OBJ_cryptopro,32L,2L
+
+#define SN_id_GostR3410_94_CryptoPro_B_ParamSet "id-GostR3410-94-CryptoPro-B-ParamSet"
+#define NID_id_GostR3410_94_CryptoPro_B_ParamSet 833
+#define OBJ_id_GostR3410_94_CryptoPro_B_ParamSet OBJ_cryptopro,32L,3L
+
+#define SN_id_GostR3410_94_CryptoPro_C_ParamSet "id-GostR3410-94-CryptoPro-C-ParamSet"
+#define NID_id_GostR3410_94_CryptoPro_C_ParamSet 834
+#define OBJ_id_GostR3410_94_CryptoPro_C_ParamSet OBJ_cryptopro,32L,4L
+
+#define SN_id_GostR3410_94_CryptoPro_D_ParamSet "id-GostR3410-94-CryptoPro-D-ParamSet"
+#define NID_id_GostR3410_94_CryptoPro_D_ParamSet 835
+#define OBJ_id_GostR3410_94_CryptoPro_D_ParamSet OBJ_cryptopro,32L,5L
+
+#define SN_id_GostR3410_94_CryptoPro_XchA_ParamSet "id-GostR3410-94-CryptoPro-XchA-ParamSet"
+#define NID_id_GostR3410_94_CryptoPro_XchA_ParamSet 836
+#define OBJ_id_GostR3410_94_CryptoPro_XchA_ParamSet OBJ_cryptopro,33L,1L
+
+#define SN_id_GostR3410_94_CryptoPro_XchB_ParamSet "id-GostR3410-94-CryptoPro-XchB-ParamSet"
+#define NID_id_GostR3410_94_CryptoPro_XchB_ParamSet 837
+#define OBJ_id_GostR3410_94_CryptoPro_XchB_ParamSet OBJ_cryptopro,33L,2L
+
+#define SN_id_GostR3410_94_CryptoPro_XchC_ParamSet "id-GostR3410-94-CryptoPro-XchC-ParamSet"
+#define NID_id_GostR3410_94_CryptoPro_XchC_ParamSet 838
+#define OBJ_id_GostR3410_94_CryptoPro_XchC_ParamSet OBJ_cryptopro,33L,3L
+
+#define SN_id_GostR3410_2001_TestParamSet "id-GostR3410-2001-TestParamSet"
+#define NID_id_GostR3410_2001_TestParamSet 839
+#define OBJ_id_GostR3410_2001_TestParamSet OBJ_cryptopro,35L,0L
+
+#define SN_id_GostR3410_2001_CryptoPro_A_ParamSet "id-GostR3410-2001-CryptoPro-A-ParamSet"
+#define NID_id_GostR3410_2001_CryptoPro_A_ParamSet 840
+#define OBJ_id_GostR3410_2001_CryptoPro_A_ParamSet OBJ_cryptopro,35L,1L
+
+#define SN_id_GostR3410_2001_CryptoPro_B_ParamSet "id-GostR3410-2001-CryptoPro-B-ParamSet"
+#define NID_id_GostR3410_2001_CryptoPro_B_ParamSet 841
+#define OBJ_id_GostR3410_2001_CryptoPro_B_ParamSet OBJ_cryptopro,35L,2L
+
+#define SN_id_GostR3410_2001_CryptoPro_C_ParamSet "id-GostR3410-2001-CryptoPro-C-ParamSet"
+#define NID_id_GostR3410_2001_CryptoPro_C_ParamSet 842
+#define OBJ_id_GostR3410_2001_CryptoPro_C_ParamSet OBJ_cryptopro,35L,3L
+
+#define SN_id_GostR3410_2001_CryptoPro_XchA_ParamSet "id-GostR3410-2001-CryptoPro-XchA-ParamSet"
+#define NID_id_GostR3410_2001_CryptoPro_XchA_ParamSet 843
+#define OBJ_id_GostR3410_2001_CryptoPro_XchA_ParamSet OBJ_cryptopro,36L,0L
+
+#define SN_id_GostR3410_2001_CryptoPro_XchB_ParamSet "id-GostR3410-2001-CryptoPro-XchB-ParamSet"
+#define NID_id_GostR3410_2001_CryptoPro_XchB_ParamSet 844
+#define OBJ_id_GostR3410_2001_CryptoPro_XchB_ParamSet OBJ_cryptopro,36L,1L
+
+#define SN_id_GostR3410_94_a "id-GostR3410-94-a"
+#define NID_id_GostR3410_94_a 845
+#define OBJ_id_GostR3410_94_a OBJ_id_GostR3410_94,1L
+
+#define SN_id_GostR3410_94_aBis "id-GostR3410-94-aBis"
+#define NID_id_GostR3410_94_aBis 846
+#define OBJ_id_GostR3410_94_aBis OBJ_id_GostR3410_94,2L
+
+#define SN_id_GostR3410_94_b "id-GostR3410-94-b"
+#define NID_id_GostR3410_94_b 847
+#define OBJ_id_GostR3410_94_b OBJ_id_GostR3410_94,3L
+
+#define SN_id_GostR3410_94_bBis "id-GostR3410-94-bBis"
+#define NID_id_GostR3410_94_bBis 848
+#define OBJ_id_GostR3410_94_bBis OBJ_id_GostR3410_94,4L
+
+#define SN_id_Gost28147_89_cc "id-Gost28147-89-cc"
+#define LN_id_Gost28147_89_cc "GOST 28147-89 Cryptocom ParamSet"
+#define NID_id_Gost28147_89_cc 849
+#define OBJ_id_Gost28147_89_cc OBJ_cryptocom,1L,6L,1L
+
+#define SN_id_GostR3410_94_cc "gost94cc"
+#define LN_id_GostR3410_94_cc "GOST 34.10-94 Cryptocom"
+#define NID_id_GostR3410_94_cc 850
+#define OBJ_id_GostR3410_94_cc OBJ_cryptocom,1L,5L,3L
+
+#define SN_id_GostR3410_2001_cc "gost2001cc"
+#define LN_id_GostR3410_2001_cc "GOST 34.10-2001 Cryptocom"
+#define NID_id_GostR3410_2001_cc 851
+#define OBJ_id_GostR3410_2001_cc OBJ_cryptocom,1L,5L,4L
+
+#define SN_id_GostR3411_94_with_GostR3410_94_cc "id-GostR3411-94-with-GostR3410-94-cc"
+#define LN_id_GostR3411_94_with_GostR3410_94_cc "GOST R 34.11-94 with GOST R 34.10-94 Cryptocom"
+#define NID_id_GostR3411_94_with_GostR3410_94_cc 852
+#define OBJ_id_GostR3411_94_with_GostR3410_94_cc OBJ_cryptocom,1L,3L,3L
+
+#define SN_id_GostR3411_94_with_GostR3410_2001_cc "id-GostR3411-94-with-GostR3410-2001-cc"
+#define LN_id_GostR3411_94_with_GostR3410_2001_cc "GOST R 34.11-94 with GOST R 34.10-2001 Cryptocom"
+#define NID_id_GostR3411_94_with_GostR3410_2001_cc 853
+#define OBJ_id_GostR3411_94_with_GostR3410_2001_cc OBJ_cryptocom,1L,3L,4L
+
+#define SN_id_GostR3410_2001_ParamSet_cc "id-GostR3410-2001-ParamSet-cc"
+#define LN_id_GostR3410_2001_ParamSet_cc "GOST R 3410-2001 Parameter Set Cryptocom"
+#define NID_id_GostR3410_2001_ParamSet_cc 854
+#define OBJ_id_GostR3410_2001_ParamSet_cc OBJ_cryptocom,1L,8L,1L
+
+#define SN_id_tc26_algorithms "id-tc26-algorithms"
+#define NID_id_tc26_algorithms 977
+#define OBJ_id_tc26_algorithms OBJ_id_tc26,1L
+
+#define SN_id_tc26_sign "id-tc26-sign"
+#define NID_id_tc26_sign 978
+#define OBJ_id_tc26_sign OBJ_id_tc26_algorithms,1L
+
+#define SN_id_GostR3410_2012_256 "gost2012_256"
+#define LN_id_GostR3410_2012_256 "GOST R 34.10-2012 with 256 bit modulus"
+#define NID_id_GostR3410_2012_256 979
+#define OBJ_id_GostR3410_2012_256 OBJ_id_tc26_sign,1L
+
+#define SN_id_GostR3410_2012_512 "gost2012_512"
+#define LN_id_GostR3410_2012_512 "GOST R 34.10-2012 with 512 bit modulus"
+#define NID_id_GostR3410_2012_512 980
+#define OBJ_id_GostR3410_2012_512 OBJ_id_tc26_sign,2L
+
+#define SN_id_tc26_digest "id-tc26-digest"
+#define NID_id_tc26_digest 981
+#define OBJ_id_tc26_digest OBJ_id_tc26_algorithms,2L
+
+#define SN_id_GostR3411_2012_256 "md_gost12_256"
+#define LN_id_GostR3411_2012_256 "GOST R 34.11-2012 with 256 bit hash"
+#define NID_id_GostR3411_2012_256 982
+#define OBJ_id_GostR3411_2012_256 OBJ_id_tc26_digest,2L
+
+#define SN_id_GostR3411_2012_512 "md_gost12_512"
+#define LN_id_GostR3411_2012_512 "GOST R 34.11-2012 with 512 bit hash"
+#define NID_id_GostR3411_2012_512 983
+#define OBJ_id_GostR3411_2012_512 OBJ_id_tc26_digest,3L
+
+#define SN_id_tc26_signwithdigest "id-tc26-signwithdigest"
+#define NID_id_tc26_signwithdigest 984
+#define OBJ_id_tc26_signwithdigest OBJ_id_tc26_algorithms,3L
+
+#define SN_id_tc26_signwithdigest_gost3410_2012_256 "id-tc26-signwithdigest-gost3410-2012-256"
+#define LN_id_tc26_signwithdigest_gost3410_2012_256 "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)"
+#define NID_id_tc26_signwithdigest_gost3410_2012_256 985
+#define OBJ_id_tc26_signwithdigest_gost3410_2012_256 OBJ_id_tc26_signwithdigest,2L
+
+#define SN_id_tc26_signwithdigest_gost3410_2012_512 "id-tc26-signwithdigest-gost3410-2012-512"
+#define LN_id_tc26_signwithdigest_gost3410_2012_512 "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)"
+#define NID_id_tc26_signwithdigest_gost3410_2012_512 986
+#define OBJ_id_tc26_signwithdigest_gost3410_2012_512 OBJ_id_tc26_signwithdigest,3L
+
+#define SN_id_tc26_mac "id-tc26-mac"
+#define NID_id_tc26_mac 987
+#define OBJ_id_tc26_mac OBJ_id_tc26_algorithms,4L
+
+#define SN_id_tc26_hmac_gost_3411_2012_256 "id-tc26-hmac-gost-3411-2012-256"
+#define LN_id_tc26_hmac_gost_3411_2012_256 "HMAC GOST 34.11-2012 256 bit"
+#define NID_id_tc26_hmac_gost_3411_2012_256 988
+#define OBJ_id_tc26_hmac_gost_3411_2012_256 OBJ_id_tc26_mac,1L
+
+#define SN_id_tc26_hmac_gost_3411_2012_512 "id-tc26-hmac-gost-3411-2012-512"
+#define LN_id_tc26_hmac_gost_3411_2012_512 "HMAC GOST 34.11-2012 512 bit"
+#define NID_id_tc26_hmac_gost_3411_2012_512 989
+#define OBJ_id_tc26_hmac_gost_3411_2012_512 OBJ_id_tc26_mac,2L
+
+#define SN_id_tc26_cipher "id-tc26-cipher"
+#define NID_id_tc26_cipher 990
+#define OBJ_id_tc26_cipher OBJ_id_tc26_algorithms,5L
+
+#define SN_id_tc26_cipher_gostr3412_2015_magma "id-tc26-cipher-gostr3412-2015-magma"
+#define NID_id_tc26_cipher_gostr3412_2015_magma 1173
+#define OBJ_id_tc26_cipher_gostr3412_2015_magma OBJ_id_tc26_cipher,1L
+
+#define SN_magma_ctr_acpkm "magma-ctr-acpkm"
+#define NID_magma_ctr_acpkm 1174
+#define OBJ_magma_ctr_acpkm OBJ_id_tc26_cipher_gostr3412_2015_magma,1L
+
+#define SN_magma_ctr_acpkm_omac "magma-ctr-acpkm-omac"
+#define NID_magma_ctr_acpkm_omac 1175
+#define OBJ_magma_ctr_acpkm_omac OBJ_id_tc26_cipher_gostr3412_2015_magma,2L
+
+#define SN_id_tc26_cipher_gostr3412_2015_kuznyechik "id-tc26-cipher-gostr3412-2015-kuznyechik"
+#define NID_id_tc26_cipher_gostr3412_2015_kuznyechik 1176
+#define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik OBJ_id_tc26_cipher,2L
+
+#define SN_kuznyechik_ctr_acpkm "kuznyechik-ctr-acpkm"
+#define NID_kuznyechik_ctr_acpkm 1177
+#define OBJ_kuznyechik_ctr_acpkm OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik,1L
+
+#define SN_kuznyechik_ctr_acpkm_omac "kuznyechik-ctr-acpkm-omac"
+#define NID_kuznyechik_ctr_acpkm_omac 1178
+#define OBJ_kuznyechik_ctr_acpkm_omac OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik,2L
+
+#define SN_id_tc26_agreement "id-tc26-agreement"
+#define NID_id_tc26_agreement 991
+#define OBJ_id_tc26_agreement OBJ_id_tc26_algorithms,6L
+
+#define SN_id_tc26_agreement_gost_3410_2012_256 "id-tc26-agreement-gost-3410-2012-256"
+#define NID_id_tc26_agreement_gost_3410_2012_256 992
+#define OBJ_id_tc26_agreement_gost_3410_2012_256 OBJ_id_tc26_agreement,1L
+
+#define SN_id_tc26_agreement_gost_3410_2012_512 "id-tc26-agreement-gost-3410-2012-512"
+#define NID_id_tc26_agreement_gost_3410_2012_512 993
+#define OBJ_id_tc26_agreement_gost_3410_2012_512 OBJ_id_tc26_agreement,2L
+
+#define SN_id_tc26_wrap "id-tc26-wrap"
+#define NID_id_tc26_wrap 1179
+#define OBJ_id_tc26_wrap OBJ_id_tc26_algorithms,7L
+
+#define SN_id_tc26_wrap_gostr3412_2015_magma "id-tc26-wrap-gostr3412-2015-magma"
+#define NID_id_tc26_wrap_gostr3412_2015_magma 1180
+#define OBJ_id_tc26_wrap_gostr3412_2015_magma OBJ_id_tc26_wrap,1L
+
+#define SN_magma_kexp15 "magma-kexp15"
+#define NID_magma_kexp15 1181
+#define OBJ_magma_kexp15 OBJ_id_tc26_wrap_gostr3412_2015_magma,1L
+
+#define SN_id_tc26_wrap_gostr3412_2015_kuznyechik "id-tc26-wrap-gostr3412-2015-kuznyechik"
+#define NID_id_tc26_wrap_gostr3412_2015_kuznyechik 1182
+#define OBJ_id_tc26_wrap_gostr3412_2015_kuznyechik OBJ_id_tc26_wrap,2L
+
+#define SN_kuznyechik_kexp15 "kuznyechik-kexp15"
+#define NID_kuznyechik_kexp15 1183
+#define OBJ_kuznyechik_kexp15 OBJ_id_tc26_wrap_gostr3412_2015_kuznyechik,1L
+
+#define SN_id_tc26_constants "id-tc26-constants"
+#define NID_id_tc26_constants 994
+#define OBJ_id_tc26_constants OBJ_id_tc26,2L
+
+#define SN_id_tc26_sign_constants "id-tc26-sign-constants"
+#define NID_id_tc26_sign_constants 995
+#define OBJ_id_tc26_sign_constants OBJ_id_tc26_constants,1L
+
+#define SN_id_tc26_gost_3410_2012_256_constants "id-tc26-gost-3410-2012-256-constants"
+#define NID_id_tc26_gost_3410_2012_256_constants 1147
+#define OBJ_id_tc26_gost_3410_2012_256_constants OBJ_id_tc26_sign_constants,1L
+
+#define SN_id_tc26_gost_3410_2012_256_paramSetA "id-tc26-gost-3410-2012-256-paramSetA"
+#define LN_id_tc26_gost_3410_2012_256_paramSetA "GOST R 34.10-2012 (256 bit) ParamSet A"
+#define NID_id_tc26_gost_3410_2012_256_paramSetA 1148
+#define OBJ_id_tc26_gost_3410_2012_256_paramSetA OBJ_id_tc26_gost_3410_2012_256_constants,1L
+
+#define SN_id_tc26_gost_3410_2012_256_paramSetB "id-tc26-gost-3410-2012-256-paramSetB"
+#define LN_id_tc26_gost_3410_2012_256_paramSetB "GOST R 34.10-2012 (256 bit) ParamSet B"
+#define NID_id_tc26_gost_3410_2012_256_paramSetB 1184
+#define OBJ_id_tc26_gost_3410_2012_256_paramSetB OBJ_id_tc26_gost_3410_2012_256_constants,2L
+
+#define SN_id_tc26_gost_3410_2012_256_paramSetC "id-tc26-gost-3410-2012-256-paramSetC"
+#define LN_id_tc26_gost_3410_2012_256_paramSetC "GOST R 34.10-2012 (256 bit) ParamSet C"
+#define NID_id_tc26_gost_3410_2012_256_paramSetC 1185
+#define OBJ_id_tc26_gost_3410_2012_256_paramSetC OBJ_id_tc26_gost_3410_2012_256_constants,3L
+
+#define SN_id_tc26_gost_3410_2012_256_paramSetD "id-tc26-gost-3410-2012-256-paramSetD"
+#define LN_id_tc26_gost_3410_2012_256_paramSetD "GOST R 34.10-2012 (256 bit) ParamSet D"
+#define NID_id_tc26_gost_3410_2012_256_paramSetD 1186
+#define OBJ_id_tc26_gost_3410_2012_256_paramSetD OBJ_id_tc26_gost_3410_2012_256_constants,4L
+
+#define SN_id_tc26_gost_3410_2012_512_constants "id-tc26-gost-3410-2012-512-constants"
+#define NID_id_tc26_gost_3410_2012_512_constants 996
+#define OBJ_id_tc26_gost_3410_2012_512_constants OBJ_id_tc26_sign_constants,2L
+
+#define SN_id_tc26_gost_3410_2012_512_paramSetTest "id-tc26-gost-3410-2012-512-paramSetTest"
+#define LN_id_tc26_gost_3410_2012_512_paramSetTest "GOST R 34.10-2012 (512 bit) testing parameter set"
+#define NID_id_tc26_gost_3410_2012_512_paramSetTest 997
+#define OBJ_id_tc26_gost_3410_2012_512_paramSetTest OBJ_id_tc26_gost_3410_2012_512_constants,0L
+
+#define SN_id_tc26_gost_3410_2012_512_paramSetA "id-tc26-gost-3410-2012-512-paramSetA"
+#define LN_id_tc26_gost_3410_2012_512_paramSetA "GOST R 34.10-2012 (512 bit) ParamSet A"
+#define NID_id_tc26_gost_3410_2012_512_paramSetA 998
+#define OBJ_id_tc26_gost_3410_2012_512_paramSetA OBJ_id_tc26_gost_3410_2012_512_constants,1L
+
+#define SN_id_tc26_gost_3410_2012_512_paramSetB "id-tc26-gost-3410-2012-512-paramSetB"
+#define LN_id_tc26_gost_3410_2012_512_paramSetB "GOST R 34.10-2012 (512 bit) ParamSet B"
+#define NID_id_tc26_gost_3410_2012_512_paramSetB 999
+#define OBJ_id_tc26_gost_3410_2012_512_paramSetB OBJ_id_tc26_gost_3410_2012_512_constants,2L
+
+#define SN_id_tc26_gost_3410_2012_512_paramSetC "id-tc26-gost-3410-2012-512-paramSetC"
+#define LN_id_tc26_gost_3410_2012_512_paramSetC "GOST R 34.10-2012 (512 bit) ParamSet C"
+#define NID_id_tc26_gost_3410_2012_512_paramSetC 1149
+#define OBJ_id_tc26_gost_3410_2012_512_paramSetC OBJ_id_tc26_gost_3410_2012_512_constants,3L
+
+#define SN_id_tc26_digest_constants "id-tc26-digest-constants"
+#define NID_id_tc26_digest_constants 1000
+#define OBJ_id_tc26_digest_constants OBJ_id_tc26_constants,2L
+
+#define SN_id_tc26_cipher_constants "id-tc26-cipher-constants"
+#define NID_id_tc26_cipher_constants 1001
+#define OBJ_id_tc26_cipher_constants OBJ_id_tc26_constants,5L
+
+#define SN_id_tc26_gost_28147_constants "id-tc26-gost-28147-constants"
+#define NID_id_tc26_gost_28147_constants 1002
+#define OBJ_id_tc26_gost_28147_constants OBJ_id_tc26_cipher_constants,1L
+
+#define SN_id_tc26_gost_28147_param_Z "id-tc26-gost-28147-param-Z"
+#define LN_id_tc26_gost_28147_param_Z "GOST 28147-89 TC26 parameter set"
+#define NID_id_tc26_gost_28147_param_Z 1003
+#define OBJ_id_tc26_gost_28147_param_Z OBJ_id_tc26_gost_28147_constants,1L
+
+#define SN_INN "INN"
+#define LN_INN "INN"
+#define NID_INN 1004
+#define OBJ_INN OBJ_member_body,643L,3L,131L,1L,1L
+
+#define SN_OGRN "OGRN"
+#define LN_OGRN "OGRN"
+#define NID_OGRN 1005
+#define OBJ_OGRN OBJ_member_body,643L,100L,1L
+
+#define SN_SNILS "SNILS"
+#define LN_SNILS "SNILS"
+#define NID_SNILS 1006
+#define OBJ_SNILS OBJ_member_body,643L,100L,3L
+
+#define SN_OGRNIP "OGRNIP"
+#define LN_OGRNIP "OGRNIP"
+#define NID_OGRNIP 1226
+#define OBJ_OGRNIP OBJ_member_body,643L,100L,5L
+
+#define SN_subjectSignTool "subjectSignTool"
+#define LN_subjectSignTool "Signing Tool of Subject"
+#define NID_subjectSignTool 1007
+#define OBJ_subjectSignTool OBJ_member_body,643L,100L,111L
+
+#define SN_issuerSignTool "issuerSignTool"
+#define LN_issuerSignTool "Signing Tool of Issuer"
+#define NID_issuerSignTool 1008
+#define OBJ_issuerSignTool OBJ_member_body,643L,100L,112L
+
+#define SN_classSignTool "classSignTool"
+#define LN_classSignTool "Class of Signing Tool"
+#define NID_classSignTool 1227
+#define OBJ_classSignTool OBJ_member_body,643L,100L,113L
+
+#define SN_classSignToolKC1 "classSignToolKC1"
+#define LN_classSignToolKC1 "Class of Signing Tool KC1"
+#define NID_classSignToolKC1 1228
+#define OBJ_classSignToolKC1 OBJ_member_body,643L,100L,113L,1L
+
+#define SN_classSignToolKC2 "classSignToolKC2"
+#define LN_classSignToolKC2 "Class of Signing Tool KC2"
+#define NID_classSignToolKC2 1229
+#define OBJ_classSignToolKC2 OBJ_member_body,643L,100L,113L,2L
+
+#define SN_classSignToolKC3 "classSignToolKC3"
+#define LN_classSignToolKC3 "Class of Signing Tool KC3"
+#define NID_classSignToolKC3 1230
+#define OBJ_classSignToolKC3 OBJ_member_body,643L,100L,113L,3L
+
+#define SN_classSignToolKB1 "classSignToolKB1"
+#define LN_classSignToolKB1 "Class of Signing Tool KB1"
+#define NID_classSignToolKB1 1231
+#define OBJ_classSignToolKB1 OBJ_member_body,643L,100L,113L,4L
+
+#define SN_classSignToolKB2 "classSignToolKB2"
+#define LN_classSignToolKB2 "Class of Signing Tool KB2"
+#define NID_classSignToolKB2 1232
+#define OBJ_classSignToolKB2 OBJ_member_body,643L,100L,113L,5L
+
+#define SN_classSignToolKA1 "classSignToolKA1"
+#define LN_classSignToolKA1 "Class of Signing Tool KA1"
+#define NID_classSignToolKA1 1233
+#define OBJ_classSignToolKA1 OBJ_member_body,643L,100L,113L,6L
+
+#define SN_kuznyechik_ecb "kuznyechik-ecb"
+#define NID_kuznyechik_ecb 1012
+
+#define SN_kuznyechik_ctr "kuznyechik-ctr"
+#define NID_kuznyechik_ctr 1013
+
+#define SN_kuznyechik_ofb "kuznyechik-ofb"
+#define NID_kuznyechik_ofb 1014
+
+#define SN_kuznyechik_cbc "kuznyechik-cbc"
+#define NID_kuznyechik_cbc 1015
+
+#define SN_kuznyechik_cfb "kuznyechik-cfb"
+#define NID_kuznyechik_cfb 1016
+
+#define SN_kuznyechik_mac "kuznyechik-mac"
+#define NID_kuznyechik_mac 1017
+
+#define SN_magma_ecb "magma-ecb"
+#define NID_magma_ecb 1187
+
+#define SN_magma_ctr "magma-ctr"
+#define NID_magma_ctr 1188
+
+#define SN_magma_ofb "magma-ofb"
+#define NID_magma_ofb 1189
+
+#define SN_magma_cbc "magma-cbc"
+#define NID_magma_cbc 1190
+
+#define SN_magma_cfb "magma-cfb"
+#define NID_magma_cfb 1191
+
+#define SN_magma_mac "magma-mac"
+#define NID_magma_mac 1192
+
+#define SN_camellia_128_cbc "CAMELLIA-128-CBC"
+#define LN_camellia_128_cbc "camellia-128-cbc"
+#define NID_camellia_128_cbc 751
+#define OBJ_camellia_128_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,2L
+
+#define SN_camellia_192_cbc "CAMELLIA-192-CBC"
+#define LN_camellia_192_cbc "camellia-192-cbc"
+#define NID_camellia_192_cbc 752
+#define OBJ_camellia_192_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,3L
+
+#define SN_camellia_256_cbc "CAMELLIA-256-CBC"
+#define LN_camellia_256_cbc "camellia-256-cbc"
+#define NID_camellia_256_cbc 753
+#define OBJ_camellia_256_cbc 1L,2L,392L,200011L,61L,1L,1L,1L,4L
+
+#define SN_id_camellia128_wrap "id-camellia128-wrap"
+#define NID_id_camellia128_wrap 907
+#define OBJ_id_camellia128_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,2L
+
+#define SN_id_camellia192_wrap "id-camellia192-wrap"
+#define NID_id_camellia192_wrap 908
+#define OBJ_id_camellia192_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,3L
+
+#define SN_id_camellia256_wrap "id-camellia256-wrap"
+#define NID_id_camellia256_wrap 909
+#define OBJ_id_camellia256_wrap 1L,2L,392L,200011L,61L,1L,1L,3L,4L
+
+#define OBJ_ntt_ds 0L,3L,4401L,5L
+
+#define OBJ_camellia OBJ_ntt_ds,3L,1L,9L
+
+#define SN_camellia_128_ecb "CAMELLIA-128-ECB"
+#define LN_camellia_128_ecb "camellia-128-ecb"
+#define NID_camellia_128_ecb 754
+#define OBJ_camellia_128_ecb OBJ_camellia,1L
+
+#define SN_camellia_128_ofb128 "CAMELLIA-128-OFB"
+#define LN_camellia_128_ofb128 "camellia-128-ofb"
+#define NID_camellia_128_ofb128 766
+#define OBJ_camellia_128_ofb128 OBJ_camellia,3L
+
+#define SN_camellia_128_cfb128 "CAMELLIA-128-CFB"
+#define LN_camellia_128_cfb128 "camellia-128-cfb"
+#define NID_camellia_128_cfb128 757
+#define OBJ_camellia_128_cfb128 OBJ_camellia,4L
+
+#define SN_camellia_128_gcm "CAMELLIA-128-GCM"
+#define LN_camellia_128_gcm "camellia-128-gcm"
+#define NID_camellia_128_gcm 961
+#define OBJ_camellia_128_gcm OBJ_camellia,6L
+
+#define SN_camellia_128_ccm "CAMELLIA-128-CCM"
+#define LN_camellia_128_ccm "camellia-128-ccm"
+#define NID_camellia_128_ccm 962
+#define OBJ_camellia_128_ccm OBJ_camellia,7L
+
+#define SN_camellia_128_ctr "CAMELLIA-128-CTR"
+#define LN_camellia_128_ctr "camellia-128-ctr"
+#define NID_camellia_128_ctr 963
+#define OBJ_camellia_128_ctr OBJ_camellia,9L
+
+#define SN_camellia_128_cmac "CAMELLIA-128-CMAC"
+#define LN_camellia_128_cmac "camellia-128-cmac"
+#define NID_camellia_128_cmac 964
+#define OBJ_camellia_128_cmac OBJ_camellia,10L
+
+#define SN_camellia_192_ecb "CAMELLIA-192-ECB"
+#define LN_camellia_192_ecb "camellia-192-ecb"
+#define NID_camellia_192_ecb 755
+#define OBJ_camellia_192_ecb OBJ_camellia,21L
+
+#define SN_camellia_192_ofb128 "CAMELLIA-192-OFB"
+#define LN_camellia_192_ofb128 "camellia-192-ofb"
+#define NID_camellia_192_ofb128 767
+#define OBJ_camellia_192_ofb128 OBJ_camellia,23L
+
+#define SN_camellia_192_cfb128 "CAMELLIA-192-CFB"
+#define LN_camellia_192_cfb128 "camellia-192-cfb"
+#define NID_camellia_192_cfb128 758
+#define OBJ_camellia_192_cfb128 OBJ_camellia,24L
+
+#define SN_camellia_192_gcm "CAMELLIA-192-GCM"
+#define LN_camellia_192_gcm "camellia-192-gcm"
+#define NID_camellia_192_gcm 965
+#define OBJ_camellia_192_gcm OBJ_camellia,26L
+
+#define SN_camellia_192_ccm "CAMELLIA-192-CCM"
+#define LN_camellia_192_ccm "camellia-192-ccm"
+#define NID_camellia_192_ccm 966
+#define OBJ_camellia_192_ccm OBJ_camellia,27L
+
+#define SN_camellia_192_ctr "CAMELLIA-192-CTR"
+#define LN_camellia_192_ctr "camellia-192-ctr"
+#define NID_camellia_192_ctr 967
+#define OBJ_camellia_192_ctr OBJ_camellia,29L
+
+#define SN_camellia_192_cmac "CAMELLIA-192-CMAC"
+#define LN_camellia_192_cmac "camellia-192-cmac"
+#define NID_camellia_192_cmac 968
+#define OBJ_camellia_192_cmac OBJ_camellia,30L
+
+#define SN_camellia_256_ecb "CAMELLIA-256-ECB"
+#define LN_camellia_256_ecb "camellia-256-ecb"
+#define NID_camellia_256_ecb 756
+#define OBJ_camellia_256_ecb OBJ_camellia,41L
+
+#define SN_camellia_256_ofb128 "CAMELLIA-256-OFB"
+#define LN_camellia_256_ofb128 "camellia-256-ofb"
+#define NID_camellia_256_ofb128 768
+#define OBJ_camellia_256_ofb128 OBJ_camellia,43L
+
+#define SN_camellia_256_cfb128 "CAMELLIA-256-CFB"
+#define LN_camellia_256_cfb128 "camellia-256-cfb"
+#define NID_camellia_256_cfb128 759
+#define OBJ_camellia_256_cfb128 OBJ_camellia,44L
+
+#define SN_camellia_256_gcm "CAMELLIA-256-GCM"
+#define LN_camellia_256_gcm "camellia-256-gcm"
+#define NID_camellia_256_gcm 969
+#define OBJ_camellia_256_gcm OBJ_camellia,46L
+
+#define SN_camellia_256_ccm "CAMELLIA-256-CCM"
+#define LN_camellia_256_ccm "camellia-256-ccm"
+#define NID_camellia_256_ccm 970
+#define OBJ_camellia_256_ccm OBJ_camellia,47L
+
+#define SN_camellia_256_ctr "CAMELLIA-256-CTR"
+#define LN_camellia_256_ctr "camellia-256-ctr"
+#define NID_camellia_256_ctr 971
+#define OBJ_camellia_256_ctr OBJ_camellia,49L
+
+#define SN_camellia_256_cmac "CAMELLIA-256-CMAC"
+#define LN_camellia_256_cmac "camellia-256-cmac"
+#define NID_camellia_256_cmac 972
+#define OBJ_camellia_256_cmac OBJ_camellia,50L
+
+#define SN_camellia_128_cfb1 "CAMELLIA-128-CFB1"
+#define LN_camellia_128_cfb1 "camellia-128-cfb1"
+#define NID_camellia_128_cfb1 760
+
+#define SN_camellia_192_cfb1 "CAMELLIA-192-CFB1"
+#define LN_camellia_192_cfb1 "camellia-192-cfb1"
+#define NID_camellia_192_cfb1 761
+
+#define SN_camellia_256_cfb1 "CAMELLIA-256-CFB1"
+#define LN_camellia_256_cfb1 "camellia-256-cfb1"
+#define NID_camellia_256_cfb1 762
+
+#define SN_camellia_128_cfb8 "CAMELLIA-128-CFB8"
+#define LN_camellia_128_cfb8 "camellia-128-cfb8"
+#define NID_camellia_128_cfb8 763
+
+#define SN_camellia_192_cfb8 "CAMELLIA-192-CFB8"
+#define LN_camellia_192_cfb8 "camellia-192-cfb8"
+#define NID_camellia_192_cfb8 764
+
+#define SN_camellia_256_cfb8 "CAMELLIA-256-CFB8"
+#define LN_camellia_256_cfb8 "camellia-256-cfb8"
+#define NID_camellia_256_cfb8 765
+
+#define OBJ_aria 1L,2L,410L,200046L,1L,1L
+
+#define SN_aria_128_ecb "ARIA-128-ECB"
+#define LN_aria_128_ecb "aria-128-ecb"
+#define NID_aria_128_ecb 1065
+#define OBJ_aria_128_ecb OBJ_aria,1L
+
+#define SN_aria_128_cbc "ARIA-128-CBC"
+#define LN_aria_128_cbc "aria-128-cbc"
+#define NID_aria_128_cbc 1066
+#define OBJ_aria_128_cbc OBJ_aria,2L
+
+#define SN_aria_128_cfb128 "ARIA-128-CFB"
+#define LN_aria_128_cfb128 "aria-128-cfb"
+#define NID_aria_128_cfb128 1067
+#define OBJ_aria_128_cfb128 OBJ_aria,3L
+
+#define SN_aria_128_ofb128 "ARIA-128-OFB"
+#define LN_aria_128_ofb128 "aria-128-ofb"
+#define NID_aria_128_ofb128 1068
+#define OBJ_aria_128_ofb128 OBJ_aria,4L
+
+#define SN_aria_128_ctr "ARIA-128-CTR"
+#define LN_aria_128_ctr "aria-128-ctr"
+#define NID_aria_128_ctr 1069
+#define OBJ_aria_128_ctr OBJ_aria,5L
+
+#define SN_aria_192_ecb "ARIA-192-ECB"
+#define LN_aria_192_ecb "aria-192-ecb"
+#define NID_aria_192_ecb 1070
+#define OBJ_aria_192_ecb OBJ_aria,6L
+
+#define SN_aria_192_cbc "ARIA-192-CBC"
+#define LN_aria_192_cbc "aria-192-cbc"
+#define NID_aria_192_cbc 1071
+#define OBJ_aria_192_cbc OBJ_aria,7L
+
+#define SN_aria_192_cfb128 "ARIA-192-CFB"
+#define LN_aria_192_cfb128 "aria-192-cfb"
+#define NID_aria_192_cfb128 1072
+#define OBJ_aria_192_cfb128 OBJ_aria,8L
+
+#define SN_aria_192_ofb128 "ARIA-192-OFB"
+#define LN_aria_192_ofb128 "aria-192-ofb"
+#define NID_aria_192_ofb128 1073
+#define OBJ_aria_192_ofb128 OBJ_aria,9L
+
+#define SN_aria_192_ctr "ARIA-192-CTR"
+#define LN_aria_192_ctr "aria-192-ctr"
+#define NID_aria_192_ctr 1074
+#define OBJ_aria_192_ctr OBJ_aria,10L
+
+#define SN_aria_256_ecb "ARIA-256-ECB"
+#define LN_aria_256_ecb "aria-256-ecb"
+#define NID_aria_256_ecb 1075
+#define OBJ_aria_256_ecb OBJ_aria,11L
+
+#define SN_aria_256_cbc "ARIA-256-CBC"
+#define LN_aria_256_cbc "aria-256-cbc"
+#define NID_aria_256_cbc 1076
+#define OBJ_aria_256_cbc OBJ_aria,12L
+
+#define SN_aria_256_cfb128 "ARIA-256-CFB"
+#define LN_aria_256_cfb128 "aria-256-cfb"
+#define NID_aria_256_cfb128 1077
+#define OBJ_aria_256_cfb128 OBJ_aria,13L
+
+#define SN_aria_256_ofb128 "ARIA-256-OFB"
+#define LN_aria_256_ofb128 "aria-256-ofb"
+#define NID_aria_256_ofb128 1078
+#define OBJ_aria_256_ofb128 OBJ_aria,14L
+
+#define SN_aria_256_ctr "ARIA-256-CTR"
+#define LN_aria_256_ctr "aria-256-ctr"
+#define NID_aria_256_ctr 1079
+#define OBJ_aria_256_ctr OBJ_aria,15L
+
+#define SN_aria_128_cfb1 "ARIA-128-CFB1"
+#define LN_aria_128_cfb1 "aria-128-cfb1"
+#define NID_aria_128_cfb1 1080
+
+#define SN_aria_192_cfb1 "ARIA-192-CFB1"
+#define LN_aria_192_cfb1 "aria-192-cfb1"
+#define NID_aria_192_cfb1 1081
+
+#define SN_aria_256_cfb1 "ARIA-256-CFB1"
+#define LN_aria_256_cfb1 "aria-256-cfb1"
+#define NID_aria_256_cfb1 1082
+
+#define SN_aria_128_cfb8 "ARIA-128-CFB8"
+#define LN_aria_128_cfb8 "aria-128-cfb8"
+#define NID_aria_128_cfb8 1083
+
+#define SN_aria_192_cfb8 "ARIA-192-CFB8"
+#define LN_aria_192_cfb8 "aria-192-cfb8"
+#define NID_aria_192_cfb8 1084
+
+#define SN_aria_256_cfb8 "ARIA-256-CFB8"
+#define LN_aria_256_cfb8 "aria-256-cfb8"
+#define NID_aria_256_cfb8 1085
+
+#define SN_aria_128_ccm "ARIA-128-CCM"
+#define LN_aria_128_ccm "aria-128-ccm"
+#define NID_aria_128_ccm 1120
+#define OBJ_aria_128_ccm OBJ_aria,37L
+
+#define SN_aria_192_ccm "ARIA-192-CCM"
+#define LN_aria_192_ccm "aria-192-ccm"
+#define NID_aria_192_ccm 1121
+#define OBJ_aria_192_ccm OBJ_aria,38L
+
+#define SN_aria_256_ccm "ARIA-256-CCM"
+#define LN_aria_256_ccm "aria-256-ccm"
+#define NID_aria_256_ccm 1122
+#define OBJ_aria_256_ccm OBJ_aria,39L
+
+#define SN_aria_128_gcm "ARIA-128-GCM"
+#define LN_aria_128_gcm "aria-128-gcm"
+#define NID_aria_128_gcm 1123
+#define OBJ_aria_128_gcm OBJ_aria,34L
+
+#define SN_aria_192_gcm "ARIA-192-GCM"
+#define LN_aria_192_gcm "aria-192-gcm"
+#define NID_aria_192_gcm 1124
+#define OBJ_aria_192_gcm OBJ_aria,35L
+
+#define SN_aria_256_gcm "ARIA-256-GCM"
+#define LN_aria_256_gcm "aria-256-gcm"
+#define NID_aria_256_gcm 1125
+#define OBJ_aria_256_gcm OBJ_aria,36L
+
+#define SN_kisa "KISA"
+#define LN_kisa "kisa"
+#define NID_kisa 773
+#define OBJ_kisa OBJ_member_body,410L,200004L
+
+#define SN_seed_ecb "SEED-ECB"
+#define LN_seed_ecb "seed-ecb"
+#define NID_seed_ecb 776
+#define OBJ_seed_ecb OBJ_kisa,1L,3L
+
+#define SN_seed_cbc "SEED-CBC"
+#define LN_seed_cbc "seed-cbc"
+#define NID_seed_cbc 777
+#define OBJ_seed_cbc OBJ_kisa,1L,4L
+
+#define SN_seed_cfb128 "SEED-CFB"
+#define LN_seed_cfb128 "seed-cfb"
+#define NID_seed_cfb128 779
+#define OBJ_seed_cfb128 OBJ_kisa,1L,5L
+
+#define SN_seed_ofb128 "SEED-OFB"
+#define LN_seed_ofb128 "seed-ofb"
+#define NID_seed_ofb128 778
+#define OBJ_seed_ofb128 OBJ_kisa,1L,6L
+
+#define SN_sm4_ecb "SM4-ECB"
+#define LN_sm4_ecb "sm4-ecb"
+#define NID_sm4_ecb 1133
+#define OBJ_sm4_ecb OBJ_sm_scheme,104L,1L
+
+#define SN_sm4_cbc "SM4-CBC"
+#define LN_sm4_cbc "sm4-cbc"
+#define NID_sm4_cbc 1134
+#define OBJ_sm4_cbc OBJ_sm_scheme,104L,2L
+
+#define SN_sm4_ofb128 "SM4-OFB"
+#define LN_sm4_ofb128 "sm4-ofb"
+#define NID_sm4_ofb128 1135
+#define OBJ_sm4_ofb128 OBJ_sm_scheme,104L,3L
+
+#define SN_sm4_cfb128 "SM4-CFB"
+#define LN_sm4_cfb128 "sm4-cfb"
+#define NID_sm4_cfb128 1137
+#define OBJ_sm4_cfb128 OBJ_sm_scheme,104L,4L
+
+#define SN_sm4_cfb1 "SM4-CFB1"
+#define LN_sm4_cfb1 "sm4-cfb1"
+#define NID_sm4_cfb1 1136
+#define OBJ_sm4_cfb1 OBJ_sm_scheme,104L,5L
+
+#define SN_sm4_cfb8 "SM4-CFB8"
+#define LN_sm4_cfb8 "sm4-cfb8"
+#define NID_sm4_cfb8 1138
+#define OBJ_sm4_cfb8 OBJ_sm_scheme,104L,6L
+
+#define SN_sm4_ctr "SM4-CTR"
+#define LN_sm4_ctr "sm4-ctr"
+#define NID_sm4_ctr 1139
+#define OBJ_sm4_ctr OBJ_sm_scheme,104L,7L
+
+#define SN_hmac "HMAC"
+#define LN_hmac "hmac"
+#define NID_hmac 855
+
+#define SN_cmac "CMAC"
+#define LN_cmac "cmac"
+#define NID_cmac 894
+
+#define SN_rc4_hmac_md5 "RC4-HMAC-MD5"
+#define LN_rc4_hmac_md5 "rc4-hmac-md5"
+#define NID_rc4_hmac_md5 915
+
+#define SN_aes_128_cbc_hmac_sha1 "AES-128-CBC-HMAC-SHA1"
+#define LN_aes_128_cbc_hmac_sha1 "aes-128-cbc-hmac-sha1"
+#define NID_aes_128_cbc_hmac_sha1 916
+
+#define SN_aes_192_cbc_hmac_sha1 "AES-192-CBC-HMAC-SHA1"
+#define LN_aes_192_cbc_hmac_sha1 "aes-192-cbc-hmac-sha1"
+#define NID_aes_192_cbc_hmac_sha1 917
+
+#define SN_aes_256_cbc_hmac_sha1 "AES-256-CBC-HMAC-SHA1"
+#define LN_aes_256_cbc_hmac_sha1 "aes-256-cbc-hmac-sha1"
+#define NID_aes_256_cbc_hmac_sha1 918
+
+#define SN_aes_128_cbc_hmac_sha256 "AES-128-CBC-HMAC-SHA256"
+#define LN_aes_128_cbc_hmac_sha256 "aes-128-cbc-hmac-sha256"
+#define NID_aes_128_cbc_hmac_sha256 948
+
+#define SN_aes_192_cbc_hmac_sha256 "AES-192-CBC-HMAC-SHA256"
+#define LN_aes_192_cbc_hmac_sha256 "aes-192-cbc-hmac-sha256"
+#define NID_aes_192_cbc_hmac_sha256 949
+
+#define SN_aes_256_cbc_hmac_sha256 "AES-256-CBC-HMAC-SHA256"
+#define LN_aes_256_cbc_hmac_sha256 "aes-256-cbc-hmac-sha256"
+#define NID_aes_256_cbc_hmac_sha256 950
+
+#define SN_chacha20_poly1305 "ChaCha20-Poly1305"
+#define LN_chacha20_poly1305 "chacha20-poly1305"
+#define NID_chacha20_poly1305 1018
+
+#define SN_chacha20 "ChaCha20"
+#define LN_chacha20 "chacha20"
+#define NID_chacha20 1019
+
+#define SN_dhpublicnumber "dhpublicnumber"
+#define LN_dhpublicnumber "X9.42 DH"
+#define NID_dhpublicnumber 920
+#define OBJ_dhpublicnumber OBJ_ISO_US,10046L,2L,1L
+
+#define SN_brainpoolP160r1 "brainpoolP160r1"
+#define NID_brainpoolP160r1 921
+#define OBJ_brainpoolP160r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,1L
+
+#define SN_brainpoolP160t1 "brainpoolP160t1"
+#define NID_brainpoolP160t1 922
+#define OBJ_brainpoolP160t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,2L
+
+#define SN_brainpoolP192r1 "brainpoolP192r1"
+#define NID_brainpoolP192r1 923
+#define OBJ_brainpoolP192r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,3L
+
+#define SN_brainpoolP192t1 "brainpoolP192t1"
+#define NID_brainpoolP192t1 924
+#define OBJ_brainpoolP192t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,4L
+
+#define SN_brainpoolP224r1 "brainpoolP224r1"
+#define NID_brainpoolP224r1 925
+#define OBJ_brainpoolP224r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,5L
+
+#define SN_brainpoolP224t1 "brainpoolP224t1"
+#define NID_brainpoolP224t1 926
+#define OBJ_brainpoolP224t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,6L
+
+#define SN_brainpoolP256r1 "brainpoolP256r1"
+#define NID_brainpoolP256r1 927
+#define OBJ_brainpoolP256r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,7L
+
+#define SN_brainpoolP256t1 "brainpoolP256t1"
+#define NID_brainpoolP256t1 928
+#define OBJ_brainpoolP256t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,8L
+
+#define SN_brainpoolP320r1 "brainpoolP320r1"
+#define NID_brainpoolP320r1 929
+#define OBJ_brainpoolP320r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,9L
+
+#define SN_brainpoolP320t1 "brainpoolP320t1"
+#define NID_brainpoolP320t1 930
+#define OBJ_brainpoolP320t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,10L
+
+#define SN_brainpoolP384r1 "brainpoolP384r1"
+#define NID_brainpoolP384r1 931
+#define OBJ_brainpoolP384r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,11L
+
+#define SN_brainpoolP384t1 "brainpoolP384t1"
+#define NID_brainpoolP384t1 932
+#define OBJ_brainpoolP384t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,12L
+
+#define SN_brainpoolP512r1 "brainpoolP512r1"
+#define NID_brainpoolP512r1 933
+#define OBJ_brainpoolP512r1 1L,3L,36L,3L,3L,2L,8L,1L,1L,13L
+
+#define SN_brainpoolP512t1 "brainpoolP512t1"
+#define NID_brainpoolP512t1 934
+#define OBJ_brainpoolP512t1 1L,3L,36L,3L,3L,2L,8L,1L,1L,14L
+
+#define OBJ_x9_63_scheme 1L,3L,133L,16L,840L,63L,0L
+
+#define OBJ_secg_scheme OBJ_certicom_arc,1L
+
+#define SN_dhSinglePass_stdDH_sha1kdf_scheme "dhSinglePass-stdDH-sha1kdf-scheme"
+#define NID_dhSinglePass_stdDH_sha1kdf_scheme 936
+#define OBJ_dhSinglePass_stdDH_sha1kdf_scheme OBJ_x9_63_scheme,2L
+
+#define SN_dhSinglePass_stdDH_sha224kdf_scheme "dhSinglePass-stdDH-sha224kdf-scheme"
+#define NID_dhSinglePass_stdDH_sha224kdf_scheme 937
+#define OBJ_dhSinglePass_stdDH_sha224kdf_scheme OBJ_secg_scheme,11L,0L
+
+#define SN_dhSinglePass_stdDH_sha256kdf_scheme "dhSinglePass-stdDH-sha256kdf-scheme"
+#define NID_dhSinglePass_stdDH_sha256kdf_scheme 938
+#define OBJ_dhSinglePass_stdDH_sha256kdf_scheme OBJ_secg_scheme,11L,1L
+
+#define SN_dhSinglePass_stdDH_sha384kdf_scheme "dhSinglePass-stdDH-sha384kdf-scheme"
+#define NID_dhSinglePass_stdDH_sha384kdf_scheme 939
+#define OBJ_dhSinglePass_stdDH_sha384kdf_scheme OBJ_secg_scheme,11L,2L
+
+#define SN_dhSinglePass_stdDH_sha512kdf_scheme "dhSinglePass-stdDH-sha512kdf-scheme"
+#define NID_dhSinglePass_stdDH_sha512kdf_scheme 940
+#define OBJ_dhSinglePass_stdDH_sha512kdf_scheme OBJ_secg_scheme,11L,3L
+
+#define SN_dhSinglePass_cofactorDH_sha1kdf_scheme "dhSinglePass-cofactorDH-sha1kdf-scheme"
+#define NID_dhSinglePass_cofactorDH_sha1kdf_scheme 941
+#define OBJ_dhSinglePass_cofactorDH_sha1kdf_scheme OBJ_x9_63_scheme,3L
+
+#define SN_dhSinglePass_cofactorDH_sha224kdf_scheme "dhSinglePass-cofactorDH-sha224kdf-scheme"
+#define NID_dhSinglePass_cofactorDH_sha224kdf_scheme 942
+#define OBJ_dhSinglePass_cofactorDH_sha224kdf_scheme OBJ_secg_scheme,14L,0L
+
+#define SN_dhSinglePass_cofactorDH_sha256kdf_scheme "dhSinglePass-cofactorDH-sha256kdf-scheme"
+#define NID_dhSinglePass_cofactorDH_sha256kdf_scheme 943
+#define OBJ_dhSinglePass_cofactorDH_sha256kdf_scheme OBJ_secg_scheme,14L,1L
+
+#define SN_dhSinglePass_cofactorDH_sha384kdf_scheme "dhSinglePass-cofactorDH-sha384kdf-scheme"
+#define NID_dhSinglePass_cofactorDH_sha384kdf_scheme 944
+#define OBJ_dhSinglePass_cofactorDH_sha384kdf_scheme OBJ_secg_scheme,14L,2L
+
+#define SN_dhSinglePass_cofactorDH_sha512kdf_scheme "dhSinglePass-cofactorDH-sha512kdf-scheme"
+#define NID_dhSinglePass_cofactorDH_sha512kdf_scheme 945
+#define OBJ_dhSinglePass_cofactorDH_sha512kdf_scheme OBJ_secg_scheme,14L,3L
+
+#define SN_dh_std_kdf "dh-std-kdf"
+#define NID_dh_std_kdf 946
+
+#define SN_dh_cofactor_kdf "dh-cofactor-kdf"
+#define NID_dh_cofactor_kdf 947
+
+#define SN_ct_precert_scts "ct_precert_scts"
+#define LN_ct_precert_scts "CT Precertificate SCTs"
+#define NID_ct_precert_scts 951
+#define OBJ_ct_precert_scts 1L,3L,6L,1L,4L,1L,11129L,2L,4L,2L
+
+#define SN_ct_precert_poison "ct_precert_poison"
+#define LN_ct_precert_poison "CT Precertificate Poison"
+#define NID_ct_precert_poison 952
+#define OBJ_ct_precert_poison 1L,3L,6L,1L,4L,1L,11129L,2L,4L,3L
+
+#define SN_ct_precert_signer "ct_precert_signer"
+#define LN_ct_precert_signer "CT Precertificate Signer"
+#define NID_ct_precert_signer 953
+#define OBJ_ct_precert_signer 1L,3L,6L,1L,4L,1L,11129L,2L,4L,4L
+
+#define SN_ct_cert_scts "ct_cert_scts"
+#define LN_ct_cert_scts "CT Certificate SCTs"
+#define NID_ct_cert_scts 954
+#define OBJ_ct_cert_scts 1L,3L,6L,1L,4L,1L,11129L,2L,4L,5L
+
+#define SN_jurisdictionLocalityName "jurisdictionL"
+#define LN_jurisdictionLocalityName "jurisdictionLocalityName"
+#define NID_jurisdictionLocalityName 955
+#define OBJ_jurisdictionLocalityName 1L,3L,6L,1L,4L,1L,311L,60L,2L,1L,1L
+
+#define SN_jurisdictionStateOrProvinceName "jurisdictionST"
+#define LN_jurisdictionStateOrProvinceName "jurisdictionStateOrProvinceName"
+#define NID_jurisdictionStateOrProvinceName 956
+#define OBJ_jurisdictionStateOrProvinceName 1L,3L,6L,1L,4L,1L,311L,60L,2L,1L,2L
+
+#define SN_jurisdictionCountryName "jurisdictionC"
+#define LN_jurisdictionCountryName "jurisdictionCountryName"
+#define NID_jurisdictionCountryName 957
+#define OBJ_jurisdictionCountryName 1L,3L,6L,1L,4L,1L,311L,60L,2L,1L,3L
+
+#define SN_id_scrypt "id-scrypt"
+#define LN_id_scrypt "scrypt"
+#define NID_id_scrypt 973
+#define OBJ_id_scrypt 1L,3L,6L,1L,4L,1L,11591L,4L,11L
+
+#define SN_tls1_prf "TLS1-PRF"
+#define LN_tls1_prf "tls1-prf"
+#define NID_tls1_prf 1021
+
+#define SN_hkdf "HKDF"
+#define LN_hkdf "hkdf"
+#define NID_hkdf 1036
+
+#define SN_sshkdf "SSHKDF"
+#define LN_sshkdf "sshkdf"
+#define NID_sshkdf 1203
+
+#define SN_sskdf "SSKDF"
+#define LN_sskdf "sskdf"
+#define NID_sskdf 1205
+
+#define SN_x942kdf "X942KDF"
+#define LN_x942kdf "x942kdf"
+#define NID_x942kdf 1207
+
+#define SN_x963kdf "X963KDF"
+#define LN_x963kdf "x963kdf"
+#define NID_x963kdf 1206
+
+#define SN_id_pkinit "id-pkinit"
+#define NID_id_pkinit 1031
+#define OBJ_id_pkinit 1L,3L,6L,1L,5L,2L,3L
+
+#define SN_pkInitClientAuth "pkInitClientAuth"
+#define LN_pkInitClientAuth "PKINIT Client Auth"
+#define NID_pkInitClientAuth 1032
+#define OBJ_pkInitClientAuth OBJ_id_pkinit,4L
+
+#define SN_pkInitKDC "pkInitKDC"
+#define LN_pkInitKDC "Signing KDC Response"
+#define NID_pkInitKDC 1033
+#define OBJ_pkInitKDC OBJ_id_pkinit,5L
+
+#define SN_X25519 "X25519"
+#define NID_X25519 1034
+#define OBJ_X25519 1L,3L,101L,110L
+
+#define SN_X448 "X448"
+#define NID_X448 1035
+#define OBJ_X448 1L,3L,101L,111L
+
+#define SN_ED25519 "ED25519"
+#define NID_ED25519 1087
+#define OBJ_ED25519 1L,3L,101L,112L
+
+#define SN_ED448 "ED448"
+#define NID_ED448 1088
+#define OBJ_ED448 1L,3L,101L,113L
+
+#define SN_kx_rsa "KxRSA"
+#define LN_kx_rsa "kx-rsa"
+#define NID_kx_rsa 1037
+
+#define SN_kx_ecdhe "KxECDHE"
+#define LN_kx_ecdhe "kx-ecdhe"
+#define NID_kx_ecdhe 1038
+
+#define SN_kx_dhe "KxDHE"
+#define LN_kx_dhe "kx-dhe"
+#define NID_kx_dhe 1039
+
+#define SN_kx_ecdhe_psk "KxECDHE-PSK"
+#define LN_kx_ecdhe_psk "kx-ecdhe-psk"
+#define NID_kx_ecdhe_psk 1040
+
+#define SN_kx_dhe_psk "KxDHE-PSK"
+#define LN_kx_dhe_psk "kx-dhe-psk"
+#define NID_kx_dhe_psk 1041
+
+#define SN_kx_rsa_psk "KxRSA_PSK"
+#define LN_kx_rsa_psk "kx-rsa-psk"
+#define NID_kx_rsa_psk 1042
+
+#define SN_kx_psk "KxPSK"
+#define LN_kx_psk "kx-psk"
+#define NID_kx_psk 1043
+
+#define SN_kx_srp "KxSRP"
+#define LN_kx_srp "kx-srp"
+#define NID_kx_srp 1044
+
+#define SN_kx_gost "KxGOST"
+#define LN_kx_gost "kx-gost"
+#define NID_kx_gost 1045
+
+#define SN_kx_gost18 "KxGOST18"
+#define LN_kx_gost18 "kx-gost18"
+#define NID_kx_gost18 1218
+
+#define SN_kx_any "KxANY"
+#define LN_kx_any "kx-any"
+#define NID_kx_any 1063
+
+#define SN_auth_rsa "AuthRSA"
+#define LN_auth_rsa "auth-rsa"
+#define NID_auth_rsa 1046
+
+#define SN_auth_ecdsa "AuthECDSA"
+#define LN_auth_ecdsa "auth-ecdsa"
+#define NID_auth_ecdsa 1047
+
+#define SN_auth_psk "AuthPSK"
+#define LN_auth_psk "auth-psk"
+#define NID_auth_psk 1048
+
+#define SN_auth_dss "AuthDSS"
+#define LN_auth_dss "auth-dss"
+#define NID_auth_dss 1049
+
+#define SN_auth_gost01 "AuthGOST01"
+#define LN_auth_gost01 "auth-gost01"
+#define NID_auth_gost01 1050
+
+#define SN_auth_gost12 "AuthGOST12"
+#define LN_auth_gost12 "auth-gost12"
+#define NID_auth_gost12 1051
+
+#define SN_auth_srp "AuthSRP"
+#define LN_auth_srp "auth-srp"
+#define NID_auth_srp 1052
+
+#define SN_auth_null "AuthNULL"
+#define LN_auth_null "auth-null"
+#define NID_auth_null 1053
+
+#define SN_auth_any "AuthANY"
+#define LN_auth_any "auth-any"
+#define NID_auth_any 1064
+
+#define SN_poly1305 "Poly1305"
+#define LN_poly1305 "poly1305"
+#define NID_poly1305 1061
+
+#define SN_siphash "SipHash"
+#define LN_siphash "siphash"
+#define NID_siphash 1062
+
+#define SN_ffdhe2048 "ffdhe2048"
+#define NID_ffdhe2048 1126
+
+#define SN_ffdhe3072 "ffdhe3072"
+#define NID_ffdhe3072 1127
+
+#define SN_ffdhe4096 "ffdhe4096"
+#define NID_ffdhe4096 1128
+
+#define SN_ffdhe6144 "ffdhe6144"
+#define NID_ffdhe6144 1129
+
+#define SN_ffdhe8192 "ffdhe8192"
+#define NID_ffdhe8192 1130
+
+#define SN_modp_1536 "modp_1536"
+#define NID_modp_1536 1212
+
+#define SN_modp_2048 "modp_2048"
+#define NID_modp_2048 1213
+
+#define SN_modp_3072 "modp_3072"
+#define NID_modp_3072 1214
+
+#define SN_modp_4096 "modp_4096"
+#define NID_modp_4096 1215
+
+#define SN_modp_6144 "modp_6144"
+#define NID_modp_6144 1216
+
+#define SN_modp_8192 "modp_8192"
+#define NID_modp_8192 1217
+
+#define SN_ISO_UA "ISO-UA"
+#define NID_ISO_UA 1150
+#define OBJ_ISO_UA OBJ_member_body,804L
+
+#define SN_ua_pki "ua-pki"
+#define NID_ua_pki 1151
+#define OBJ_ua_pki OBJ_ISO_UA,2L,1L,1L,1L
+
+#define SN_dstu28147 "dstu28147"
+#define LN_dstu28147 "DSTU Gost 28147-2009"
+#define NID_dstu28147 1152
+#define OBJ_dstu28147 OBJ_ua_pki,1L,1L,1L
+
+#define SN_dstu28147_ofb "dstu28147-ofb"
+#define LN_dstu28147_ofb "DSTU Gost 28147-2009 OFB mode"
+#define NID_dstu28147_ofb 1153
+#define OBJ_dstu28147_ofb OBJ_dstu28147,2L
+
+#define SN_dstu28147_cfb "dstu28147-cfb"
+#define LN_dstu28147_cfb "DSTU Gost 28147-2009 CFB mode"
+#define NID_dstu28147_cfb 1154
+#define OBJ_dstu28147_cfb OBJ_dstu28147,3L
+
+#define SN_dstu28147_wrap "dstu28147-wrap"
+#define LN_dstu28147_wrap "DSTU Gost 28147-2009 key wrap"
+#define NID_dstu28147_wrap 1155
+#define OBJ_dstu28147_wrap OBJ_dstu28147,5L
+
+#define SN_hmacWithDstu34311 "hmacWithDstu34311"
+#define LN_hmacWithDstu34311 "HMAC DSTU Gost 34311-95"
+#define NID_hmacWithDstu34311 1156
+#define OBJ_hmacWithDstu34311 OBJ_ua_pki,1L,1L,2L
+
+#define SN_dstu34311 "dstu34311"
+#define LN_dstu34311 "DSTU Gost 34311-95"
+#define NID_dstu34311 1157
+#define OBJ_dstu34311 OBJ_ua_pki,1L,2L,1L
+
+#define SN_dstu4145le "dstu4145le"
+#define LN_dstu4145le "DSTU 4145-2002 little endian"
+#define NID_dstu4145le 1158
+#define OBJ_dstu4145le OBJ_ua_pki,1L,3L,1L,1L
+
+#define SN_dstu4145be "dstu4145be"
+#define LN_dstu4145be "DSTU 4145-2002 big endian"
+#define NID_dstu4145be 1159
+#define OBJ_dstu4145be OBJ_dstu4145le,1L,1L
+
+#define SN_uacurve0 "uacurve0"
+#define LN_uacurve0 "DSTU curve 0"
+#define NID_uacurve0 1160
+#define OBJ_uacurve0 OBJ_dstu4145le,2L,0L
+
+#define SN_uacurve1 "uacurve1"
+#define LN_uacurve1 "DSTU curve 1"
+#define NID_uacurve1 1161
+#define OBJ_uacurve1 OBJ_dstu4145le,2L,1L
+
+#define SN_uacurve2 "uacurve2"
+#define LN_uacurve2 "DSTU curve 2"
+#define NID_uacurve2 1162
+#define OBJ_uacurve2 OBJ_dstu4145le,2L,2L
+
+#define SN_uacurve3 "uacurve3"
+#define LN_uacurve3 "DSTU curve 3"
+#define NID_uacurve3 1163
+#define OBJ_uacurve3 OBJ_dstu4145le,2L,3L
+
+#define SN_uacurve4 "uacurve4"
+#define LN_uacurve4 "DSTU curve 4"
+#define NID_uacurve4 1164
+#define OBJ_uacurve4 OBJ_dstu4145le,2L,4L
+
+#define SN_uacurve5 "uacurve5"
+#define LN_uacurve5 "DSTU curve 5"
+#define NID_uacurve5 1165
+#define OBJ_uacurve5 OBJ_dstu4145le,2L,5L
+
+#define SN_uacurve6 "uacurve6"
+#define LN_uacurve6 "DSTU curve 6"
+#define NID_uacurve6 1166
+#define OBJ_uacurve6 OBJ_dstu4145le,2L,6L
+
+#define SN_uacurve7 "uacurve7"
+#define LN_uacurve7 "DSTU curve 7"
+#define NID_uacurve7 1167
+#define OBJ_uacurve7 OBJ_dstu4145le,2L,7L
+
+#define SN_uacurve8 "uacurve8"
+#define LN_uacurve8 "DSTU curve 8"
+#define NID_uacurve8 1168
+#define OBJ_uacurve8 OBJ_dstu4145le,2L,8L
+
+#define SN_uacurve9 "uacurve9"
+#define LN_uacurve9 "DSTU curve 9"
+#define NID_uacurve9 1169
+#define OBJ_uacurve9 OBJ_dstu4145le,2L,9L
+
+#define SN_aes_128_siv "AES-128-SIV"
+#define LN_aes_128_siv "aes-128-siv"
+#define NID_aes_128_siv 1198
+
+#define SN_aes_192_siv "AES-192-SIV"
+#define LN_aes_192_siv "aes-192-siv"
+#define NID_aes_192_siv 1199
+
+#define SN_aes_256_siv "AES-256-SIV"
+#define LN_aes_256_siv "aes-256-siv"
+#define NID_aes_256_siv 1200
+
+#endif /* OPENSSL_OBJ_MAC_H */
+
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+
+#define SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm SN_magma_ctr_acpkm
+#define NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm NID_magma_ctr_acpkm
+#define OBJ_id_tc26_cipher_gostr3412_2015_magma_ctracpkm OBJ_magma_ctr_acpkm
+
+#define SN_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac SN_magma_ctr_acpkm_omac
+#define NID_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac NID_magma_ctr_acpkm_omac
+#define OBJ_id_tc26_cipher_gostr3412_2015_magma_ctracpkm_omac OBJ_magma_ctr_acpkm_omac
+
+#define SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm SN_kuznyechik_ctr_acpkm
+#define NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm NID_kuznyechik_ctr_acpkm
+#define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm OBJ_kuznyechik_ctr_acpkm
+
+#define SN_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac SN_kuznyechik_ctr_acpkm_omac
+#define NID_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac NID_kuznyechik_ctr_acpkm_omac
+#define OBJ_id_tc26_cipher_gostr3412_2015_kuznyechik_ctracpkm_omac OBJ_kuznyechik_ctr_acpkm_omac
+
+#define SN_id_tc26_wrap_gostr3412_2015_magma_kexp15 SN_magma_kexp15
+#define NID_id_tc26_wrap_gostr3412_2015_magma_kexp15 NID_magma_kexp15
+#define OBJ_id_tc26_wrap_gostr3412_2015_magma_kexp15 OBJ_magma_kexp15
+
+#define SN_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 SN_kuznyechik_kexp15
+#define NID_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 NID_kuznyechik_kexp15
+#define OBJ_id_tc26_wrap_gostr3412_2015_kuznyechik_kexp15 OBJ_kuznyechik_kexp15
+
+#define SN_grasshopper_ecb SN_kuznyechik_ecb
+#define NID_grasshopper_ecb NID_kuznyechik_ecb
+
+#define SN_grasshopper_ctr SN_kuznyechik_ctr
+#define NID_grasshopper_ctr NID_kuznyechik_ctr
+
+#define SN_grasshopper_ofb SN_kuznyechik_ofb
+#define NID_grasshopper_ofb NID_kuznyechik_ofb
+
+#define SN_grasshopper_cbc SN_kuznyechik_cbc
+#define NID_grasshopper_cbc NID_kuznyechik_cbc
+
+#define SN_grasshopper_cfb SN_kuznyechik_cfb
+#define NID_grasshopper_cfb NID_kuznyechik_cfb
+
+#define SN_grasshopper_mac SN_kuznyechik_mac
+#define NID_grasshopper_mac NID_kuznyechik_mac
+
+#endif /* OPENSSL_NO_DEPRECATED_3_0 */
diff --git a/include/openssl/objects.h b/include/openssl/objects.h
new file mode 100644
index 00000000..9ea91c27
--- /dev/null
+++ b/include/openssl/objects.h
@@ -0,0 +1,183 @@
+/*
+ * Copyright 1995-2019 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_OBJECTS_H
+# define OPENSSL_OBJECTS_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_OBJECTS_H
+# endif
+
+# include <openssl/obj_mac.h>
+# include <openssl/bio.h>
+# include <openssl/asn1.h>
+# include <openssl/objectserr.h>
+
+# define OBJ_NAME_TYPE_UNDEF 0x00
+# define OBJ_NAME_TYPE_MD_METH 0x01
+# define OBJ_NAME_TYPE_CIPHER_METH 0x02
+# define OBJ_NAME_TYPE_PKEY_METH 0x03
+# define OBJ_NAME_TYPE_COMP_METH 0x04
+# define OBJ_NAME_TYPE_MAC_METH 0x05
+# define OBJ_NAME_TYPE_KDF_METH 0x06
+# define OBJ_NAME_TYPE_NUM 0x07
+
+# define OBJ_NAME_ALIAS 0x8000
+
+# define OBJ_BSEARCH_VALUE_ON_NOMATCH 0x01
+# define OBJ_BSEARCH_FIRST_VALUE_ON_MATCH 0x02
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct obj_name_st {
+ int type;
+ int alias;
+ const char *name;
+ const char *data;
+} OBJ_NAME;
+
+# define OBJ_create_and_add_object(a,b,c) OBJ_create(a,b,c)
+
+int OBJ_NAME_init(void);
+int OBJ_NAME_new_index(unsigned long (*hash_func) (const char *),
+ int (*cmp_func) (const char *, const char *),
+ void (*free_func) (const char *, int, const char *));
+const char *OBJ_NAME_get(const char *name, int type);
+int OBJ_NAME_add(const char *name, int type, const char *data);
+int OBJ_NAME_remove(const char *name, int type);
+void OBJ_NAME_cleanup(int type); /* -1 for everything */
+void OBJ_NAME_do_all(int type, void (*fn) (const OBJ_NAME *, void *arg),
+ void *arg);
+void OBJ_NAME_do_all_sorted(int type,
+ void (*fn) (const OBJ_NAME *, void *arg),
+ void *arg);
+
+DECLARE_ASN1_DUP_FUNCTION_name(ASN1_OBJECT, OBJ)
+ASN1_OBJECT *OBJ_nid2obj(int n);
+const char *OBJ_nid2ln(int n);
+const char *OBJ_nid2sn(int n);
+int OBJ_obj2nid(const ASN1_OBJECT *o);
+ASN1_OBJECT *OBJ_txt2obj(const char *s, int no_name);
+int OBJ_obj2txt(char *buf, int buf_len, const ASN1_OBJECT *a, int no_name);
+int OBJ_txt2nid(const char *s);
+int OBJ_ln2nid(const char *s);
+int OBJ_sn2nid(const char *s);
+int OBJ_cmp(const ASN1_OBJECT *a, const ASN1_OBJECT *b);
+const void *OBJ_bsearch_(const void *key, const void *base, int num, int size,
+ int (*cmp) (const void *, const void *));
+const void *OBJ_bsearch_ex_(const void *key, const void *base, int num,
+ int size,
+ int (*cmp) (const void *, const void *),
+ int flags);
+
+# define _DECLARE_OBJ_BSEARCH_CMP_FN(scope, type1, type2, nm) \
+ static int nm##_cmp_BSEARCH_CMP_FN(const void *, const void *); \
+ static int nm##_cmp(type1 const *, type2 const *); \
+ scope type2 * OBJ_bsearch_##nm(type1 *key, type2 const *base, int num)
+
+# define DECLARE_OBJ_BSEARCH_CMP_FN(type1, type2, cmp) \
+ _DECLARE_OBJ_BSEARCH_CMP_FN(static, type1, type2, cmp)
+# define DECLARE_OBJ_BSEARCH_GLOBAL_CMP_FN(type1, type2, nm) \
+ type2 * OBJ_bsearch_##nm(type1 *key, type2 const *base, int num)
+
+/*-
+ * Unsolved problem: if a type is actually a pointer type, like
+ * nid_triple is, then its impossible to get a const where you need
+ * it. Consider:
+ *
+ * typedef int nid_triple[3];
+ * const void *a_;
+ * const nid_triple const *a = a_;
+ *
+ * The assignment discards a const because what you really want is:
+ *
+ * const int const * const *a = a_;
+ *
+ * But if you do that, you lose the fact that a is an array of 3 ints,
+ * which breaks comparison functions.
+ *
+ * Thus we end up having to cast, sadly, or unpack the
+ * declarations. Or, as I finally did in this case, declare nid_triple
+ * to be a struct, which it should have been in the first place.
+ *
+ * Ben, August 2008.
+ *
+ * Also, strictly speaking not all types need be const, but handling
+ * the non-constness means a lot of complication, and in practice
+ * comparison routines do always not touch their arguments.
+ */
+
+# define IMPLEMENT_OBJ_BSEARCH_CMP_FN(type1, type2, nm) \
+ static int nm##_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_) \
+ { \
+ type1 const *a = a_; \
+ type2 const *b = b_; \
+ return nm##_cmp(a,b); \
+ } \
+ static type2 *OBJ_bsearch_##nm(type1 *key, type2 const *base, int num) \
+ { \
+ return (type2 *)OBJ_bsearch_(key, base, num, sizeof(type2), \
+ nm##_cmp_BSEARCH_CMP_FN); \
+ } \
+ extern void dummy_prototype(void)
+
+# define IMPLEMENT_OBJ_BSEARCH_GLOBAL_CMP_FN(type1, type2, nm) \
+ static int nm##_cmp_BSEARCH_CMP_FN(const void *a_, const void *b_) \
+ { \
+ type1 const *a = a_; \
+ type2 const *b = b_; \
+ return nm##_cmp(a,b); \
+ } \
+ type2 *OBJ_bsearch_##nm(type1 *key, type2 const *base, int num) \
+ { \
+ return (type2 *)OBJ_bsearch_(key, base, num, sizeof(type2), \
+ nm##_cmp_BSEARCH_CMP_FN); \
+ } \
+ extern void dummy_prototype(void)
+
+# define OBJ_bsearch(type1,key,type2,base,num,cmp) \
+ ((type2 *)OBJ_bsearch_(CHECKED_PTR_OF(type1,key),CHECKED_PTR_OF(type2,base), \
+ num,sizeof(type2), \
+ ((void)CHECKED_PTR_OF(type1,cmp##_type_1), \
+ (void)CHECKED_PTR_OF(type2,cmp##_type_2), \
+ cmp##_BSEARCH_CMP_FN)))
+
+# define OBJ_bsearch_ex(type1,key,type2,base,num,cmp,flags) \
+ ((type2 *)OBJ_bsearch_ex_(CHECKED_PTR_OF(type1,key),CHECKED_PTR_OF(type2,base), \
+ num,sizeof(type2), \
+ ((void)CHECKED_PTR_OF(type1,cmp##_type_1), \
+ (void)type_2=CHECKED_PTR_OF(type2,cmp##_type_2), \
+ cmp##_BSEARCH_CMP_FN)),flags)
+
+int OBJ_new_nid(int num);
+int OBJ_add_object(const ASN1_OBJECT *obj);
+int OBJ_create(const char *oid, const char *sn, const char *ln);
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OBJ_cleanup() while(0) continue
+#endif
+int OBJ_create_objects(BIO *in);
+
+size_t OBJ_length(const ASN1_OBJECT *obj);
+const unsigned char *OBJ_get0_data(const ASN1_OBJECT *obj);
+
+int OBJ_find_sigid_algs(int signid, int *pdig_nid, int *ppkey_nid);
+int OBJ_find_sigid_by_algs(int *psignid, int dig_nid, int pkey_nid);
+int OBJ_add_sigid(int signid, int dig_id, int pkey_id);
+void OBJ_sigid_free(void);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/objectserr.h b/include/openssl/objectserr.h
new file mode 100644
index 00000000..585217f6
--- /dev/null
+++ b/include/openssl/objectserr.h
@@ -0,0 +1,28 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_OBJECTSERR_H
+# define OPENSSL_OBJECTSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * OBJ reason codes.
+ */
+# define OBJ_R_OID_EXISTS 102
+# define OBJ_R_UNKNOWN_NID 101
+# define OBJ_R_UNKNOWN_OBJECT_NAME 103
+
+#endif
diff --git a/include/openssl/ocsp.h b/include/openssl/ocsp.h
new file mode 100644
index 00000000..5688381e
--- /dev/null
+++ b/include/openssl/ocsp.h
@@ -0,0 +1,483 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\ocsp.h.in
+ *
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_OCSP_H
+# define OPENSSL_OCSP_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_OCSP_H
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/http.h>
+# include <openssl/asn1.h>
+
+/*
+ * These definitions are outside the OPENSSL_NO_OCSP guard because although for
+ * historical reasons they have OCSP_* names, they can actually be used
+ * independently of OCSP. E.g. see RFC5280
+ */
+/*-
+ * CRLReason ::= ENUMERATED {
+ * unspecified (0),
+ * keyCompromise (1),
+ * cACompromise (2),
+ * affiliationChanged (3),
+ * superseded (4),
+ * cessationOfOperation (5),
+ * certificateHold (6),
+ * -- value 7 is not used
+ * removeFromCRL (8),
+ * privilegeWithdrawn (9),
+ * aACompromise (10) }
+ */
+# define OCSP_REVOKED_STATUS_NOSTATUS -1
+# define OCSP_REVOKED_STATUS_UNSPECIFIED 0
+# define OCSP_REVOKED_STATUS_KEYCOMPROMISE 1
+# define OCSP_REVOKED_STATUS_CACOMPROMISE 2
+# define OCSP_REVOKED_STATUS_AFFILIATIONCHANGED 3
+# define OCSP_REVOKED_STATUS_SUPERSEDED 4
+# define OCSP_REVOKED_STATUS_CESSATIONOFOPERATION 5
+# define OCSP_REVOKED_STATUS_CERTIFICATEHOLD 6
+# define OCSP_REVOKED_STATUS_REMOVEFROMCRL 8
+# define OCSP_REVOKED_STATUS_PRIVILEGEWITHDRAWN 9
+# define OCSP_REVOKED_STATUS_AACOMPROMISE 10
+
+
+# ifndef OPENSSL_NO_OCSP
+
+# include <openssl/x509.h>
+# include <openssl/x509v3.h>
+# include <openssl/safestack.h>
+# include <openssl/ocsperr.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* Various flags and values */
+
+# define OCSP_DEFAULT_NONCE_LENGTH 16
+
+# define OCSP_NOCERTS 0x1
+# define OCSP_NOINTERN 0x2
+# define OCSP_NOSIGS 0x4
+# define OCSP_NOCHAIN 0x8
+# define OCSP_NOVERIFY 0x10
+# define OCSP_NOEXPLICIT 0x20
+# define OCSP_NOCASIGN 0x40
+# define OCSP_NODELEGATED 0x80
+# define OCSP_NOCHECKS 0x100
+# define OCSP_TRUSTOTHER 0x200
+# define OCSP_RESPID_KEY 0x400
+# define OCSP_NOTIME 0x800
+# define OCSP_PARTIAL_CHAIN 0x1000
+
+typedef struct ocsp_cert_id_st OCSP_CERTID;
+typedef struct ocsp_one_request_st OCSP_ONEREQ;
+typedef struct ocsp_req_info_st OCSP_REQINFO;
+typedef struct ocsp_signature_st OCSP_SIGNATURE;
+typedef struct ocsp_request_st OCSP_REQUEST;
+
+SKM_DEFINE_STACK_OF_INTERNAL(OCSP_CERTID, OCSP_CERTID, OCSP_CERTID)
+#define sk_OCSP_CERTID_num(sk) OPENSSL_sk_num(ossl_check_const_OCSP_CERTID_sk_type(sk))
+#define sk_OCSP_CERTID_value(sk, idx) ((OCSP_CERTID *)OPENSSL_sk_value(ossl_check_const_OCSP_CERTID_sk_type(sk), (idx)))
+#define sk_OCSP_CERTID_new(cmp) ((STACK_OF(OCSP_CERTID) *)OPENSSL_sk_new(ossl_check_OCSP_CERTID_compfunc_type(cmp)))
+#define sk_OCSP_CERTID_new_null() ((STACK_OF(OCSP_CERTID) *)OPENSSL_sk_new_null())
+#define sk_OCSP_CERTID_new_reserve(cmp, n) ((STACK_OF(OCSP_CERTID) *)OPENSSL_sk_new_reserve(ossl_check_OCSP_CERTID_compfunc_type(cmp), (n)))
+#define sk_OCSP_CERTID_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OCSP_CERTID_sk_type(sk), (n))
+#define sk_OCSP_CERTID_free(sk) OPENSSL_sk_free(ossl_check_OCSP_CERTID_sk_type(sk))
+#define sk_OCSP_CERTID_zero(sk) OPENSSL_sk_zero(ossl_check_OCSP_CERTID_sk_type(sk))
+#define sk_OCSP_CERTID_delete(sk, i) ((OCSP_CERTID *)OPENSSL_sk_delete(ossl_check_OCSP_CERTID_sk_type(sk), (i)))
+#define sk_OCSP_CERTID_delete_ptr(sk, ptr) ((OCSP_CERTID *)OPENSSL_sk_delete_ptr(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_type(ptr)))
+#define sk_OCSP_CERTID_push(sk, ptr) OPENSSL_sk_push(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_type(ptr))
+#define sk_OCSP_CERTID_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_type(ptr))
+#define sk_OCSP_CERTID_pop(sk) ((OCSP_CERTID *)OPENSSL_sk_pop(ossl_check_OCSP_CERTID_sk_type(sk)))
+#define sk_OCSP_CERTID_shift(sk) ((OCSP_CERTID *)OPENSSL_sk_shift(ossl_check_OCSP_CERTID_sk_type(sk)))
+#define sk_OCSP_CERTID_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OCSP_CERTID_sk_type(sk),ossl_check_OCSP_CERTID_freefunc_type(freefunc))
+#define sk_OCSP_CERTID_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_type(ptr), (idx))
+#define sk_OCSP_CERTID_set(sk, idx, ptr) ((OCSP_CERTID *)OPENSSL_sk_set(ossl_check_OCSP_CERTID_sk_type(sk), (idx), ossl_check_OCSP_CERTID_type(ptr)))
+#define sk_OCSP_CERTID_find(sk, ptr) OPENSSL_sk_find(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_type(ptr))
+#define sk_OCSP_CERTID_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_type(ptr))
+#define sk_OCSP_CERTID_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_type(ptr), pnum)
+#define sk_OCSP_CERTID_sort(sk) OPENSSL_sk_sort(ossl_check_OCSP_CERTID_sk_type(sk))
+#define sk_OCSP_CERTID_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OCSP_CERTID_sk_type(sk))
+#define sk_OCSP_CERTID_dup(sk) ((STACK_OF(OCSP_CERTID) *)OPENSSL_sk_dup(ossl_check_const_OCSP_CERTID_sk_type(sk)))
+#define sk_OCSP_CERTID_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OCSP_CERTID) *)OPENSSL_sk_deep_copy(ossl_check_const_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_copyfunc_type(copyfunc), ossl_check_OCSP_CERTID_freefunc_type(freefunc)))
+#define sk_OCSP_CERTID_set_cmp_func(sk, cmp) ((sk_OCSP_CERTID_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OCSP_CERTID_sk_type(sk), ossl_check_OCSP_CERTID_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(OCSP_ONEREQ, OCSP_ONEREQ, OCSP_ONEREQ)
+#define sk_OCSP_ONEREQ_num(sk) OPENSSL_sk_num(ossl_check_const_OCSP_ONEREQ_sk_type(sk))
+#define sk_OCSP_ONEREQ_value(sk, idx) ((OCSP_ONEREQ *)OPENSSL_sk_value(ossl_check_const_OCSP_ONEREQ_sk_type(sk), (idx)))
+#define sk_OCSP_ONEREQ_new(cmp) ((STACK_OF(OCSP_ONEREQ) *)OPENSSL_sk_new(ossl_check_OCSP_ONEREQ_compfunc_type(cmp)))
+#define sk_OCSP_ONEREQ_new_null() ((STACK_OF(OCSP_ONEREQ) *)OPENSSL_sk_new_null())
+#define sk_OCSP_ONEREQ_new_reserve(cmp, n) ((STACK_OF(OCSP_ONEREQ) *)OPENSSL_sk_new_reserve(ossl_check_OCSP_ONEREQ_compfunc_type(cmp), (n)))
+#define sk_OCSP_ONEREQ_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OCSP_ONEREQ_sk_type(sk), (n))
+#define sk_OCSP_ONEREQ_free(sk) OPENSSL_sk_free(ossl_check_OCSP_ONEREQ_sk_type(sk))
+#define sk_OCSP_ONEREQ_zero(sk) OPENSSL_sk_zero(ossl_check_OCSP_ONEREQ_sk_type(sk))
+#define sk_OCSP_ONEREQ_delete(sk, i) ((OCSP_ONEREQ *)OPENSSL_sk_delete(ossl_check_OCSP_ONEREQ_sk_type(sk), (i)))
+#define sk_OCSP_ONEREQ_delete_ptr(sk, ptr) ((OCSP_ONEREQ *)OPENSSL_sk_delete_ptr(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_type(ptr)))
+#define sk_OCSP_ONEREQ_push(sk, ptr) OPENSSL_sk_push(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_type(ptr))
+#define sk_OCSP_ONEREQ_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_type(ptr))
+#define sk_OCSP_ONEREQ_pop(sk) ((OCSP_ONEREQ *)OPENSSL_sk_pop(ossl_check_OCSP_ONEREQ_sk_type(sk)))
+#define sk_OCSP_ONEREQ_shift(sk) ((OCSP_ONEREQ *)OPENSSL_sk_shift(ossl_check_OCSP_ONEREQ_sk_type(sk)))
+#define sk_OCSP_ONEREQ_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OCSP_ONEREQ_sk_type(sk),ossl_check_OCSP_ONEREQ_freefunc_type(freefunc))
+#define sk_OCSP_ONEREQ_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_type(ptr), (idx))
+#define sk_OCSP_ONEREQ_set(sk, idx, ptr) ((OCSP_ONEREQ *)OPENSSL_sk_set(ossl_check_OCSP_ONEREQ_sk_type(sk), (idx), ossl_check_OCSP_ONEREQ_type(ptr)))
+#define sk_OCSP_ONEREQ_find(sk, ptr) OPENSSL_sk_find(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_type(ptr))
+#define sk_OCSP_ONEREQ_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_type(ptr))
+#define sk_OCSP_ONEREQ_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_type(ptr), pnum)
+#define sk_OCSP_ONEREQ_sort(sk) OPENSSL_sk_sort(ossl_check_OCSP_ONEREQ_sk_type(sk))
+#define sk_OCSP_ONEREQ_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OCSP_ONEREQ_sk_type(sk))
+#define sk_OCSP_ONEREQ_dup(sk) ((STACK_OF(OCSP_ONEREQ) *)OPENSSL_sk_dup(ossl_check_const_OCSP_ONEREQ_sk_type(sk)))
+#define sk_OCSP_ONEREQ_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OCSP_ONEREQ) *)OPENSSL_sk_deep_copy(ossl_check_const_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_copyfunc_type(copyfunc), ossl_check_OCSP_ONEREQ_freefunc_type(freefunc)))
+#define sk_OCSP_ONEREQ_set_cmp_func(sk, cmp) ((sk_OCSP_ONEREQ_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OCSP_ONEREQ_sk_type(sk), ossl_check_OCSP_ONEREQ_compfunc_type(cmp)))
+
+
+# define OCSP_RESPONSE_STATUS_SUCCESSFUL 0
+# define OCSP_RESPONSE_STATUS_MALFORMEDREQUEST 1
+# define OCSP_RESPONSE_STATUS_INTERNALERROR 2
+# define OCSP_RESPONSE_STATUS_TRYLATER 3
+# define OCSP_RESPONSE_STATUS_SIGREQUIRED 5
+# define OCSP_RESPONSE_STATUS_UNAUTHORIZED 6
+
+typedef struct ocsp_resp_bytes_st OCSP_RESPBYTES;
+
+# define V_OCSP_RESPID_NAME 0
+# define V_OCSP_RESPID_KEY 1
+
+SKM_DEFINE_STACK_OF_INTERNAL(OCSP_RESPID, OCSP_RESPID, OCSP_RESPID)
+#define sk_OCSP_RESPID_num(sk) OPENSSL_sk_num(ossl_check_const_OCSP_RESPID_sk_type(sk))
+#define sk_OCSP_RESPID_value(sk, idx) ((OCSP_RESPID *)OPENSSL_sk_value(ossl_check_const_OCSP_RESPID_sk_type(sk), (idx)))
+#define sk_OCSP_RESPID_new(cmp) ((STACK_OF(OCSP_RESPID) *)OPENSSL_sk_new(ossl_check_OCSP_RESPID_compfunc_type(cmp)))
+#define sk_OCSP_RESPID_new_null() ((STACK_OF(OCSP_RESPID) *)OPENSSL_sk_new_null())
+#define sk_OCSP_RESPID_new_reserve(cmp, n) ((STACK_OF(OCSP_RESPID) *)OPENSSL_sk_new_reserve(ossl_check_OCSP_RESPID_compfunc_type(cmp), (n)))
+#define sk_OCSP_RESPID_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OCSP_RESPID_sk_type(sk), (n))
+#define sk_OCSP_RESPID_free(sk) OPENSSL_sk_free(ossl_check_OCSP_RESPID_sk_type(sk))
+#define sk_OCSP_RESPID_zero(sk) OPENSSL_sk_zero(ossl_check_OCSP_RESPID_sk_type(sk))
+#define sk_OCSP_RESPID_delete(sk, i) ((OCSP_RESPID *)OPENSSL_sk_delete(ossl_check_OCSP_RESPID_sk_type(sk), (i)))
+#define sk_OCSP_RESPID_delete_ptr(sk, ptr) ((OCSP_RESPID *)OPENSSL_sk_delete_ptr(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_type(ptr)))
+#define sk_OCSP_RESPID_push(sk, ptr) OPENSSL_sk_push(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_type(ptr))
+#define sk_OCSP_RESPID_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_type(ptr))
+#define sk_OCSP_RESPID_pop(sk) ((OCSP_RESPID *)OPENSSL_sk_pop(ossl_check_OCSP_RESPID_sk_type(sk)))
+#define sk_OCSP_RESPID_shift(sk) ((OCSP_RESPID *)OPENSSL_sk_shift(ossl_check_OCSP_RESPID_sk_type(sk)))
+#define sk_OCSP_RESPID_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OCSP_RESPID_sk_type(sk),ossl_check_OCSP_RESPID_freefunc_type(freefunc))
+#define sk_OCSP_RESPID_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_type(ptr), (idx))
+#define sk_OCSP_RESPID_set(sk, idx, ptr) ((OCSP_RESPID *)OPENSSL_sk_set(ossl_check_OCSP_RESPID_sk_type(sk), (idx), ossl_check_OCSP_RESPID_type(ptr)))
+#define sk_OCSP_RESPID_find(sk, ptr) OPENSSL_sk_find(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_type(ptr))
+#define sk_OCSP_RESPID_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_type(ptr))
+#define sk_OCSP_RESPID_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_type(ptr), pnum)
+#define sk_OCSP_RESPID_sort(sk) OPENSSL_sk_sort(ossl_check_OCSP_RESPID_sk_type(sk))
+#define sk_OCSP_RESPID_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OCSP_RESPID_sk_type(sk))
+#define sk_OCSP_RESPID_dup(sk) ((STACK_OF(OCSP_RESPID) *)OPENSSL_sk_dup(ossl_check_const_OCSP_RESPID_sk_type(sk)))
+#define sk_OCSP_RESPID_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OCSP_RESPID) *)OPENSSL_sk_deep_copy(ossl_check_const_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_copyfunc_type(copyfunc), ossl_check_OCSP_RESPID_freefunc_type(freefunc)))
+#define sk_OCSP_RESPID_set_cmp_func(sk, cmp) ((sk_OCSP_RESPID_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OCSP_RESPID_sk_type(sk), ossl_check_OCSP_RESPID_compfunc_type(cmp)))
+
+
+typedef struct ocsp_revoked_info_st OCSP_REVOKEDINFO;
+
+# define V_OCSP_CERTSTATUS_GOOD 0
+# define V_OCSP_CERTSTATUS_REVOKED 1
+# define V_OCSP_CERTSTATUS_UNKNOWN 2
+
+typedef struct ocsp_cert_status_st OCSP_CERTSTATUS;
+typedef struct ocsp_single_response_st OCSP_SINGLERESP;
+
+SKM_DEFINE_STACK_OF_INTERNAL(OCSP_SINGLERESP, OCSP_SINGLERESP, OCSP_SINGLERESP)
+#define sk_OCSP_SINGLERESP_num(sk) OPENSSL_sk_num(ossl_check_const_OCSP_SINGLERESP_sk_type(sk))
+#define sk_OCSP_SINGLERESP_value(sk, idx) ((OCSP_SINGLERESP *)OPENSSL_sk_value(ossl_check_const_OCSP_SINGLERESP_sk_type(sk), (idx)))
+#define sk_OCSP_SINGLERESP_new(cmp) ((STACK_OF(OCSP_SINGLERESP) *)OPENSSL_sk_new(ossl_check_OCSP_SINGLERESP_compfunc_type(cmp)))
+#define sk_OCSP_SINGLERESP_new_null() ((STACK_OF(OCSP_SINGLERESP) *)OPENSSL_sk_new_null())
+#define sk_OCSP_SINGLERESP_new_reserve(cmp, n) ((STACK_OF(OCSP_SINGLERESP) *)OPENSSL_sk_new_reserve(ossl_check_OCSP_SINGLERESP_compfunc_type(cmp), (n)))
+#define sk_OCSP_SINGLERESP_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OCSP_SINGLERESP_sk_type(sk), (n))
+#define sk_OCSP_SINGLERESP_free(sk) OPENSSL_sk_free(ossl_check_OCSP_SINGLERESP_sk_type(sk))
+#define sk_OCSP_SINGLERESP_zero(sk) OPENSSL_sk_zero(ossl_check_OCSP_SINGLERESP_sk_type(sk))
+#define sk_OCSP_SINGLERESP_delete(sk, i) ((OCSP_SINGLERESP *)OPENSSL_sk_delete(ossl_check_OCSP_SINGLERESP_sk_type(sk), (i)))
+#define sk_OCSP_SINGLERESP_delete_ptr(sk, ptr) ((OCSP_SINGLERESP *)OPENSSL_sk_delete_ptr(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_type(ptr)))
+#define sk_OCSP_SINGLERESP_push(sk, ptr) OPENSSL_sk_push(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_type(ptr))
+#define sk_OCSP_SINGLERESP_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_type(ptr))
+#define sk_OCSP_SINGLERESP_pop(sk) ((OCSP_SINGLERESP *)OPENSSL_sk_pop(ossl_check_OCSP_SINGLERESP_sk_type(sk)))
+#define sk_OCSP_SINGLERESP_shift(sk) ((OCSP_SINGLERESP *)OPENSSL_sk_shift(ossl_check_OCSP_SINGLERESP_sk_type(sk)))
+#define sk_OCSP_SINGLERESP_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OCSP_SINGLERESP_sk_type(sk),ossl_check_OCSP_SINGLERESP_freefunc_type(freefunc))
+#define sk_OCSP_SINGLERESP_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_type(ptr), (idx))
+#define sk_OCSP_SINGLERESP_set(sk, idx, ptr) ((OCSP_SINGLERESP *)OPENSSL_sk_set(ossl_check_OCSP_SINGLERESP_sk_type(sk), (idx), ossl_check_OCSP_SINGLERESP_type(ptr)))
+#define sk_OCSP_SINGLERESP_find(sk, ptr) OPENSSL_sk_find(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_type(ptr))
+#define sk_OCSP_SINGLERESP_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_type(ptr))
+#define sk_OCSP_SINGLERESP_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_type(ptr), pnum)
+#define sk_OCSP_SINGLERESP_sort(sk) OPENSSL_sk_sort(ossl_check_OCSP_SINGLERESP_sk_type(sk))
+#define sk_OCSP_SINGLERESP_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OCSP_SINGLERESP_sk_type(sk))
+#define sk_OCSP_SINGLERESP_dup(sk) ((STACK_OF(OCSP_SINGLERESP) *)OPENSSL_sk_dup(ossl_check_const_OCSP_SINGLERESP_sk_type(sk)))
+#define sk_OCSP_SINGLERESP_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OCSP_SINGLERESP) *)OPENSSL_sk_deep_copy(ossl_check_const_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_copyfunc_type(copyfunc), ossl_check_OCSP_SINGLERESP_freefunc_type(freefunc)))
+#define sk_OCSP_SINGLERESP_set_cmp_func(sk, cmp) ((sk_OCSP_SINGLERESP_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OCSP_SINGLERESP_sk_type(sk), ossl_check_OCSP_SINGLERESP_compfunc_type(cmp)))
+
+
+typedef struct ocsp_response_data_st OCSP_RESPDATA;
+
+typedef struct ocsp_basic_response_st OCSP_BASICRESP;
+
+typedef struct ocsp_crl_id_st OCSP_CRLID;
+typedef struct ocsp_service_locator_st OCSP_SERVICELOC;
+
+# define PEM_STRING_OCSP_REQUEST "OCSP REQUEST"
+# define PEM_STRING_OCSP_RESPONSE "OCSP RESPONSE"
+
+# define d2i_OCSP_REQUEST_bio(bp,p) ASN1_d2i_bio_of(OCSP_REQUEST,OCSP_REQUEST_new,d2i_OCSP_REQUEST,bp,p)
+
+# define d2i_OCSP_RESPONSE_bio(bp,p) ASN1_d2i_bio_of(OCSP_RESPONSE,OCSP_RESPONSE_new,d2i_OCSP_RESPONSE,bp,p)
+
+# define PEM_read_bio_OCSP_REQUEST(bp,x,cb) (OCSP_REQUEST *)PEM_ASN1_read_bio( \
+ (char *(*)())d2i_OCSP_REQUEST,PEM_STRING_OCSP_REQUEST, \
+ bp,(char **)(x),cb,NULL)
+
+# define PEM_read_bio_OCSP_RESPONSE(bp,x,cb) (OCSP_RESPONSE *)PEM_ASN1_read_bio(\
+ (char *(*)())d2i_OCSP_RESPONSE,PEM_STRING_OCSP_RESPONSE, \
+ bp,(char **)(x),cb,NULL)
+
+# define PEM_write_bio_OCSP_REQUEST(bp,o) \
+ PEM_ASN1_write_bio((int (*)())i2d_OCSP_REQUEST,PEM_STRING_OCSP_REQUEST,\
+ bp,(char *)(o), NULL,NULL,0,NULL,NULL)
+
+# define PEM_write_bio_OCSP_RESPONSE(bp,o) \
+ PEM_ASN1_write_bio((int (*)())i2d_OCSP_RESPONSE,PEM_STRING_OCSP_RESPONSE,\
+ bp,(char *)(o), NULL,NULL,0,NULL,NULL)
+
+# define i2d_OCSP_RESPONSE_bio(bp,o) ASN1_i2d_bio_of(OCSP_RESPONSE,i2d_OCSP_RESPONSE,bp,o)
+
+# define i2d_OCSP_REQUEST_bio(bp,o) ASN1_i2d_bio_of(OCSP_REQUEST,i2d_OCSP_REQUEST,bp,o)
+
+# define ASN1_BIT_STRING_digest(data,type,md,len) \
+ ASN1_item_digest(ASN1_ITEM_rptr(ASN1_BIT_STRING),type,data,md,len)
+
+# define OCSP_CERTSTATUS_dup(cs)\
+ (OCSP_CERTSTATUS*)ASN1_dup((i2d_of_void *)i2d_OCSP_CERTSTATUS,\
+ (d2i_of_void *)d2i_OCSP_CERTSTATUS,(char *)(cs))
+
+DECLARE_ASN1_DUP_FUNCTION(OCSP_CERTID)
+
+OSSL_HTTP_REQ_CTX *OCSP_sendreq_new(BIO *io, const char *path,
+ const OCSP_REQUEST *req, int buf_size);
+OCSP_RESPONSE *OCSP_sendreq_bio(BIO *b, const char *path, OCSP_REQUEST *req);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef OSSL_HTTP_REQ_CTX OCSP_REQ_CTX;
+# define OCSP_REQ_CTX_new(io, buf_size) \
+ OSSL_HTTP_REQ_CTX_new(io, io, buf_size)
+# define OCSP_REQ_CTX_free OSSL_HTTP_REQ_CTX_free
+# define OCSP_REQ_CTX_http(rctx, op, path) \
+ (OSSL_HTTP_REQ_CTX_set_expected(rctx, NULL, 1 /* asn1 */, 0, 0) && \
+ OSSL_HTTP_REQ_CTX_set_request_line(rctx, strcmp(op, "POST") == 0, \
+ NULL, NULL, path))
+# define OCSP_REQ_CTX_add1_header OSSL_HTTP_REQ_CTX_add1_header
+# define OCSP_REQ_CTX_i2d(r, it, req) \
+ OSSL_HTTP_REQ_CTX_set1_req(r, "application/ocsp-request", it, req)
+# define OCSP_REQ_CTX_set1_req(r, req) \
+ OCSP_REQ_CTX_i2d(r, ASN1_ITEM_rptr(OCSP_REQUEST), (ASN1_VALUE *)(req))
+# define OCSP_REQ_CTX_nbio OSSL_HTTP_REQ_CTX_nbio
+# define OCSP_REQ_CTX_nbio_d2i OSSL_HTTP_REQ_CTX_nbio_d2i
+# define OCSP_sendreq_nbio(p, r) \
+ OSSL_HTTP_REQ_CTX_nbio_d2i(r, (ASN1_VALUE **)(p), \
+ ASN1_ITEM_rptr(OCSP_RESPONSE))
+# define OCSP_REQ_CTX_get0_mem_bio OSSL_HTTP_REQ_CTX_get0_mem_bio
+# define OCSP_set_max_response_length OSSL_HTTP_REQ_CTX_set_max_response_length
+# endif
+
+OCSP_CERTID *OCSP_cert_to_id(const EVP_MD *dgst, const X509 *subject,
+ const X509 *issuer);
+
+OCSP_CERTID *OCSP_cert_id_new(const EVP_MD *dgst,
+ const X509_NAME *issuerName,
+ const ASN1_BIT_STRING *issuerKey,
+ const ASN1_INTEGER *serialNumber);
+
+OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid);
+
+int OCSP_request_add1_nonce(OCSP_REQUEST *req, unsigned char *val, int len);
+int OCSP_basic_add1_nonce(OCSP_BASICRESP *resp, unsigned char *val, int len);
+int OCSP_check_nonce(OCSP_REQUEST *req, OCSP_BASICRESP *bs);
+int OCSP_copy_nonce(OCSP_BASICRESP *resp, OCSP_REQUEST *req);
+
+int OCSP_request_set1_name(OCSP_REQUEST *req, const X509_NAME *nm);
+int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert);
+
+int OCSP_request_sign(OCSP_REQUEST *req,
+ X509 *signer,
+ EVP_PKEY *key,
+ const EVP_MD *dgst,
+ STACK_OF(X509) *certs, unsigned long flags);
+
+int OCSP_response_status(OCSP_RESPONSE *resp);
+OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp);
+
+const ASN1_OCTET_STRING *OCSP_resp_get0_signature(const OCSP_BASICRESP *bs);
+const X509_ALGOR *OCSP_resp_get0_tbs_sigalg(const OCSP_BASICRESP *bs);
+const OCSP_RESPDATA *OCSP_resp_get0_respdata(const OCSP_BASICRESP *bs);
+int OCSP_resp_get0_signer(OCSP_BASICRESP *bs, X509 **signer,
+ STACK_OF(X509) *extra_certs);
+
+int OCSP_resp_count(OCSP_BASICRESP *bs);
+OCSP_SINGLERESP *OCSP_resp_get0(OCSP_BASICRESP *bs, int idx);
+const ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(const OCSP_BASICRESP* bs);
+const STACK_OF(X509) *OCSP_resp_get0_certs(const OCSP_BASICRESP *bs);
+int OCSP_resp_get0_id(const OCSP_BASICRESP *bs,
+ const ASN1_OCTET_STRING **pid,
+ const X509_NAME **pname);
+int OCSP_resp_get1_id(const OCSP_BASICRESP *bs,
+ ASN1_OCTET_STRING **pid,
+ X509_NAME **pname);
+
+int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last);
+int OCSP_single_get0_status(OCSP_SINGLERESP *single, int *reason,
+ ASN1_GENERALIZEDTIME **revtime,
+ ASN1_GENERALIZEDTIME **thisupd,
+ ASN1_GENERALIZEDTIME **nextupd);
+int OCSP_resp_find_status(OCSP_BASICRESP *bs, OCSP_CERTID *id, int *status,
+ int *reason,
+ ASN1_GENERALIZEDTIME **revtime,
+ ASN1_GENERALIZEDTIME **thisupd,
+ ASN1_GENERALIZEDTIME **nextupd);
+int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd,
+ ASN1_GENERALIZEDTIME *nextupd, long sec, long maxsec);
+
+int OCSP_request_verify(OCSP_REQUEST *req, STACK_OF(X509) *certs,
+ X509_STORE *store, unsigned long flags);
+
+# define OCSP_parse_url(url, host, port, path, ssl) \
+ OSSL_HTTP_parse_url(url, ssl, NULL, host, port, NULL, path, NULL, NULL)
+
+int OCSP_id_issuer_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b);
+int OCSP_id_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b);
+
+int OCSP_request_onereq_count(OCSP_REQUEST *req);
+OCSP_ONEREQ *OCSP_request_onereq_get0(OCSP_REQUEST *req, int i);
+OCSP_CERTID *OCSP_onereq_get0_id(OCSP_ONEREQ *one);
+int OCSP_id_get0_info(ASN1_OCTET_STRING **piNameHash, ASN1_OBJECT **pmd,
+ ASN1_OCTET_STRING **pikeyHash,
+ ASN1_INTEGER **pserial, OCSP_CERTID *cid);
+int OCSP_request_is_signed(OCSP_REQUEST *req);
+OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs);
+OCSP_SINGLERESP *OCSP_basic_add1_status(OCSP_BASICRESP *rsp,
+ OCSP_CERTID *cid,
+ int status, int reason,
+ ASN1_TIME *revtime,
+ ASN1_TIME *thisupd,
+ ASN1_TIME *nextupd);
+int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert);
+int OCSP_basic_sign(OCSP_BASICRESP *brsp,
+ X509 *signer, EVP_PKEY *key, const EVP_MD *dgst,
+ STACK_OF(X509) *certs, unsigned long flags);
+int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp,
+ X509 *signer, EVP_MD_CTX *ctx,
+ STACK_OF(X509) *certs, unsigned long flags);
+int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert);
+int OCSP_RESPID_set_by_key_ex(OCSP_RESPID *respid, X509 *cert,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert);
+int OCSP_RESPID_match_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert);
+
+X509_EXTENSION *OCSP_crlID_new(const char *url, long *n, char *tim);
+
+X509_EXTENSION *OCSP_accept_responses_new(char **oids);
+
+X509_EXTENSION *OCSP_archive_cutoff_new(char *tim);
+
+X509_EXTENSION *OCSP_url_svcloc_new(const X509_NAME *issuer, const char **urls);
+
+int OCSP_REQUEST_get_ext_count(OCSP_REQUEST *x);
+int OCSP_REQUEST_get_ext_by_NID(OCSP_REQUEST *x, int nid, int lastpos);
+int OCSP_REQUEST_get_ext_by_OBJ(OCSP_REQUEST *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int OCSP_REQUEST_get_ext_by_critical(OCSP_REQUEST *x, int crit, int lastpos);
+X509_EXTENSION *OCSP_REQUEST_get_ext(OCSP_REQUEST *x, int loc);
+X509_EXTENSION *OCSP_REQUEST_delete_ext(OCSP_REQUEST *x, int loc);
+void *OCSP_REQUEST_get1_ext_d2i(OCSP_REQUEST *x, int nid, int *crit,
+ int *idx);
+int OCSP_REQUEST_add1_ext_i2d(OCSP_REQUEST *x, int nid, void *value, int crit,
+ unsigned long flags);
+int OCSP_REQUEST_add_ext(OCSP_REQUEST *x, X509_EXTENSION *ex, int loc);
+
+int OCSP_ONEREQ_get_ext_count(OCSP_ONEREQ *x);
+int OCSP_ONEREQ_get_ext_by_NID(OCSP_ONEREQ *x, int nid, int lastpos);
+int OCSP_ONEREQ_get_ext_by_OBJ(OCSP_ONEREQ *x, const ASN1_OBJECT *obj, int lastpos);
+int OCSP_ONEREQ_get_ext_by_critical(OCSP_ONEREQ *x, int crit, int lastpos);
+X509_EXTENSION *OCSP_ONEREQ_get_ext(OCSP_ONEREQ *x, int loc);
+X509_EXTENSION *OCSP_ONEREQ_delete_ext(OCSP_ONEREQ *x, int loc);
+void *OCSP_ONEREQ_get1_ext_d2i(OCSP_ONEREQ *x, int nid, int *crit, int *idx);
+int OCSP_ONEREQ_add1_ext_i2d(OCSP_ONEREQ *x, int nid, void *value, int crit,
+ unsigned long flags);
+int OCSP_ONEREQ_add_ext(OCSP_ONEREQ *x, X509_EXTENSION *ex, int loc);
+
+int OCSP_BASICRESP_get_ext_count(OCSP_BASICRESP *x);
+int OCSP_BASICRESP_get_ext_by_NID(OCSP_BASICRESP *x, int nid, int lastpos);
+int OCSP_BASICRESP_get_ext_by_OBJ(OCSP_BASICRESP *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int OCSP_BASICRESP_get_ext_by_critical(OCSP_BASICRESP *x, int crit,
+ int lastpos);
+X509_EXTENSION *OCSP_BASICRESP_get_ext(OCSP_BASICRESP *x, int loc);
+X509_EXTENSION *OCSP_BASICRESP_delete_ext(OCSP_BASICRESP *x, int loc);
+void *OCSP_BASICRESP_get1_ext_d2i(OCSP_BASICRESP *x, int nid, int *crit,
+ int *idx);
+int OCSP_BASICRESP_add1_ext_i2d(OCSP_BASICRESP *x, int nid, void *value,
+ int crit, unsigned long flags);
+int OCSP_BASICRESP_add_ext(OCSP_BASICRESP *x, X509_EXTENSION *ex, int loc);
+
+int OCSP_SINGLERESP_get_ext_count(OCSP_SINGLERESP *x);
+int OCSP_SINGLERESP_get_ext_by_NID(OCSP_SINGLERESP *x, int nid, int lastpos);
+int OCSP_SINGLERESP_get_ext_by_OBJ(OCSP_SINGLERESP *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int OCSP_SINGLERESP_get_ext_by_critical(OCSP_SINGLERESP *x, int crit,
+ int lastpos);
+X509_EXTENSION *OCSP_SINGLERESP_get_ext(OCSP_SINGLERESP *x, int loc);
+X509_EXTENSION *OCSP_SINGLERESP_delete_ext(OCSP_SINGLERESP *x, int loc);
+void *OCSP_SINGLERESP_get1_ext_d2i(OCSP_SINGLERESP *x, int nid, int *crit,
+ int *idx);
+int OCSP_SINGLERESP_add1_ext_i2d(OCSP_SINGLERESP *x, int nid, void *value,
+ int crit, unsigned long flags);
+int OCSP_SINGLERESP_add_ext(OCSP_SINGLERESP *x, X509_EXTENSION *ex, int loc);
+const OCSP_CERTID *OCSP_SINGLERESP_get0_id(const OCSP_SINGLERESP *x);
+
+DECLARE_ASN1_FUNCTIONS(OCSP_SINGLERESP)
+DECLARE_ASN1_FUNCTIONS(OCSP_CERTSTATUS)
+DECLARE_ASN1_FUNCTIONS(OCSP_REVOKEDINFO)
+DECLARE_ASN1_FUNCTIONS(OCSP_BASICRESP)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPDATA)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPID)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPONSE)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPBYTES)
+DECLARE_ASN1_FUNCTIONS(OCSP_ONEREQ)
+DECLARE_ASN1_FUNCTIONS(OCSP_CERTID)
+DECLARE_ASN1_FUNCTIONS(OCSP_REQUEST)
+DECLARE_ASN1_FUNCTIONS(OCSP_SIGNATURE)
+DECLARE_ASN1_FUNCTIONS(OCSP_REQINFO)
+DECLARE_ASN1_FUNCTIONS(OCSP_CRLID)
+DECLARE_ASN1_FUNCTIONS(OCSP_SERVICELOC)
+
+const char *OCSP_response_status_str(long s);
+const char *OCSP_cert_status_str(long s);
+const char *OCSP_crl_reason_str(long s);
+
+int OCSP_REQUEST_print(BIO *bp, OCSP_REQUEST *a, unsigned long flags);
+int OCSP_RESPONSE_print(BIO *bp, OCSP_RESPONSE *o, unsigned long flags);
+
+int OCSP_basic_verify(OCSP_BASICRESP *bs, STACK_OF(X509) *certs,
+ X509_STORE *st, unsigned long flags);
+
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* !defined(OPENSSL_NO_OCSP) */
+#endif
diff --git a/include/openssl/ocsp.h.in b/include/openssl/ocsp.h.in
new file mode 100644
index 00000000..e2cc2716
--- /dev/null
+++ b/include/openssl/ocsp.h.in
@@ -0,0 +1,387 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2000-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_OCSP_H
+# define OPENSSL_OCSP_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_OCSP_H
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/http.h>
+# include <openssl/asn1.h>
+
+/*
+ * These definitions are outside the OPENSSL_NO_OCSP guard because although for
+ * historical reasons they have OCSP_* names, they can actually be used
+ * independently of OCSP. E.g. see RFC5280
+ */
+/*-
+ * CRLReason ::= ENUMERATED {
+ * unspecified (0),
+ * keyCompromise (1),
+ * cACompromise (2),
+ * affiliationChanged (3),
+ * superseded (4),
+ * cessationOfOperation (5),
+ * certificateHold (6),
+ * -- value 7 is not used
+ * removeFromCRL (8),
+ * privilegeWithdrawn (9),
+ * aACompromise (10) }
+ */
+# define OCSP_REVOKED_STATUS_NOSTATUS -1
+# define OCSP_REVOKED_STATUS_UNSPECIFIED 0
+# define OCSP_REVOKED_STATUS_KEYCOMPROMISE 1
+# define OCSP_REVOKED_STATUS_CACOMPROMISE 2
+# define OCSP_REVOKED_STATUS_AFFILIATIONCHANGED 3
+# define OCSP_REVOKED_STATUS_SUPERSEDED 4
+# define OCSP_REVOKED_STATUS_CESSATIONOFOPERATION 5
+# define OCSP_REVOKED_STATUS_CERTIFICATEHOLD 6
+# define OCSP_REVOKED_STATUS_REMOVEFROMCRL 8
+# define OCSP_REVOKED_STATUS_PRIVILEGEWITHDRAWN 9
+# define OCSP_REVOKED_STATUS_AACOMPROMISE 10
+
+
+# ifndef OPENSSL_NO_OCSP
+
+# include <openssl/x509.h>
+# include <openssl/x509v3.h>
+# include <openssl/safestack.h>
+# include <openssl/ocsperr.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* Various flags and values */
+
+# define OCSP_DEFAULT_NONCE_LENGTH 16
+
+# define OCSP_NOCERTS 0x1
+# define OCSP_NOINTERN 0x2
+# define OCSP_NOSIGS 0x4
+# define OCSP_NOCHAIN 0x8
+# define OCSP_NOVERIFY 0x10
+# define OCSP_NOEXPLICIT 0x20
+# define OCSP_NOCASIGN 0x40
+# define OCSP_NODELEGATED 0x80
+# define OCSP_NOCHECKS 0x100
+# define OCSP_TRUSTOTHER 0x200
+# define OCSP_RESPID_KEY 0x400
+# define OCSP_NOTIME 0x800
+# define OCSP_PARTIAL_CHAIN 0x1000
+
+typedef struct ocsp_cert_id_st OCSP_CERTID;
+typedef struct ocsp_one_request_st OCSP_ONEREQ;
+typedef struct ocsp_req_info_st OCSP_REQINFO;
+typedef struct ocsp_signature_st OCSP_SIGNATURE;
+typedef struct ocsp_request_st OCSP_REQUEST;
+
+{-
+ generate_stack_macros("OCSP_CERTID")
+ .generate_stack_macros("OCSP_ONEREQ");
+-}
+
+# define OCSP_RESPONSE_STATUS_SUCCESSFUL 0
+# define OCSP_RESPONSE_STATUS_MALFORMEDREQUEST 1
+# define OCSP_RESPONSE_STATUS_INTERNALERROR 2
+# define OCSP_RESPONSE_STATUS_TRYLATER 3
+# define OCSP_RESPONSE_STATUS_SIGREQUIRED 5
+# define OCSP_RESPONSE_STATUS_UNAUTHORIZED 6
+
+typedef struct ocsp_resp_bytes_st OCSP_RESPBYTES;
+
+# define V_OCSP_RESPID_NAME 0
+# define V_OCSP_RESPID_KEY 1
+
+{-
+ generate_stack_macros("OCSP_RESPID");
+-}
+
+typedef struct ocsp_revoked_info_st OCSP_REVOKEDINFO;
+
+# define V_OCSP_CERTSTATUS_GOOD 0
+# define V_OCSP_CERTSTATUS_REVOKED 1
+# define V_OCSP_CERTSTATUS_UNKNOWN 2
+
+typedef struct ocsp_cert_status_st OCSP_CERTSTATUS;
+typedef struct ocsp_single_response_st OCSP_SINGLERESP;
+
+{-
+ generate_stack_macros("OCSP_SINGLERESP");
+-}
+
+typedef struct ocsp_response_data_st OCSP_RESPDATA;
+
+typedef struct ocsp_basic_response_st OCSP_BASICRESP;
+
+typedef struct ocsp_crl_id_st OCSP_CRLID;
+typedef struct ocsp_service_locator_st OCSP_SERVICELOC;
+
+# define PEM_STRING_OCSP_REQUEST "OCSP REQUEST"
+# define PEM_STRING_OCSP_RESPONSE "OCSP RESPONSE"
+
+# define d2i_OCSP_REQUEST_bio(bp,p) ASN1_d2i_bio_of(OCSP_REQUEST,OCSP_REQUEST_new,d2i_OCSP_REQUEST,bp,p)
+
+# define d2i_OCSP_RESPONSE_bio(bp,p) ASN1_d2i_bio_of(OCSP_RESPONSE,OCSP_RESPONSE_new,d2i_OCSP_RESPONSE,bp,p)
+
+# define PEM_read_bio_OCSP_REQUEST(bp,x,cb) (OCSP_REQUEST *)PEM_ASN1_read_bio( \
+ (char *(*)())d2i_OCSP_REQUEST,PEM_STRING_OCSP_REQUEST, \
+ bp,(char **)(x),cb,NULL)
+
+# define PEM_read_bio_OCSP_RESPONSE(bp,x,cb) (OCSP_RESPONSE *)PEM_ASN1_read_bio(\
+ (char *(*)())d2i_OCSP_RESPONSE,PEM_STRING_OCSP_RESPONSE, \
+ bp,(char **)(x),cb,NULL)
+
+# define PEM_write_bio_OCSP_REQUEST(bp,o) \
+ PEM_ASN1_write_bio((int (*)())i2d_OCSP_REQUEST,PEM_STRING_OCSP_REQUEST,\
+ bp,(char *)(o), NULL,NULL,0,NULL,NULL)
+
+# define PEM_write_bio_OCSP_RESPONSE(bp,o) \
+ PEM_ASN1_write_bio((int (*)())i2d_OCSP_RESPONSE,PEM_STRING_OCSP_RESPONSE,\
+ bp,(char *)(o), NULL,NULL,0,NULL,NULL)
+
+# define i2d_OCSP_RESPONSE_bio(bp,o) ASN1_i2d_bio_of(OCSP_RESPONSE,i2d_OCSP_RESPONSE,bp,o)
+
+# define i2d_OCSP_REQUEST_bio(bp,o) ASN1_i2d_bio_of(OCSP_REQUEST,i2d_OCSP_REQUEST,bp,o)
+
+# define ASN1_BIT_STRING_digest(data,type,md,len) \
+ ASN1_item_digest(ASN1_ITEM_rptr(ASN1_BIT_STRING),type,data,md,len)
+
+# define OCSP_CERTSTATUS_dup(cs)\
+ (OCSP_CERTSTATUS*)ASN1_dup((i2d_of_void *)i2d_OCSP_CERTSTATUS,\
+ (d2i_of_void *)d2i_OCSP_CERTSTATUS,(char *)(cs))
+
+DECLARE_ASN1_DUP_FUNCTION(OCSP_CERTID)
+
+OSSL_HTTP_REQ_CTX *OCSP_sendreq_new(BIO *io, const char *path,
+ const OCSP_REQUEST *req, int buf_size);
+OCSP_RESPONSE *OCSP_sendreq_bio(BIO *b, const char *path, OCSP_REQUEST *req);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef OSSL_HTTP_REQ_CTX OCSP_REQ_CTX;
+# define OCSP_REQ_CTX_new(io, buf_size) \
+ OSSL_HTTP_REQ_CTX_new(io, io, buf_size)
+# define OCSP_REQ_CTX_free OSSL_HTTP_REQ_CTX_free
+# define OCSP_REQ_CTX_http(rctx, op, path) \
+ (OSSL_HTTP_REQ_CTX_set_expected(rctx, NULL, 1 /* asn1 */, 0, 0) && \
+ OSSL_HTTP_REQ_CTX_set_request_line(rctx, strcmp(op, "POST") == 0, \
+ NULL, NULL, path))
+# define OCSP_REQ_CTX_add1_header OSSL_HTTP_REQ_CTX_add1_header
+# define OCSP_REQ_CTX_i2d(r, it, req) \
+ OSSL_HTTP_REQ_CTX_set1_req(r, "application/ocsp-request", it, req)
+# define OCSP_REQ_CTX_set1_req(r, req) \
+ OCSP_REQ_CTX_i2d(r, ASN1_ITEM_rptr(OCSP_REQUEST), (ASN1_VALUE *)(req))
+# define OCSP_REQ_CTX_nbio OSSL_HTTP_REQ_CTX_nbio
+# define OCSP_REQ_CTX_nbio_d2i OSSL_HTTP_REQ_CTX_nbio_d2i
+# define OCSP_sendreq_nbio(p, r) \
+ OSSL_HTTP_REQ_CTX_nbio_d2i(r, (ASN1_VALUE **)(p), \
+ ASN1_ITEM_rptr(OCSP_RESPONSE))
+# define OCSP_REQ_CTX_get0_mem_bio OSSL_HTTP_REQ_CTX_get0_mem_bio
+# define OCSP_set_max_response_length OSSL_HTTP_REQ_CTX_set_max_response_length
+# endif
+
+OCSP_CERTID *OCSP_cert_to_id(const EVP_MD *dgst, const X509 *subject,
+ const X509 *issuer);
+
+OCSP_CERTID *OCSP_cert_id_new(const EVP_MD *dgst,
+ const X509_NAME *issuerName,
+ const ASN1_BIT_STRING *issuerKey,
+ const ASN1_INTEGER *serialNumber);
+
+OCSP_ONEREQ *OCSP_request_add0_id(OCSP_REQUEST *req, OCSP_CERTID *cid);
+
+int OCSP_request_add1_nonce(OCSP_REQUEST *req, unsigned char *val, int len);
+int OCSP_basic_add1_nonce(OCSP_BASICRESP *resp, unsigned char *val, int len);
+int OCSP_check_nonce(OCSP_REQUEST *req, OCSP_BASICRESP *bs);
+int OCSP_copy_nonce(OCSP_BASICRESP *resp, OCSP_REQUEST *req);
+
+int OCSP_request_set1_name(OCSP_REQUEST *req, const X509_NAME *nm);
+int OCSP_request_add1_cert(OCSP_REQUEST *req, X509 *cert);
+
+int OCSP_request_sign(OCSP_REQUEST *req,
+ X509 *signer,
+ EVP_PKEY *key,
+ const EVP_MD *dgst,
+ STACK_OF(X509) *certs, unsigned long flags);
+
+int OCSP_response_status(OCSP_RESPONSE *resp);
+OCSP_BASICRESP *OCSP_response_get1_basic(OCSP_RESPONSE *resp);
+
+const ASN1_OCTET_STRING *OCSP_resp_get0_signature(const OCSP_BASICRESP *bs);
+const X509_ALGOR *OCSP_resp_get0_tbs_sigalg(const OCSP_BASICRESP *bs);
+const OCSP_RESPDATA *OCSP_resp_get0_respdata(const OCSP_BASICRESP *bs);
+int OCSP_resp_get0_signer(OCSP_BASICRESP *bs, X509 **signer,
+ STACK_OF(X509) *extra_certs);
+
+int OCSP_resp_count(OCSP_BASICRESP *bs);
+OCSP_SINGLERESP *OCSP_resp_get0(OCSP_BASICRESP *bs, int idx);
+const ASN1_GENERALIZEDTIME *OCSP_resp_get0_produced_at(const OCSP_BASICRESP* bs);
+const STACK_OF(X509) *OCSP_resp_get0_certs(const OCSP_BASICRESP *bs);
+int OCSP_resp_get0_id(const OCSP_BASICRESP *bs,
+ const ASN1_OCTET_STRING **pid,
+ const X509_NAME **pname);
+int OCSP_resp_get1_id(const OCSP_BASICRESP *bs,
+ ASN1_OCTET_STRING **pid,
+ X509_NAME **pname);
+
+int OCSP_resp_find(OCSP_BASICRESP *bs, OCSP_CERTID *id, int last);
+int OCSP_single_get0_status(OCSP_SINGLERESP *single, int *reason,
+ ASN1_GENERALIZEDTIME **revtime,
+ ASN1_GENERALIZEDTIME **thisupd,
+ ASN1_GENERALIZEDTIME **nextupd);
+int OCSP_resp_find_status(OCSP_BASICRESP *bs, OCSP_CERTID *id, int *status,
+ int *reason,
+ ASN1_GENERALIZEDTIME **revtime,
+ ASN1_GENERALIZEDTIME **thisupd,
+ ASN1_GENERALIZEDTIME **nextupd);
+int OCSP_check_validity(ASN1_GENERALIZEDTIME *thisupd,
+ ASN1_GENERALIZEDTIME *nextupd, long sec, long maxsec);
+
+int OCSP_request_verify(OCSP_REQUEST *req, STACK_OF(X509) *certs,
+ X509_STORE *store, unsigned long flags);
+
+# define OCSP_parse_url(url, host, port, path, ssl) \
+ OSSL_HTTP_parse_url(url, ssl, NULL, host, port, NULL, path, NULL, NULL)
+
+int OCSP_id_issuer_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b);
+int OCSP_id_cmp(const OCSP_CERTID *a, const OCSP_CERTID *b);
+
+int OCSP_request_onereq_count(OCSP_REQUEST *req);
+OCSP_ONEREQ *OCSP_request_onereq_get0(OCSP_REQUEST *req, int i);
+OCSP_CERTID *OCSP_onereq_get0_id(OCSP_ONEREQ *one);
+int OCSP_id_get0_info(ASN1_OCTET_STRING **piNameHash, ASN1_OBJECT **pmd,
+ ASN1_OCTET_STRING **pikeyHash,
+ ASN1_INTEGER **pserial, OCSP_CERTID *cid);
+int OCSP_request_is_signed(OCSP_REQUEST *req);
+OCSP_RESPONSE *OCSP_response_create(int status, OCSP_BASICRESP *bs);
+OCSP_SINGLERESP *OCSP_basic_add1_status(OCSP_BASICRESP *rsp,
+ OCSP_CERTID *cid,
+ int status, int reason,
+ ASN1_TIME *revtime,
+ ASN1_TIME *thisupd,
+ ASN1_TIME *nextupd);
+int OCSP_basic_add1_cert(OCSP_BASICRESP *resp, X509 *cert);
+int OCSP_basic_sign(OCSP_BASICRESP *brsp,
+ X509 *signer, EVP_PKEY *key, const EVP_MD *dgst,
+ STACK_OF(X509) *certs, unsigned long flags);
+int OCSP_basic_sign_ctx(OCSP_BASICRESP *brsp,
+ X509 *signer, EVP_MD_CTX *ctx,
+ STACK_OF(X509) *certs, unsigned long flags);
+int OCSP_RESPID_set_by_name(OCSP_RESPID *respid, X509 *cert);
+int OCSP_RESPID_set_by_key_ex(OCSP_RESPID *respid, X509 *cert,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int OCSP_RESPID_set_by_key(OCSP_RESPID *respid, X509 *cert);
+int OCSP_RESPID_match_ex(OCSP_RESPID *respid, X509 *cert, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int OCSP_RESPID_match(OCSP_RESPID *respid, X509 *cert);
+
+X509_EXTENSION *OCSP_crlID_new(const char *url, long *n, char *tim);
+
+X509_EXTENSION *OCSP_accept_responses_new(char **oids);
+
+X509_EXTENSION *OCSP_archive_cutoff_new(char *tim);
+
+X509_EXTENSION *OCSP_url_svcloc_new(const X509_NAME *issuer, const char **urls);
+
+int OCSP_REQUEST_get_ext_count(OCSP_REQUEST *x);
+int OCSP_REQUEST_get_ext_by_NID(OCSP_REQUEST *x, int nid, int lastpos);
+int OCSP_REQUEST_get_ext_by_OBJ(OCSP_REQUEST *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int OCSP_REQUEST_get_ext_by_critical(OCSP_REQUEST *x, int crit, int lastpos);
+X509_EXTENSION *OCSP_REQUEST_get_ext(OCSP_REQUEST *x, int loc);
+X509_EXTENSION *OCSP_REQUEST_delete_ext(OCSP_REQUEST *x, int loc);
+void *OCSP_REQUEST_get1_ext_d2i(OCSP_REQUEST *x, int nid, int *crit,
+ int *idx);
+int OCSP_REQUEST_add1_ext_i2d(OCSP_REQUEST *x, int nid, void *value, int crit,
+ unsigned long flags);
+int OCSP_REQUEST_add_ext(OCSP_REQUEST *x, X509_EXTENSION *ex, int loc);
+
+int OCSP_ONEREQ_get_ext_count(OCSP_ONEREQ *x);
+int OCSP_ONEREQ_get_ext_by_NID(OCSP_ONEREQ *x, int nid, int lastpos);
+int OCSP_ONEREQ_get_ext_by_OBJ(OCSP_ONEREQ *x, const ASN1_OBJECT *obj, int lastpos);
+int OCSP_ONEREQ_get_ext_by_critical(OCSP_ONEREQ *x, int crit, int lastpos);
+X509_EXTENSION *OCSP_ONEREQ_get_ext(OCSP_ONEREQ *x, int loc);
+X509_EXTENSION *OCSP_ONEREQ_delete_ext(OCSP_ONEREQ *x, int loc);
+void *OCSP_ONEREQ_get1_ext_d2i(OCSP_ONEREQ *x, int nid, int *crit, int *idx);
+int OCSP_ONEREQ_add1_ext_i2d(OCSP_ONEREQ *x, int nid, void *value, int crit,
+ unsigned long flags);
+int OCSP_ONEREQ_add_ext(OCSP_ONEREQ *x, X509_EXTENSION *ex, int loc);
+
+int OCSP_BASICRESP_get_ext_count(OCSP_BASICRESP *x);
+int OCSP_BASICRESP_get_ext_by_NID(OCSP_BASICRESP *x, int nid, int lastpos);
+int OCSP_BASICRESP_get_ext_by_OBJ(OCSP_BASICRESP *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int OCSP_BASICRESP_get_ext_by_critical(OCSP_BASICRESP *x, int crit,
+ int lastpos);
+X509_EXTENSION *OCSP_BASICRESP_get_ext(OCSP_BASICRESP *x, int loc);
+X509_EXTENSION *OCSP_BASICRESP_delete_ext(OCSP_BASICRESP *x, int loc);
+void *OCSP_BASICRESP_get1_ext_d2i(OCSP_BASICRESP *x, int nid, int *crit,
+ int *idx);
+int OCSP_BASICRESP_add1_ext_i2d(OCSP_BASICRESP *x, int nid, void *value,
+ int crit, unsigned long flags);
+int OCSP_BASICRESP_add_ext(OCSP_BASICRESP *x, X509_EXTENSION *ex, int loc);
+
+int OCSP_SINGLERESP_get_ext_count(OCSP_SINGLERESP *x);
+int OCSP_SINGLERESP_get_ext_by_NID(OCSP_SINGLERESP *x, int nid, int lastpos);
+int OCSP_SINGLERESP_get_ext_by_OBJ(OCSP_SINGLERESP *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int OCSP_SINGLERESP_get_ext_by_critical(OCSP_SINGLERESP *x, int crit,
+ int lastpos);
+X509_EXTENSION *OCSP_SINGLERESP_get_ext(OCSP_SINGLERESP *x, int loc);
+X509_EXTENSION *OCSP_SINGLERESP_delete_ext(OCSP_SINGLERESP *x, int loc);
+void *OCSP_SINGLERESP_get1_ext_d2i(OCSP_SINGLERESP *x, int nid, int *crit,
+ int *idx);
+int OCSP_SINGLERESP_add1_ext_i2d(OCSP_SINGLERESP *x, int nid, void *value,
+ int crit, unsigned long flags);
+int OCSP_SINGLERESP_add_ext(OCSP_SINGLERESP *x, X509_EXTENSION *ex, int loc);
+const OCSP_CERTID *OCSP_SINGLERESP_get0_id(const OCSP_SINGLERESP *x);
+
+DECLARE_ASN1_FUNCTIONS(OCSP_SINGLERESP)
+DECLARE_ASN1_FUNCTIONS(OCSP_CERTSTATUS)
+DECLARE_ASN1_FUNCTIONS(OCSP_REVOKEDINFO)
+DECLARE_ASN1_FUNCTIONS(OCSP_BASICRESP)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPDATA)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPID)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPONSE)
+DECLARE_ASN1_FUNCTIONS(OCSP_RESPBYTES)
+DECLARE_ASN1_FUNCTIONS(OCSP_ONEREQ)
+DECLARE_ASN1_FUNCTIONS(OCSP_CERTID)
+DECLARE_ASN1_FUNCTIONS(OCSP_REQUEST)
+DECLARE_ASN1_FUNCTIONS(OCSP_SIGNATURE)
+DECLARE_ASN1_FUNCTIONS(OCSP_REQINFO)
+DECLARE_ASN1_FUNCTIONS(OCSP_CRLID)
+DECLARE_ASN1_FUNCTIONS(OCSP_SERVICELOC)
+
+const char *OCSP_response_status_str(long s);
+const char *OCSP_cert_status_str(long s);
+const char *OCSP_crl_reason_str(long s);
+
+int OCSP_REQUEST_print(BIO *bp, OCSP_REQUEST *a, unsigned long flags);
+int OCSP_RESPONSE_print(BIO *bp, OCSP_RESPONSE *o, unsigned long flags);
+
+int OCSP_basic_verify(OCSP_BASICRESP *bs, STACK_OF(X509) *certs,
+ X509_STORE *st, unsigned long flags);
+
+
+# ifdef __cplusplus
+}
+# endif
+# endif /* !defined(OPENSSL_NO_OCSP) */
+#endif
diff --git a/include/openssl/ocsperr.h b/include/openssl/ocsperr.h
new file mode 100644
index 00000000..46a0523c
--- /dev/null
+++ b/include/openssl/ocsperr.h
@@ -0,0 +1,53 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_OCSPERR_H
+# define OPENSSL_OCSPERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_OCSP
+
+
+/*
+ * OCSP reason codes.
+ */
+# define OCSP_R_CERTIFICATE_VERIFY_ERROR 101
+# define OCSP_R_DIGEST_ERR 102
+# define OCSP_R_DIGEST_NAME_ERR 106
+# define OCSP_R_DIGEST_SIZE_ERR 107
+# define OCSP_R_ERROR_IN_NEXTUPDATE_FIELD 122
+# define OCSP_R_ERROR_IN_THISUPDATE_FIELD 123
+# define OCSP_R_MISSING_OCSPSIGNING_USAGE 103
+# define OCSP_R_NEXTUPDATE_BEFORE_THISUPDATE 124
+# define OCSP_R_NOT_BASIC_RESPONSE 104
+# define OCSP_R_NO_CERTIFICATES_IN_CHAIN 105
+# define OCSP_R_NO_RESPONSE_DATA 108
+# define OCSP_R_NO_REVOKED_TIME 109
+# define OCSP_R_NO_SIGNER_KEY 130
+# define OCSP_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 110
+# define OCSP_R_REQUEST_NOT_SIGNED 128
+# define OCSP_R_RESPONSE_CONTAINS_NO_REVOCATION_DATA 111
+# define OCSP_R_ROOT_CA_NOT_TRUSTED 112
+# define OCSP_R_SIGNATURE_FAILURE 117
+# define OCSP_R_SIGNER_CERTIFICATE_NOT_FOUND 118
+# define OCSP_R_STATUS_EXPIRED 125
+# define OCSP_R_STATUS_NOT_YET_VALID 126
+# define OCSP_R_STATUS_TOO_OLD 127
+# define OCSP_R_UNKNOWN_MESSAGE_DIGEST 119
+# define OCSP_R_UNKNOWN_NID 120
+# define OCSP_R_UNSUPPORTED_REQUESTORNAME_TYPE 129
+
+# endif
+#endif
diff --git a/include/openssl/opensslconf.h b/include/openssl/opensslconf.h
new file mode 100644
index 00000000..1e83371f
--- /dev/null
+++ b/include/openssl/opensslconf.h
@@ -0,0 +1,17 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_OPENSSLCONF_H
+# define OPENSSL_OPENSSLCONF_H
+# pragma once
+
+# include <openssl/configuration.h>
+# include <openssl/macros.h>
+
+#endif /* OPENSSL_OPENSSLCONF_H */
diff --git a/include/openssl/opensslv.h b/include/openssl/opensslv.h
new file mode 100644
index 00000000..612d5aec
--- /dev/null
+++ b/include/openssl/opensslv.h
@@ -0,0 +1,114 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\opensslv.h.in
+ *
+ * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_OPENSSLV_H
+# define OPENSSL_OPENSSLV_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * SECTION 1: VERSION DATA. These will change for each release
+ */
+
+/*
+ * Base version macros
+ *
+ * These macros express version number MAJOR.MINOR.PATCH exactly
+ */
+# define OPENSSL_VERSION_MAJOR 3
+# define OPENSSL_VERSION_MINOR 0
+# define OPENSSL_VERSION_PATCH 1
+
+/*
+ * Additional version information
+ *
+ * These are also part of the new version scheme, but aren't part
+ * of the version number itself.
+ */
+
+/* Could be: #define OPENSSL_VERSION_PRE_RELEASE "-alpha.1" */
+# define OPENSSL_VERSION_PRE_RELEASE ""
+/* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+fips" */
+/* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+vendor.1" */
+# define OPENSSL_VERSION_BUILD_METADATA ""
+
+/*
+ * Note: The OpenSSL Project will never define OPENSSL_VERSION_BUILD_METADATA
+ * to be anything but the empty string. Its use is entirely reserved for
+ * others
+ */
+
+/*
+ * Shared library version
+ *
+ * This is strictly to express ABI version, which may or may not
+ * be related to the API version expressed with the macros above.
+ * This is defined in free form.
+ */
+# define OPENSSL_SHLIB_VERSION 3
+
+/*
+ * SECTION 2: USEFUL MACROS
+ */
+
+/* For checking general API compatibility when preprocessing */
+# define OPENSSL_VERSION_PREREQ(maj,min) \
+ ((OPENSSL_VERSION_MAJOR << 16) + OPENSSL_VERSION_MINOR >= ((maj) << 16) + (min))
+
+/*
+ * Macros to get the version in easily digested string form, both the short
+ * "MAJOR.MINOR.PATCH" variant (where MAJOR, MINOR and PATCH are replaced
+ * with the values from the corresponding OPENSSL_VERSION_ macros) and the
+ * longer variant with OPENSSL_VERSION_PRE_RELEASE_STR and
+ * OPENSSL_VERSION_BUILD_METADATA_STR appended.
+ */
+# define OPENSSL_VERSION_STR "3.0.1"
+# define OPENSSL_FULL_VERSION_STR "3.0.1"
+
+/*
+ * SECTION 3: ADDITIONAL METADATA
+ *
+ * These strings are defined separately to allow them to be parsable.
+ */
+# define OPENSSL_RELEASE_DATE "14 Dec 2021"
+
+/*
+ * SECTION 4: BACKWARD COMPATIBILITY
+ */
+
+# define OPENSSL_VERSION_TEXT "OpenSSL 3.0.1 14 Dec 2021"
+
+/* Synthesize OPENSSL_VERSION_NUMBER with the layout 0xMNN00PPSL */
+# ifdef OPENSSL_VERSION_PRE_RELEASE
+# define _OPENSSL_VERSION_PRE_RELEASE 0x0L
+# else
+# define _OPENSSL_VERSION_PRE_RELEASE 0xfL
+# endif
+# define OPENSSL_VERSION_NUMBER \
+ ( (OPENSSL_VERSION_MAJOR<<28) \
+ |(OPENSSL_VERSION_MINOR<<20) \
+ |(OPENSSL_VERSION_PATCH<<4) \
+ |_OPENSSL_VERSION_PRE_RELEASE )
+
+# ifdef __cplusplus
+}
+# endif
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_OPENSSLV_H
+# endif
+
+#endif /* OPENSSL_OPENSSLV_H */
diff --git a/include/openssl/opensslv.h.in b/include/openssl/opensslv.h.in
new file mode 100644
index 00000000..3f47a2ac
--- /dev/null
+++ b/include/openssl/opensslv.h.in
@@ -0,0 +1,113 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1999-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_OPENSSLV_H
+# define OPENSSL_OPENSSLV_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * SECTION 1: VERSION DATA. These will change for each release
+ */
+
+/*
+ * Base version macros
+ *
+ * These macros express version number MAJOR.MINOR.PATCH exactly
+ */
+# define OPENSSL_VERSION_MAJOR {- $config{major} -}
+# define OPENSSL_VERSION_MINOR {- $config{minor} -}
+# define OPENSSL_VERSION_PATCH {- $config{patch} -}
+
+/*
+ * Additional version information
+ *
+ * These are also part of the new version scheme, but aren't part
+ * of the version number itself.
+ */
+
+/* Could be: #define OPENSSL_VERSION_PRE_RELEASE "-alpha.1" */
+# define OPENSSL_VERSION_PRE_RELEASE "{- $config{prerelease} -}"
+/* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+fips" */
+/* Could be: #define OPENSSL_VERSION_BUILD_METADATA "+vendor.1" */
+# define OPENSSL_VERSION_BUILD_METADATA "{- $config{build_metadata} -}"
+
+/*
+ * Note: The OpenSSL Project will never define OPENSSL_VERSION_BUILD_METADATA
+ * to be anything but the empty string. Its use is entirely reserved for
+ * others
+ */
+
+/*
+ * Shared library version
+ *
+ * This is strictly to express ABI version, which may or may not
+ * be related to the API version expressed with the macros above.
+ * This is defined in free form.
+ */
+# define OPENSSL_SHLIB_VERSION {- $config{shlib_version} -}
+
+/*
+ * SECTION 2: USEFUL MACROS
+ */
+
+/* For checking general API compatibility when preprocessing */
+# define OPENSSL_VERSION_PREREQ(maj,min) \
+ ((OPENSSL_VERSION_MAJOR << 16) + OPENSSL_VERSION_MINOR >= ((maj) << 16) + (min))
+
+/*
+ * Macros to get the version in easily digested string form, both the short
+ * "MAJOR.MINOR.PATCH" variant (where MAJOR, MINOR and PATCH are replaced
+ * with the values from the corresponding OPENSSL_VERSION_ macros) and the
+ * longer variant with OPENSSL_VERSION_PRE_RELEASE_STR and
+ * OPENSSL_VERSION_BUILD_METADATA_STR appended.
+ */
+# define OPENSSL_VERSION_STR "{- $config{version} -}"
+# define OPENSSL_FULL_VERSION_STR "{- $config{full_version} -}"
+
+/*
+ * SECTION 3: ADDITIONAL METADATA
+ *
+ * These strings are defined separately to allow them to be parsable.
+ */
+# define OPENSSL_RELEASE_DATE "{- $config{release_date} -}"
+
+/*
+ * SECTION 4: BACKWARD COMPATIBILITY
+ */
+
+# define OPENSSL_VERSION_TEXT "OpenSSL {- "$config{full_version} $config{release_date}" -}"
+
+/* Synthesize OPENSSL_VERSION_NUMBER with the layout 0xMNN00PPSL */
+# ifdef OPENSSL_VERSION_PRE_RELEASE
+# define _OPENSSL_VERSION_PRE_RELEASE 0x0L
+# else
+# define _OPENSSL_VERSION_PRE_RELEASE 0xfL
+# endif
+# define OPENSSL_VERSION_NUMBER \
+ ( (OPENSSL_VERSION_MAJOR<<28) \
+ |(OPENSSL_VERSION_MINOR<<20) \
+ |(OPENSSL_VERSION_PATCH<<4) \
+ |_OPENSSL_VERSION_PRE_RELEASE )
+
+# ifdef __cplusplus
+}
+# endif
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_OPENSSLV_H
+# endif
+
+#endif /* OPENSSL_OPENSSLV_H */
diff --git a/include/openssl/ossl_typ.h b/include/openssl/ossl_typ.h
new file mode 100644
index 00000000..82a58988
--- /dev/null
+++ b/include/openssl/ossl_typ.h
@@ -0,0 +1,16 @@
+/*
+ * Copyright 2019 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * The original <openssl/ossl_typ.h> was renamed to <openssl/types.h>
+ *
+ * This header file only exists for compatibility reasons with older
+ * applications which #include <openssl/ossl_typ.h>.
+ */
+# include <openssl/types.h>
diff --git a/include/openssl/param_build.h b/include/openssl/param_build.h
new file mode 100644
index 00000000..f29fdb29
--- /dev/null
+++ b/include/openssl/param_build.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PARAM_BUILD_H
+# define OPENSSL_PARAM_BUILD_H
+# pragma once
+
+# include <openssl/params.h>
+# include <openssl/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+OSSL_PARAM_BLD *OSSL_PARAM_BLD_new(void);
+OSSL_PARAM *OSSL_PARAM_BLD_to_param(OSSL_PARAM_BLD *bld);
+void OSSL_PARAM_BLD_free(OSSL_PARAM_BLD *bld);
+
+int OSSL_PARAM_BLD_push_int(OSSL_PARAM_BLD *bld, const char *key, int val);
+int OSSL_PARAM_BLD_push_uint(OSSL_PARAM_BLD *bld, const char *key,
+ unsigned int val);
+int OSSL_PARAM_BLD_push_long(OSSL_PARAM_BLD *bld, const char *key,
+ long int val);
+int OSSL_PARAM_BLD_push_ulong(OSSL_PARAM_BLD *bld, const char *key,
+ unsigned long int val);
+int OSSL_PARAM_BLD_push_int32(OSSL_PARAM_BLD *bld, const char *key,
+ int32_t val);
+int OSSL_PARAM_BLD_push_uint32(OSSL_PARAM_BLD *bld, const char *key,
+ uint32_t val);
+int OSSL_PARAM_BLD_push_int64(OSSL_PARAM_BLD *bld, const char *key,
+ int64_t val);
+int OSSL_PARAM_BLD_push_uint64(OSSL_PARAM_BLD *bld, const char *key,
+ uint64_t val);
+int OSSL_PARAM_BLD_push_size_t(OSSL_PARAM_BLD *bld, const char *key,
+ size_t val);
+int OSSL_PARAM_BLD_push_time_t(OSSL_PARAM_BLD *bld, const char *key,
+ time_t val);
+int OSSL_PARAM_BLD_push_double(OSSL_PARAM_BLD *bld, const char *key,
+ double val);
+int OSSL_PARAM_BLD_push_BN(OSSL_PARAM_BLD *bld, const char *key,
+ const BIGNUM *bn);
+int OSSL_PARAM_BLD_push_BN_pad(OSSL_PARAM_BLD *bld, const char *key,
+ const BIGNUM *bn, size_t sz);
+int OSSL_PARAM_BLD_push_utf8_string(OSSL_PARAM_BLD *bld, const char *key,
+ const char *buf, size_t bsize);
+int OSSL_PARAM_BLD_push_utf8_ptr(OSSL_PARAM_BLD *bld, const char *key,
+ char *buf, size_t bsize);
+int OSSL_PARAM_BLD_push_octet_string(OSSL_PARAM_BLD *bld, const char *key,
+ const void *buf, size_t bsize);
+int OSSL_PARAM_BLD_push_octet_ptr(OSSL_PARAM_BLD *bld, const char *key,
+ void *buf, size_t bsize);
+
+# ifdef __cplusplus
+}
+# endif
+#endif /* OPENSSL_PARAM_BUILD_H */
diff --git a/include/openssl/params.h b/include/openssl/params.h
new file mode 100644
index 00000000..d75eab07
--- /dev/null
+++ b/include/openssl/params.h
@@ -0,0 +1,160 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PARAMS_H
+# define OPENSSL_PARAMS_H
+# pragma once
+
+# include <openssl/core.h>
+# include <openssl/bn.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define OSSL_PARAM_UNMODIFIED ((size_t)-1)
+
+# define OSSL_PARAM_END \
+ { NULL, 0, NULL, 0, 0 }
+
+# define OSSL_PARAM_DEFN(key, type, addr, sz) \
+ { (key), (type), (addr), (sz), OSSL_PARAM_UNMODIFIED }
+
+/* Basic parameter types without return sizes */
+# define OSSL_PARAM_int(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_INTEGER, (addr), sizeof(int))
+# define OSSL_PARAM_uint(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UNSIGNED_INTEGER, (addr), \
+ sizeof(unsigned int))
+# define OSSL_PARAM_long(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_INTEGER, (addr), sizeof(long int))
+# define OSSL_PARAM_ulong(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UNSIGNED_INTEGER, (addr), \
+ sizeof(unsigned long int))
+# define OSSL_PARAM_int32(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_INTEGER, (addr), sizeof(int32_t))
+# define OSSL_PARAM_uint32(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UNSIGNED_INTEGER, (addr), \
+ sizeof(uint32_t))
+# define OSSL_PARAM_int64(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_INTEGER, (addr), sizeof(int64_t))
+# define OSSL_PARAM_uint64(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UNSIGNED_INTEGER, (addr), \
+ sizeof(uint64_t))
+# define OSSL_PARAM_size_t(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UNSIGNED_INTEGER, (addr), sizeof(size_t))
+# define OSSL_PARAM_time_t(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_INTEGER, (addr), sizeof(time_t))
+# define OSSL_PARAM_double(key, addr) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_REAL, (addr), sizeof(double))
+
+# define OSSL_PARAM_BN(key, bn, sz) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UNSIGNED_INTEGER, (bn), (sz))
+# define OSSL_PARAM_utf8_string(key, addr, sz) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UTF8_STRING, (addr), sz)
+# define OSSL_PARAM_octet_string(key, addr, sz) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_OCTET_STRING, (addr), sz)
+
+# define OSSL_PARAM_utf8_ptr(key, addr, sz) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_UTF8_PTR, (addr), sz)
+# define OSSL_PARAM_octet_ptr(key, addr, sz) \
+ OSSL_PARAM_DEFN((key), OSSL_PARAM_OCTET_PTR, (addr), sz)
+
+/* Search an OSSL_PARAM array for a matching name */
+OSSL_PARAM *OSSL_PARAM_locate(OSSL_PARAM *p, const char *key);
+const OSSL_PARAM *OSSL_PARAM_locate_const(const OSSL_PARAM *p, const char *key);
+
+/* Basic parameter type run-time construction */
+OSSL_PARAM OSSL_PARAM_construct_int(const char *key, int *buf);
+OSSL_PARAM OSSL_PARAM_construct_uint(const char *key, unsigned int *buf);
+OSSL_PARAM OSSL_PARAM_construct_long(const char *key, long int *buf);
+OSSL_PARAM OSSL_PARAM_construct_ulong(const char *key, unsigned long int *buf);
+OSSL_PARAM OSSL_PARAM_construct_int32(const char *key, int32_t *buf);
+OSSL_PARAM OSSL_PARAM_construct_uint32(const char *key, uint32_t *buf);
+OSSL_PARAM OSSL_PARAM_construct_int64(const char *key, int64_t *buf);
+OSSL_PARAM OSSL_PARAM_construct_uint64(const char *key, uint64_t *buf);
+OSSL_PARAM OSSL_PARAM_construct_size_t(const char *key, size_t *buf);
+OSSL_PARAM OSSL_PARAM_construct_time_t(const char *key, time_t *buf);
+OSSL_PARAM OSSL_PARAM_construct_BN(const char *key, unsigned char *buf,
+ size_t bsize);
+OSSL_PARAM OSSL_PARAM_construct_double(const char *key, double *buf);
+OSSL_PARAM OSSL_PARAM_construct_utf8_string(const char *key, char *buf,
+ size_t bsize);
+OSSL_PARAM OSSL_PARAM_construct_utf8_ptr(const char *key, char **buf,
+ size_t bsize);
+OSSL_PARAM OSSL_PARAM_construct_octet_string(const char *key, void *buf,
+ size_t bsize);
+OSSL_PARAM OSSL_PARAM_construct_octet_ptr(const char *key, void **buf,
+ size_t bsize);
+OSSL_PARAM OSSL_PARAM_construct_end(void);
+
+int OSSL_PARAM_allocate_from_text(OSSL_PARAM *to,
+ const OSSL_PARAM *paramdefs,
+ const char *key, const char *value,
+ size_t value_n, int *found);
+
+int OSSL_PARAM_get_int(const OSSL_PARAM *p, int *val);
+int OSSL_PARAM_get_uint(const OSSL_PARAM *p, unsigned int *val);
+int OSSL_PARAM_get_long(const OSSL_PARAM *p, long int *val);
+int OSSL_PARAM_get_ulong(const OSSL_PARAM *p, unsigned long int *val);
+int OSSL_PARAM_get_int32(const OSSL_PARAM *p, int32_t *val);
+int OSSL_PARAM_get_uint32(const OSSL_PARAM *p, uint32_t *val);
+int OSSL_PARAM_get_int64(const OSSL_PARAM *p, int64_t *val);
+int OSSL_PARAM_get_uint64(const OSSL_PARAM *p, uint64_t *val);
+int OSSL_PARAM_get_size_t(const OSSL_PARAM *p, size_t *val);
+int OSSL_PARAM_get_time_t(const OSSL_PARAM *p, time_t *val);
+
+int OSSL_PARAM_set_int(OSSL_PARAM *p, int val);
+int OSSL_PARAM_set_uint(OSSL_PARAM *p, unsigned int val);
+int OSSL_PARAM_set_long(OSSL_PARAM *p, long int val);
+int OSSL_PARAM_set_ulong(OSSL_PARAM *p, unsigned long int val);
+int OSSL_PARAM_set_int32(OSSL_PARAM *p, int32_t val);
+int OSSL_PARAM_set_uint32(OSSL_PARAM *p, uint32_t val);
+int OSSL_PARAM_set_int64(OSSL_PARAM *p, int64_t val);
+int OSSL_PARAM_set_uint64(OSSL_PARAM *p, uint64_t val);
+int OSSL_PARAM_set_size_t(OSSL_PARAM *p, size_t val);
+int OSSL_PARAM_set_time_t(OSSL_PARAM *p, time_t val);
+
+int OSSL_PARAM_get_double(const OSSL_PARAM *p, double *val);
+int OSSL_PARAM_set_double(OSSL_PARAM *p, double val);
+
+int OSSL_PARAM_get_BN(const OSSL_PARAM *p, BIGNUM **val);
+int OSSL_PARAM_set_BN(OSSL_PARAM *p, const BIGNUM *val);
+
+int OSSL_PARAM_get_utf8_string(const OSSL_PARAM *p, char **val, size_t max_len);
+int OSSL_PARAM_set_utf8_string(OSSL_PARAM *p, const char *val);
+
+int OSSL_PARAM_get_octet_string(const OSSL_PARAM *p, void **val, size_t max_len,
+ size_t *used_len);
+int OSSL_PARAM_set_octet_string(OSSL_PARAM *p, const void *val, size_t len);
+
+int OSSL_PARAM_get_utf8_ptr(const OSSL_PARAM *p, const char **val);
+int OSSL_PARAM_set_utf8_ptr(OSSL_PARAM *p, const char *val);
+
+int OSSL_PARAM_get_octet_ptr(const OSSL_PARAM *p, const void **val,
+ size_t *used_len);
+int OSSL_PARAM_set_octet_ptr(OSSL_PARAM *p, const void *val,
+ size_t used_len);
+
+int OSSL_PARAM_get_utf8_string_ptr(const OSSL_PARAM *p, const char **val);
+int OSSL_PARAM_get_octet_string_ptr(const OSSL_PARAM *p, const void **val,
+ size_t *used_len);
+
+int OSSL_PARAM_modified(const OSSL_PARAM *p);
+void OSSL_PARAM_set_all_unmodified(OSSL_PARAM *p);
+
+OSSL_PARAM *OSSL_PARAM_dup(const OSSL_PARAM *p);
+OSSL_PARAM *OSSL_PARAM_merge(const OSSL_PARAM *p1, const OSSL_PARAM *p2);
+void OSSL_PARAM_free(OSSL_PARAM *p);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/pem.h b/include/openssl/pem.h
new file mode 100644
index 00000000..80940dfa
--- /dev/null
+++ b/include/openssl/pem.h
@@ -0,0 +1,538 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PEM_H
+# define OPENSSL_PEM_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_PEM_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/bio.h>
+# include <openssl/safestack.h>
+# include <openssl/evp.h>
+# include <openssl/x509.h>
+# include <openssl/pemerr.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define PEM_BUFSIZE 1024
+
+# define PEM_STRING_X509_OLD "X509 CERTIFICATE"
+# define PEM_STRING_X509 "CERTIFICATE"
+# define PEM_STRING_X509_TRUSTED "TRUSTED CERTIFICATE"
+# define PEM_STRING_X509_REQ_OLD "NEW CERTIFICATE REQUEST"
+# define PEM_STRING_X509_REQ "CERTIFICATE REQUEST"
+# define PEM_STRING_X509_CRL "X509 CRL"
+# define PEM_STRING_EVP_PKEY "ANY PRIVATE KEY"
+# define PEM_STRING_PUBLIC "PUBLIC KEY"
+# define PEM_STRING_RSA "RSA PRIVATE KEY"
+# define PEM_STRING_RSA_PUBLIC "RSA PUBLIC KEY"
+# define PEM_STRING_DSA "DSA PRIVATE KEY"
+# define PEM_STRING_DSA_PUBLIC "DSA PUBLIC KEY"
+# define PEM_STRING_PKCS7 "PKCS7"
+# define PEM_STRING_PKCS7_SIGNED "PKCS #7 SIGNED DATA"
+# define PEM_STRING_PKCS8 "ENCRYPTED PRIVATE KEY"
+# define PEM_STRING_PKCS8INF "PRIVATE KEY"
+# define PEM_STRING_DHPARAMS "DH PARAMETERS"
+# define PEM_STRING_DHXPARAMS "X9.42 DH PARAMETERS"
+# define PEM_STRING_SSL_SESSION "SSL SESSION PARAMETERS"
+# define PEM_STRING_DSAPARAMS "DSA PARAMETERS"
+# define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY"
+# define PEM_STRING_ECPARAMETERS "EC PARAMETERS"
+# define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY"
+# define PEM_STRING_PARAMETERS "PARAMETERS"
+# define PEM_STRING_CMS "CMS"
+
+# define PEM_TYPE_ENCRYPTED 10
+# define PEM_TYPE_MIC_ONLY 20
+# define PEM_TYPE_MIC_CLEAR 30
+# define PEM_TYPE_CLEAR 40
+
+/*
+ * These macros make the PEM_read/PEM_write functions easier to maintain and
+ * write. Now they are all implemented with either: IMPLEMENT_PEM_rw(...) or
+ * IMPLEMENT_PEM_rw_cb(...)
+ */
+
+# define PEM_read_cb_fnsig(name, type, INTYPE, readname) \
+ type *PEM_##readname##_##name(INTYPE *out, type **x, \
+ pem_password_cb *cb, void *u)
+# define PEM_read_cb_ex_fnsig(name, type, INTYPE, readname) \
+ type *PEM_##readname##_##name##_ex(INTYPE *out, type **x, \
+ pem_password_cb *cb, void *u, \
+ OSSL_LIB_CTX *libctx, \
+ const char *propq)
+
+# define PEM_write_fnsig(name, type, OUTTYPE, writename) \
+ int PEM_##writename##_##name(OUTTYPE *out, const type *x)
+# define PEM_write_cb_fnsig(name, type, OUTTYPE, writename) \
+ int PEM_##writename##_##name(OUTTYPE *out, const type *x, \
+ const EVP_CIPHER *enc, \
+ const unsigned char *kstr, int klen, \
+ pem_password_cb *cb, void *u)
+# define PEM_write_ex_fnsig(name, type, OUTTYPE, writename) \
+ int PEM_##writename##_##name##_ex(OUTTYPE *out, const type *x, \
+ OSSL_LIB_CTX *libctx, \
+ const char *propq)
+# define PEM_write_cb_ex_fnsig(name, type, OUTTYPE, writename) \
+ int PEM_##writename##_##name##_ex(OUTTYPE *out, const type *x, \
+ const EVP_CIPHER *enc, \
+ const unsigned char *kstr, int klen, \
+ pem_password_cb *cb, void *u, \
+ OSSL_LIB_CTX *libctx, \
+ const char *propq)
+
+# ifdef OPENSSL_NO_STDIO
+
+# define IMPLEMENT_PEM_read_fp(name, type, str, asn1) /**/
+# define IMPLEMENT_PEM_write_fp(name, type, str, asn1) /**/
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) /**/
+# endif
+# define IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) /**/
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) /**/
+# endif
+# else
+
+# define IMPLEMENT_PEM_read_fp(name, type, str, asn1) \
+ type *PEM_read_##name(FILE *fp, type **x, pem_password_cb *cb, void *u) \
+ { \
+ return PEM_ASN1_read((d2i_of_void *)d2i_##asn1, str, fp, \
+ (void **)x, cb, u); \
+ }
+
+# define IMPLEMENT_PEM_write_fp(name, type, str, asn1) \
+ PEM_write_fnsig(name, type, FILE, write) \
+ { \
+ return PEM_ASN1_write((i2d_of_void *)i2d_##asn1, str, out, \
+ x, NULL, NULL, 0, NULL, NULL); \
+ }
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_fp_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_fp(name, type, str, asn1)
+# endif
+
+# define IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1) \
+ PEM_write_cb_fnsig(name, type, FILE, write) \
+ { \
+ return PEM_ASN1_write((i2d_of_void *)i2d_##asn1, str, out, \
+ x, enc, kstr, klen, cb, u); \
+ }
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1)
+# endif
+# endif
+
+# define IMPLEMENT_PEM_read_bio(name, type, str, asn1) \
+ type *PEM_read_bio_##name(BIO *bp, type **x, \
+ pem_password_cb *cb, void *u) \
+ { \
+ return PEM_ASN1_read_bio((d2i_of_void *)d2i_##asn1, str, bp, \
+ (void **)x, cb, u); \
+ }
+
+# define IMPLEMENT_PEM_write_bio(name, type, str, asn1) \
+ PEM_write_fnsig(name, type, BIO, write_bio) \
+ { \
+ return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1, str, out, \
+ x, NULL,NULL,0,NULL,NULL); \
+ }
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_bio_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_bio(name, type, str, asn1)
+# endif
+
+# define IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \
+ PEM_write_cb_fnsig(name, type, BIO, write_bio) \
+ { \
+ return PEM_ASN1_write_bio((i2d_of_void *)i2d_##asn1, str, out, \
+ x, enc, kstr, klen, cb, u); \
+ }
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_cb_bio_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1)
+# endif
+
+# define IMPLEMENT_PEM_write(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_bio(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_fp(name, type, str, asn1)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_bio_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_fp_const(name, type, str, asn1)
+# endif
+
+# define IMPLEMENT_PEM_write_cb(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_cb_bio(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_cb_fp(name, type, str, asn1)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_write_cb_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_cb_bio_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_cb_fp_const(name, type, str, asn1)
+# endif
+
+# define IMPLEMENT_PEM_read(name, type, str, asn1) \
+ IMPLEMENT_PEM_read_bio(name, type, str, asn1) \
+ IMPLEMENT_PEM_read_fp(name, type, str, asn1)
+
+# define IMPLEMENT_PEM_rw(name, type, str, asn1) \
+ IMPLEMENT_PEM_read(name, type, str, asn1) \
+ IMPLEMENT_PEM_write(name, type, str, asn1)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define IMPLEMENT_PEM_rw_const(name, type, str, asn1) \
+ IMPLEMENT_PEM_read(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_const(name, type, str, asn1)
+# endif
+
+# define IMPLEMENT_PEM_rw_cb(name, type, str, asn1) \
+ IMPLEMENT_PEM_read(name, type, str, asn1) \
+ IMPLEMENT_PEM_write_cb(name, type, str, asn1)
+
+/* These are the same except they are for the declarations */
+
+/*
+ * The mysterious 'extern' that's passed to some macros is innocuous,
+ * and is there to quiet pre-C99 compilers that may complain about empty
+ * arguments in macro calls.
+ */
+# if defined(OPENSSL_NO_STDIO)
+
+# define DECLARE_PEM_read_fp_attr(attr, name, type) /**/
+# define DECLARE_PEM_read_fp_ex_attr(attr, name, type) /**/
+# define DECLARE_PEM_write_fp_attr(attr, name, type) /**/
+# define DECLARE_PEM_write_fp_ex_attr(attr, name, type) /**/
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DECLARE_PEM_write_fp_const_attr(attr, name, type) /**/
+# endif
+# define DECLARE_PEM_write_cb_fp_attr(attr, name, type) /**/
+# define DECLARE_PEM_write_cb_fp_ex_attr(attr, name, type) /**/
+
+# else
+
+# define DECLARE_PEM_read_fp_attr(attr, name, type) \
+ attr PEM_read_cb_fnsig(name, type, FILE, read);
+# define DECLARE_PEM_read_fp_ex_attr(attr, name, type) \
+ attr PEM_read_cb_fnsig(name, type, FILE, read); \
+ attr PEM_read_cb_ex_fnsig(name, type, FILE, read);
+
+# define DECLARE_PEM_write_fp_attr(attr, name, type) \
+ attr PEM_write_fnsig(name, type, FILE, write);
+# define DECLARE_PEM_write_fp_ex_attr(attr, name, type) \
+ attr PEM_write_fnsig(name, type, FILE, write); \
+ attr PEM_write_ex_fnsig(name, type, FILE, write);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DECLARE_PEM_write_fp_const_attr(attr, name, type) \
+ attr PEM_write_fnsig(name, type, FILE, write);
+# endif
+# define DECLARE_PEM_write_cb_fp_attr(attr, name, type) \
+ attr PEM_write_cb_fnsig(name, type, FILE, write);
+# define DECLARE_PEM_write_cb_fp_ex_attr(attr, name, type) \
+ attr PEM_write_cb_fnsig(name, type, FILE, write); \
+ attr PEM_write_cb_ex_fnsig(name, type, FILE, write);
+
+# endif
+
+# define DECLARE_PEM_read_fp(name, type) \
+ DECLARE_PEM_read_fp_attr(extern, name, type)
+# define DECLARE_PEM_write_fp(name, type) \
+ DECLARE_PEM_write_fp_attr(extern, name, type)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DECLARE_PEM_write_fp_const(name, type) \
+ DECLARE_PEM_write_fp_const_attr(extern, name, type)
+# endif
+# define DECLARE_PEM_write_cb_fp(name, type) \
+ DECLARE_PEM_write_cb_fp_attr(extern, name, type)
+
+# define DECLARE_PEM_read_bio_attr(attr, name, type) \
+ attr PEM_read_cb_fnsig(name, type, BIO, read_bio);
+# define DECLARE_PEM_read_bio_ex_attr(attr, name, type) \
+ attr PEM_read_cb_fnsig(name, type, BIO, read_bio); \
+ attr PEM_read_cb_ex_fnsig(name, type, BIO, read_bio);
+# define DECLARE_PEM_read_bio(name, type) \
+ DECLARE_PEM_read_bio_attr(extern, name, type)
+# define DECLARE_PEM_read_bio_ex(name, type) \
+ DECLARE_PEM_read_bio_ex_attr(extern, name, type)
+
+# define DECLARE_PEM_write_bio_attr(attr, name, type) \
+ attr PEM_write_fnsig(name, type, BIO, write_bio);
+# define DECLARE_PEM_write_bio_ex_attr(attr, name, type) \
+ attr PEM_write_fnsig(name, type, BIO, write_bio); \
+ attr PEM_write_ex_fnsig(name, type, BIO, write_bio);
+# define DECLARE_PEM_write_bio(name, type) \
+ DECLARE_PEM_write_bio_attr(extern, name, type)
+# define DECLARE_PEM_write_bio_ex(name, type) \
+ DECLARE_PEM_write_bio_ex_attr(extern, name, type)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DECLARE_PEM_write_bio_const_attr(attr, name, type) \
+ attr PEM_write_fnsig(name, type, BIO, write_bio);
+# define DECLARE_PEM_write_bio_const(name, type) \
+ DECLARE_PEM_write_bio_const_attr(extern, name, type)
+# endif
+
+# define DECLARE_PEM_write_cb_bio_attr(attr, name, type) \
+ attr PEM_write_cb_fnsig(name, type, BIO, write_bio);
+# define DECLARE_PEM_write_cb_bio_ex_attr(attr, name, type) \
+ attr PEM_write_cb_fnsig(name, type, BIO, write_bio); \
+ attr PEM_write_cb_ex_fnsig(name, type, BIO, write_bio);
+# define DECLARE_PEM_write_cb_bio(name, type) \
+ DECLARE_PEM_write_cb_bio_attr(extern, name, type)
+# define DECLARE_PEM_write_cb_ex_bio(name, type) \
+ DECLARE_PEM_write_cb_bio_ex_attr(extern, name, type)
+
+# define DECLARE_PEM_write_attr(attr, name, type) \
+ DECLARE_PEM_write_bio_attr(attr, name, type) \
+ DECLARE_PEM_write_fp_attr(attr, name, type)
+# define DECLARE_PEM_write_ex_attr(attr, name, type) \
+ DECLARE_PEM_write_bio_ex_attr(attr, name, type) \
+ DECLARE_PEM_write_fp_ex_attr(attr, name, type)
+# define DECLARE_PEM_write(name, type) \
+ DECLARE_PEM_write_attr(extern, name, type)
+# define DECLARE_PEM_write_ex(name, type) \
+ DECLARE_PEM_write_ex_attr(extern, name, type)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DECLARE_PEM_write_const_attr(attr, name, type) \
+ DECLARE_PEM_write_bio_const_attr(attr, name, type) \
+ DECLARE_PEM_write_fp_const_attr(attr, name, type)
+# define DECLARE_PEM_write_const(name, type) \
+ DECLARE_PEM_write_const_attr(extern, name, type)
+# endif
+# define DECLARE_PEM_write_cb_attr(attr, name, type) \
+ DECLARE_PEM_write_cb_bio_attr(attr, name, type) \
+ DECLARE_PEM_write_cb_fp_attr(attr, name, type)
+# define DECLARE_PEM_write_cb_ex_attr(attr, name, type) \
+ DECLARE_PEM_write_cb_bio_ex_attr(attr, name, type) \
+ DECLARE_PEM_write_cb_fp_ex_attr(attr, name, type)
+# define DECLARE_PEM_write_cb(name, type) \
+ DECLARE_PEM_write_cb_attr(extern, name, type)
+# define DECLARE_PEM_write_cb_ex(name, type) \
+ DECLARE_PEM_write_cb_ex_attr(extern, name, type)
+# define DECLARE_PEM_read_attr(attr, name, type) \
+ DECLARE_PEM_read_bio_attr(attr, name, type) \
+ DECLARE_PEM_read_fp_attr(attr, name, type)
+# define DECLARE_PEM_read_ex_attr(attr, name, type) \
+ DECLARE_PEM_read_bio_ex_attr(attr, name, type) \
+ DECLARE_PEM_read_fp_ex_attr(attr, name, type)
+# define DECLARE_PEM_read(name, type) \
+ DECLARE_PEM_read_attr(extern, name, type)
+# define DECLARE_PEM_read_ex(name, type) \
+ DECLARE_PEM_read_ex_attr(extern, name, type)
+# define DECLARE_PEM_rw_attr(attr, name, type) \
+ DECLARE_PEM_read_attr(attr, name, type) \
+ DECLARE_PEM_write_attr(attr, name, type)
+# define DECLARE_PEM_rw_ex_attr(attr, name, type) \
+ DECLARE_PEM_read_ex_attr(attr, name, type) \
+ DECLARE_PEM_write_ex_attr(attr, name, type)
+# define DECLARE_PEM_rw(name, type) \
+ DECLARE_PEM_rw_attr(extern, name, type)
+# define DECLARE_PEM_rw_ex(name, type) \
+ DECLARE_PEM_rw_ex_attr(extern, name, type)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define DECLARE_PEM_rw_const_attr(attr, name, type) \
+ DECLARE_PEM_read_attr(attr, name, type) \
+ DECLARE_PEM_write_const_attr(attr, name, type)
+# define DECLARE_PEM_rw_const(name, type) \
+ DECLARE_PEM_rw_const_attr(extern, name, type)
+# endif
+# define DECLARE_PEM_rw_cb_attr(attr, name, type) \
+ DECLARE_PEM_read_attr(attr, name, type) \
+ DECLARE_PEM_write_cb_attr(attr, name, type)
+# define DECLARE_PEM_rw_cb_ex_attr(attr, name, type) \
+ DECLARE_PEM_read_ex_attr(attr, name, type) \
+ DECLARE_PEM_write_cb_ex_attr(attr, name, type)
+# define DECLARE_PEM_rw_cb(name, type) \
+ DECLARE_PEM_rw_cb_attr(extern, name, type)
+# define DECLARE_PEM_rw_cb_ex(name, type) \
+ DECLARE_PEM_rw_cb_ex_attr(extern, name, type)
+
+int PEM_get_EVP_CIPHER_INFO(char *header, EVP_CIPHER_INFO *cipher);
+int PEM_do_header(EVP_CIPHER_INFO *cipher, unsigned char *data, long *len,
+ pem_password_cb *callback, void *u);
+
+int PEM_read_bio(BIO *bp, char **name, char **header,
+ unsigned char **data, long *len);
+# define PEM_FLAG_SECURE 0x1
+# define PEM_FLAG_EAY_COMPATIBLE 0x2
+# define PEM_FLAG_ONLY_B64 0x4
+int PEM_read_bio_ex(BIO *bp, char **name, char **header,
+ unsigned char **data, long *len, unsigned int flags);
+int PEM_bytes_read_bio_secmem(unsigned char **pdata, long *plen, char **pnm,
+ const char *name, BIO *bp, pem_password_cb *cb,
+ void *u);
+int PEM_write_bio(BIO *bp, const char *name, const char *hdr,
+ const unsigned char *data, long len);
+int PEM_bytes_read_bio(unsigned char **pdata, long *plen, char **pnm,
+ const char *name, BIO *bp, pem_password_cb *cb,
+ void *u);
+void *PEM_ASN1_read_bio(d2i_of_void *d2i, const char *name, BIO *bp, void **x,
+ pem_password_cb *cb, void *u);
+int PEM_ASN1_write_bio(i2d_of_void *i2d, const char *name, BIO *bp,
+ const void *x, const EVP_CIPHER *enc,
+ const unsigned char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+
+STACK_OF(X509_INFO) *PEM_X509_INFO_read_bio(BIO *bp, STACK_OF(X509_INFO) *sk,
+ pem_password_cb *cb, void *u);
+STACK_OF(X509_INFO)
+*PEM_X509_INFO_read_bio_ex(BIO *bp, STACK_OF(X509_INFO) *sk,
+ pem_password_cb *cb, void *u, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+int PEM_X509_INFO_write_bio(BIO *bp, const X509_INFO *xi, EVP_CIPHER *enc,
+ const unsigned char *kstr, int klen,
+ pem_password_cb *cd, void *u);
+
+#ifndef OPENSSL_NO_STDIO
+int PEM_read(FILE *fp, char **name, char **header,
+ unsigned char **data, long *len);
+int PEM_write(FILE *fp, const char *name, const char *hdr,
+ const unsigned char *data, long len);
+void *PEM_ASN1_read(d2i_of_void *d2i, const char *name, FILE *fp, void **x,
+ pem_password_cb *cb, void *u);
+int PEM_ASN1_write(i2d_of_void *i2d, const char *name, FILE *fp,
+ const void *x, const EVP_CIPHER *enc,
+ const unsigned char *kstr, int klen,
+ pem_password_cb *callback, void *u);
+STACK_OF(X509_INFO) *PEM_X509_INFO_read(FILE *fp, STACK_OF(X509_INFO) *sk,
+ pem_password_cb *cb, void *u);
+STACK_OF(X509_INFO)
+*PEM_X509_INFO_read_ex(FILE *fp, STACK_OF(X509_INFO) *sk, pem_password_cb *cb,
+ void *u, OSSL_LIB_CTX *libctx, const char *propq);
+#endif
+
+int PEM_SignInit(EVP_MD_CTX *ctx, EVP_MD *type);
+int PEM_SignUpdate(EVP_MD_CTX *ctx, const unsigned char *d, unsigned int cnt);
+int PEM_SignFinal(EVP_MD_CTX *ctx, unsigned char *sigret,
+ unsigned int *siglen, EVP_PKEY *pkey);
+
+/* The default pem_password_cb that's used internally */
+int PEM_def_callback(char *buf, int num, int rwflag, void *userdata);
+void PEM_proc_type(char *buf, int type);
+void PEM_dek_info(char *buf, const char *type, int len, const char *str);
+
+# include <openssl/symhacks.h>
+
+DECLARE_PEM_rw(X509, X509)
+DECLARE_PEM_rw(X509_AUX, X509)
+DECLARE_PEM_rw(X509_REQ, X509_REQ)
+DECLARE_PEM_write(X509_REQ_NEW, X509_REQ)
+DECLARE_PEM_rw(X509_CRL, X509_CRL)
+DECLARE_PEM_rw(X509_PUBKEY, X509_PUBKEY)
+DECLARE_PEM_rw(PKCS7, PKCS7)
+DECLARE_PEM_rw(NETSCAPE_CERT_SEQUENCE, NETSCAPE_CERT_SEQUENCE)
+DECLARE_PEM_rw(PKCS8, X509_SIG)
+DECLARE_PEM_rw(PKCS8_PRIV_KEY_INFO, PKCS8_PRIV_KEY_INFO)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+DECLARE_PEM_rw_cb_attr(OSSL_DEPRECATEDIN_3_0, RSAPrivateKey, RSA)
+DECLARE_PEM_rw_attr(OSSL_DEPRECATEDIN_3_0, RSAPublicKey, RSA)
+DECLARE_PEM_rw_attr(OSSL_DEPRECATEDIN_3_0, RSA_PUBKEY, RSA)
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+DECLARE_PEM_rw_cb_attr(OSSL_DEPRECATEDIN_3_0, DSAPrivateKey, DSA)
+DECLARE_PEM_rw_attr(OSSL_DEPRECATEDIN_3_0, DSA_PUBKEY, DSA)
+DECLARE_PEM_rw_attr(OSSL_DEPRECATEDIN_3_0, DSAparams, DSA)
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+DECLARE_PEM_rw_attr(OSSL_DEPRECATEDIN_3_0, ECPKParameters, EC_GROUP)
+DECLARE_PEM_rw_cb_attr(OSSL_DEPRECATEDIN_3_0, ECPrivateKey, EC_KEY)
+DECLARE_PEM_rw_attr(OSSL_DEPRECATEDIN_3_0, EC_PUBKEY, EC_KEY)
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DH
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+DECLARE_PEM_rw_attr(OSSL_DEPRECATEDIN_3_0, DHparams, DH)
+DECLARE_PEM_write_attr(OSSL_DEPRECATEDIN_3_0, DHxparams, DH)
+# endif
+# endif
+DECLARE_PEM_rw_cb_ex(PrivateKey, EVP_PKEY)
+DECLARE_PEM_rw_ex(PUBKEY, EVP_PKEY)
+
+int PEM_write_bio_PrivateKey_traditional(BIO *bp, const EVP_PKEY *x,
+ const EVP_CIPHER *enc,
+ const unsigned char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+
+/* Why do these take a signed char *kstr? */
+int PEM_write_bio_PKCS8PrivateKey_nid(BIO *bp, const EVP_PKEY *x, int nid,
+ const char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+int PEM_write_bio_PKCS8PrivateKey(BIO *, const EVP_PKEY *, const EVP_CIPHER *,
+ const char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+int i2d_PKCS8PrivateKey_bio(BIO *bp, const EVP_PKEY *x, const EVP_CIPHER *enc,
+ const char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+int i2d_PKCS8PrivateKey_nid_bio(BIO *bp, const EVP_PKEY *x, int nid,
+ const char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+EVP_PKEY *d2i_PKCS8PrivateKey_bio(BIO *bp, EVP_PKEY **x, pem_password_cb *cb,
+ void *u);
+
+# ifndef OPENSSL_NO_STDIO
+int i2d_PKCS8PrivateKey_fp(FILE *fp, const EVP_PKEY *x, const EVP_CIPHER *enc,
+ const char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+int i2d_PKCS8PrivateKey_nid_fp(FILE *fp, const EVP_PKEY *x, int nid,
+ const char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+int PEM_write_PKCS8PrivateKey_nid(FILE *fp, const EVP_PKEY *x, int nid,
+ const char *kstr, int klen,
+ pem_password_cb *cb, void *u);
+
+EVP_PKEY *d2i_PKCS8PrivateKey_fp(FILE *fp, EVP_PKEY **x, pem_password_cb *cb,
+ void *u);
+
+int PEM_write_PKCS8PrivateKey(FILE *fp, const EVP_PKEY *x, const EVP_CIPHER *enc,
+ const char *kstr, int klen,
+ pem_password_cb *cd, void *u);
+# endif
+EVP_PKEY *PEM_read_bio_Parameters_ex(BIO *bp, EVP_PKEY **x,
+ OSSL_LIB_CTX *libctx, const char *propq);
+EVP_PKEY *PEM_read_bio_Parameters(BIO *bp, EVP_PKEY **x);
+int PEM_write_bio_Parameters(BIO *bp, const EVP_PKEY *x);
+
+EVP_PKEY *b2i_PrivateKey(const unsigned char **in, long length);
+EVP_PKEY *b2i_PublicKey(const unsigned char **in, long length);
+EVP_PKEY *b2i_PrivateKey_bio(BIO *in);
+EVP_PKEY *b2i_PublicKey_bio(BIO *in);
+int i2b_PrivateKey_bio(BIO *out, const EVP_PKEY *pk);
+int i2b_PublicKey_bio(BIO *out, const EVP_PKEY *pk);
+EVP_PKEY *b2i_PVK_bio(BIO *in, pem_password_cb *cb, void *u);
+EVP_PKEY *b2i_PVK_bio_ex(BIO *in, pem_password_cb *cb, void *u,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int i2b_PVK_bio(BIO *out, const EVP_PKEY *pk, int enclevel,
+ pem_password_cb *cb, void *u);
+int i2b_PVK_bio_ex(BIO *out, const EVP_PKEY *pk, int enclevel,
+ pem_password_cb *cb, void *u,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/pem2.h b/include/openssl/pem2.h
new file mode 100644
index 00000000..a8a5325b
--- /dev/null
+++ b/include/openssl/pem2.h
@@ -0,0 +1,19 @@
+/*
+ * Copyright 1999-2018 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PEM2_H
+# define OPENSSL_PEM2_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_PEM2_H
+# endif
+# include <openssl/pemerr.h>
+#endif
diff --git a/include/openssl/pemerr.h b/include/openssl/pemerr.h
new file mode 100644
index 00000000..18f6d9ef
--- /dev/null
+++ b/include/openssl/pemerr.h
@@ -0,0 +1,58 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PEMERR_H
+# define OPENSSL_PEMERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * PEM reason codes.
+ */
+# define PEM_R_BAD_BASE64_DECODE 100
+# define PEM_R_BAD_DECRYPT 101
+# define PEM_R_BAD_END_LINE 102
+# define PEM_R_BAD_IV_CHARS 103
+# define PEM_R_BAD_MAGIC_NUMBER 116
+# define PEM_R_BAD_PASSWORD_READ 104
+# define PEM_R_BAD_VERSION_NUMBER 117
+# define PEM_R_BIO_WRITE_FAILURE 118
+# define PEM_R_CIPHER_IS_NULL 127
+# define PEM_R_ERROR_CONVERTING_PRIVATE_KEY 115
+# define PEM_R_EXPECTING_DSS_KEY_BLOB 131
+# define PEM_R_EXPECTING_PRIVATE_KEY_BLOB 119
+# define PEM_R_EXPECTING_PUBLIC_KEY_BLOB 120
+# define PEM_R_EXPECTING_RSA_KEY_BLOB 132
+# define PEM_R_HEADER_TOO_LONG 128
+# define PEM_R_INCONSISTENT_HEADER 121
+# define PEM_R_KEYBLOB_HEADER_PARSE_ERROR 122
+# define PEM_R_KEYBLOB_TOO_SHORT 123
+# define PEM_R_MISSING_DEK_IV 129
+# define PEM_R_NOT_DEK_INFO 105
+# define PEM_R_NOT_ENCRYPTED 106
+# define PEM_R_NOT_PROC_TYPE 107
+# define PEM_R_NO_START_LINE 108
+# define PEM_R_PROBLEMS_GETTING_PASSWORD 109
+# define PEM_R_PVK_DATA_TOO_SHORT 124
+# define PEM_R_PVK_TOO_SHORT 125
+# define PEM_R_READ_KEY 111
+# define PEM_R_SHORT_HEADER 112
+# define PEM_R_UNEXPECTED_DEK_IV 130
+# define PEM_R_UNSUPPORTED_CIPHER 113
+# define PEM_R_UNSUPPORTED_ENCRYPTION 114
+# define PEM_R_UNSUPPORTED_KEY_COMPONENTS 126
+# define PEM_R_UNSUPPORTED_PUBLIC_KEY_TYPE 110
+
+#endif
diff --git a/include/openssl/pkcs12.h b/include/openssl/pkcs12.h
new file mode 100644
index 00000000..f0da0867
--- /dev/null
+++ b/include/openssl/pkcs12.h
@@ -0,0 +1,350 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\pkcs12.h.in
+ *
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_PKCS12_H
+# define OPENSSL_PKCS12_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_PKCS12_H
+# endif
+
+# include <openssl/bio.h>
+# include <openssl/core.h>
+# include <openssl/x509.h>
+# include <openssl/pkcs12err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define PKCS12_KEY_ID 1
+# define PKCS12_IV_ID 2
+# define PKCS12_MAC_ID 3
+
+/* Default iteration count */
+# ifndef PKCS12_DEFAULT_ITER
+# define PKCS12_DEFAULT_ITER PKCS5_DEFAULT_ITER
+# endif
+
+# define PKCS12_MAC_KEY_LENGTH 20
+
+# define PKCS12_SALT_LEN 8
+
+/* It's not clear if these are actually needed... */
+# define PKCS12_key_gen PKCS12_key_gen_utf8
+# define PKCS12_add_friendlyname PKCS12_add_friendlyname_utf8
+
+/* MS key usage constants */
+
+# define KEY_EX 0x10
+# define KEY_SIG 0x80
+
+typedef struct PKCS12_MAC_DATA_st PKCS12_MAC_DATA;
+
+typedef struct PKCS12_st PKCS12;
+
+typedef struct PKCS12_SAFEBAG_st PKCS12_SAFEBAG;
+
+SKM_DEFINE_STACK_OF_INTERNAL(PKCS12_SAFEBAG, PKCS12_SAFEBAG, PKCS12_SAFEBAG)
+#define sk_PKCS12_SAFEBAG_num(sk) OPENSSL_sk_num(ossl_check_const_PKCS12_SAFEBAG_sk_type(sk))
+#define sk_PKCS12_SAFEBAG_value(sk, idx) ((PKCS12_SAFEBAG *)OPENSSL_sk_value(ossl_check_const_PKCS12_SAFEBAG_sk_type(sk), (idx)))
+#define sk_PKCS12_SAFEBAG_new(cmp) ((STACK_OF(PKCS12_SAFEBAG) *)OPENSSL_sk_new(ossl_check_PKCS12_SAFEBAG_compfunc_type(cmp)))
+#define sk_PKCS12_SAFEBAG_new_null() ((STACK_OF(PKCS12_SAFEBAG) *)OPENSSL_sk_new_null())
+#define sk_PKCS12_SAFEBAG_new_reserve(cmp, n) ((STACK_OF(PKCS12_SAFEBAG) *)OPENSSL_sk_new_reserve(ossl_check_PKCS12_SAFEBAG_compfunc_type(cmp), (n)))
+#define sk_PKCS12_SAFEBAG_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_PKCS12_SAFEBAG_sk_type(sk), (n))
+#define sk_PKCS12_SAFEBAG_free(sk) OPENSSL_sk_free(ossl_check_PKCS12_SAFEBAG_sk_type(sk))
+#define sk_PKCS12_SAFEBAG_zero(sk) OPENSSL_sk_zero(ossl_check_PKCS12_SAFEBAG_sk_type(sk))
+#define sk_PKCS12_SAFEBAG_delete(sk, i) ((PKCS12_SAFEBAG *)OPENSSL_sk_delete(ossl_check_PKCS12_SAFEBAG_sk_type(sk), (i)))
+#define sk_PKCS12_SAFEBAG_delete_ptr(sk, ptr) ((PKCS12_SAFEBAG *)OPENSSL_sk_delete_ptr(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_type(ptr)))
+#define sk_PKCS12_SAFEBAG_push(sk, ptr) OPENSSL_sk_push(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_type(ptr))
+#define sk_PKCS12_SAFEBAG_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_type(ptr))
+#define sk_PKCS12_SAFEBAG_pop(sk) ((PKCS12_SAFEBAG *)OPENSSL_sk_pop(ossl_check_PKCS12_SAFEBAG_sk_type(sk)))
+#define sk_PKCS12_SAFEBAG_shift(sk) ((PKCS12_SAFEBAG *)OPENSSL_sk_shift(ossl_check_PKCS12_SAFEBAG_sk_type(sk)))
+#define sk_PKCS12_SAFEBAG_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_PKCS12_SAFEBAG_sk_type(sk),ossl_check_PKCS12_SAFEBAG_freefunc_type(freefunc))
+#define sk_PKCS12_SAFEBAG_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_type(ptr), (idx))
+#define sk_PKCS12_SAFEBAG_set(sk, idx, ptr) ((PKCS12_SAFEBAG *)OPENSSL_sk_set(ossl_check_PKCS12_SAFEBAG_sk_type(sk), (idx), ossl_check_PKCS12_SAFEBAG_type(ptr)))
+#define sk_PKCS12_SAFEBAG_find(sk, ptr) OPENSSL_sk_find(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_type(ptr))
+#define sk_PKCS12_SAFEBAG_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_type(ptr))
+#define sk_PKCS12_SAFEBAG_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_type(ptr), pnum)
+#define sk_PKCS12_SAFEBAG_sort(sk) OPENSSL_sk_sort(ossl_check_PKCS12_SAFEBAG_sk_type(sk))
+#define sk_PKCS12_SAFEBAG_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_PKCS12_SAFEBAG_sk_type(sk))
+#define sk_PKCS12_SAFEBAG_dup(sk) ((STACK_OF(PKCS12_SAFEBAG) *)OPENSSL_sk_dup(ossl_check_const_PKCS12_SAFEBAG_sk_type(sk)))
+#define sk_PKCS12_SAFEBAG_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(PKCS12_SAFEBAG) *)OPENSSL_sk_deep_copy(ossl_check_const_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_copyfunc_type(copyfunc), ossl_check_PKCS12_SAFEBAG_freefunc_type(freefunc)))
+#define sk_PKCS12_SAFEBAG_set_cmp_func(sk, cmp) ((sk_PKCS12_SAFEBAG_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_PKCS12_SAFEBAG_sk_type(sk), ossl_check_PKCS12_SAFEBAG_compfunc_type(cmp)))
+
+
+typedef struct pkcs12_bag_st PKCS12_BAGS;
+
+# define PKCS12_ERROR 0
+# define PKCS12_OK 1
+
+/* Compatibility macros */
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+
+# define M_PKCS12_bag_type PKCS12_bag_type
+# define M_PKCS12_cert_bag_type PKCS12_cert_bag_type
+# define M_PKCS12_crl_bag_type PKCS12_cert_bag_type
+
+# define PKCS12_certbag2x509 PKCS12_SAFEBAG_get1_cert
+# define PKCS12_certbag2scrl PKCS12_SAFEBAG_get1_crl
+# define PKCS12_bag_type PKCS12_SAFEBAG_get_nid
+# define PKCS12_cert_bag_type PKCS12_SAFEBAG_get_bag_nid
+# define PKCS12_x5092certbag PKCS12_SAFEBAG_create_cert
+# define PKCS12_x509crl2certbag PKCS12_SAFEBAG_create_crl
+# define PKCS12_MAKE_KEYBAG PKCS12_SAFEBAG_create0_p8inf
+# define PKCS12_MAKE_SHKEYBAG PKCS12_SAFEBAG_create_pkcs8_encrypt
+
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 ASN1_TYPE *PKCS12_get_attr(const PKCS12_SAFEBAG *bag,
+ int attr_nid);
+#endif
+
+ASN1_TYPE *PKCS8_get_attr(PKCS8_PRIV_KEY_INFO *p8, int attr_nid);
+int PKCS12_mac_present(const PKCS12 *p12);
+void PKCS12_get0_mac(const ASN1_OCTET_STRING **pmac,
+ const X509_ALGOR **pmacalg,
+ const ASN1_OCTET_STRING **psalt,
+ const ASN1_INTEGER **piter,
+ const PKCS12 *p12);
+
+const ASN1_TYPE *PKCS12_SAFEBAG_get0_attr(const PKCS12_SAFEBAG *bag,
+ int attr_nid);
+const ASN1_OBJECT *PKCS12_SAFEBAG_get0_type(const PKCS12_SAFEBAG *bag);
+int PKCS12_SAFEBAG_get_nid(const PKCS12_SAFEBAG *bag);
+int PKCS12_SAFEBAG_get_bag_nid(const PKCS12_SAFEBAG *bag);
+const ASN1_TYPE *PKCS12_SAFEBAG_get0_bag_obj(const PKCS12_SAFEBAG *bag);
+const ASN1_OBJECT *PKCS12_SAFEBAG_get0_bag_type(const PKCS12_SAFEBAG *bag);
+
+X509 *PKCS12_SAFEBAG_get1_cert(const PKCS12_SAFEBAG *bag);
+X509_CRL *PKCS12_SAFEBAG_get1_crl(const PKCS12_SAFEBAG *bag);
+const STACK_OF(PKCS12_SAFEBAG) *
+PKCS12_SAFEBAG_get0_safes(const PKCS12_SAFEBAG *bag);
+const PKCS8_PRIV_KEY_INFO *PKCS12_SAFEBAG_get0_p8inf(const PKCS12_SAFEBAG *bag);
+const X509_SIG *PKCS12_SAFEBAG_get0_pkcs8(const PKCS12_SAFEBAG *bag);
+
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_cert(X509 *x509);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_crl(X509_CRL *crl);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_secret(int type, int vtype, const unsigned char *value, int len);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_p8inf(PKCS8_PRIV_KEY_INFO *p8);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_pkcs8(X509_SIG *p8);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt(int pbe_nid,
+ const char *pass,
+ int passlen,
+ unsigned char *salt,
+ int saltlen, int iter,
+ PKCS8_PRIV_KEY_INFO *p8inf);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(int pbe_nid,
+ const char *pass,
+ int passlen,
+ unsigned char *salt,
+ int saltlen, int iter,
+ PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+PKCS12_SAFEBAG *PKCS12_item_pack_safebag(void *obj, const ASN1_ITEM *it,
+ int nid1, int nid2);
+PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(const X509_SIG *p8, const char *pass,
+ int passlen);
+PKCS8_PRIV_KEY_INFO *PKCS8_decrypt_ex(const X509_SIG *p8, const char *pass,
+ int passlen, OSSL_LIB_CTX *ctx,
+ const char *propq);
+PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey(const PKCS12_SAFEBAG *bag,
+ const char *pass, int passlen);
+PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey_ex(const PKCS12_SAFEBAG *bag,
+ const char *pass, int passlen,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher,
+ const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8);
+X509_SIG *PKCS8_encrypt_ex(int pbe_nid, const EVP_CIPHER *cipher,
+ const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8,
+ OSSL_LIB_CTX *ctx, const char *propq);
+X509_SIG *PKCS8_set0_pbe(const char *pass, int passlen,
+ PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe);
+X509_SIG *PKCS8_set0_pbe_ex(const char *pass, int passlen,
+ PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe,
+ OSSL_LIB_CTX *ctx, const char *propq);
+PKCS7 *PKCS12_pack_p7data(STACK_OF(PKCS12_SAFEBAG) *sk);
+STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7data(PKCS7 *p7);
+PKCS7 *PKCS12_pack_p7encdata(int pbe_nid, const char *pass, int passlen,
+ unsigned char *salt, int saltlen, int iter,
+ STACK_OF(PKCS12_SAFEBAG) *bags);
+PKCS7 *PKCS12_pack_p7encdata_ex(int pbe_nid, const char *pass, int passlen,
+ unsigned char *salt, int saltlen, int iter,
+ STACK_OF(PKCS12_SAFEBAG) *bags,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7encdata(PKCS7 *p7, const char *pass,
+ int passlen);
+
+int PKCS12_pack_authsafes(PKCS12 *p12, STACK_OF(PKCS7) *safes);
+STACK_OF(PKCS7) *PKCS12_unpack_authsafes(const PKCS12 *p12);
+
+int PKCS12_add_localkeyid(PKCS12_SAFEBAG *bag, unsigned char *name,
+ int namelen);
+int PKCS12_add_friendlyname_asc(PKCS12_SAFEBAG *bag, const char *name,
+ int namelen);
+int PKCS12_add_friendlyname_utf8(PKCS12_SAFEBAG *bag, const char *name,
+ int namelen);
+int PKCS12_add_CSPName_asc(PKCS12_SAFEBAG *bag, const char *name,
+ int namelen);
+int PKCS12_add_friendlyname_uni(PKCS12_SAFEBAG *bag,
+ const unsigned char *name, int namelen);
+int PKCS12_add1_attr_by_NID(PKCS12_SAFEBAG *bag, int nid, int type,
+ const unsigned char *bytes, int len);
+int PKCS12_add1_attr_by_txt(PKCS12_SAFEBAG *bag, const char *attrname, int type,
+ const unsigned char *bytes, int len);
+int PKCS8_add_keyusage(PKCS8_PRIV_KEY_INFO *p8, int usage);
+ASN1_TYPE *PKCS12_get_attr_gen(const STACK_OF(X509_ATTRIBUTE) *attrs,
+ int attr_nid);
+char *PKCS12_get_friendlyname(PKCS12_SAFEBAG *bag);
+const STACK_OF(X509_ATTRIBUTE) *
+PKCS12_SAFEBAG_get0_attrs(const PKCS12_SAFEBAG *bag);
+unsigned char *PKCS12_pbe_crypt(const X509_ALGOR *algor,
+ const char *pass, int passlen,
+ const unsigned char *in, int inlen,
+ unsigned char **data, int *datalen,
+ int en_de);
+unsigned char *PKCS12_pbe_crypt_ex(const X509_ALGOR *algor,
+ const char *pass, int passlen,
+ const unsigned char *in, int inlen,
+ unsigned char **data, int *datalen,
+ int en_de, OSSL_LIB_CTX *libctx,
+ const char *propq);
+void *PKCS12_item_decrypt_d2i(const X509_ALGOR *algor, const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ const ASN1_OCTET_STRING *oct, int zbuf);
+void *PKCS12_item_decrypt_d2i_ex(const X509_ALGOR *algor, const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ const ASN1_OCTET_STRING *oct, int zbuf,
+ OSSL_LIB_CTX *libctx,
+ const char *propq);
+ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor,
+ const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ void *obj, int zbuf);
+ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt_ex(X509_ALGOR *algor,
+ const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ void *obj, int zbuf,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+PKCS12 *PKCS12_init(int mode);
+PKCS12 *PKCS12_init_ex(int mode, OSSL_LIB_CTX *ctx, const char *propq);
+
+int PKCS12_key_gen_asc(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type);
+int PKCS12_key_gen_asc_ex(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type,
+ OSSL_LIB_CTX *ctx, const char *propq);
+int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type);
+int PKCS12_key_gen_uni_ex(unsigned char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type,
+ OSSL_LIB_CTX *ctx, const char *propq);
+int PKCS12_key_gen_utf8(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type);
+int PKCS12_key_gen_utf8_ex(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int PKCS12_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md_type, int en_de);
+int PKCS12_PBE_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md_type, int en_de,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen,
+ unsigned char *mac, unsigned int *maclen);
+int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen);
+int PKCS12_set_mac(PKCS12 *p12, const char *pass, int passlen,
+ unsigned char *salt, int saltlen, int iter,
+ const EVP_MD *md_type);
+int PKCS12_setup_mac(PKCS12 *p12, int iter, unsigned char *salt,
+ int saltlen, const EVP_MD *md_type);
+unsigned char *OPENSSL_asc2uni(const char *asc, int asclen,
+ unsigned char **uni, int *unilen);
+char *OPENSSL_uni2asc(const unsigned char *uni, int unilen);
+unsigned char *OPENSSL_utf82uni(const char *asc, int asclen,
+ unsigned char **uni, int *unilen);
+char *OPENSSL_uni2utf8(const unsigned char *uni, int unilen);
+
+DECLARE_ASN1_FUNCTIONS(PKCS12)
+DECLARE_ASN1_FUNCTIONS(PKCS12_MAC_DATA)
+DECLARE_ASN1_FUNCTIONS(PKCS12_SAFEBAG)
+DECLARE_ASN1_FUNCTIONS(PKCS12_BAGS)
+
+DECLARE_ASN1_ITEM(PKCS12_SAFEBAGS)
+DECLARE_ASN1_ITEM(PKCS12_AUTHSAFES)
+
+void PKCS12_PBE_add(void);
+int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert,
+ STACK_OF(X509) **ca);
+PKCS12 *PKCS12_create(const char *pass, const char *name, EVP_PKEY *pkey,
+ X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert,
+ int iter, int mac_iter, int keytype);
+PKCS12 *PKCS12_create_ex(const char *pass, const char *name, EVP_PKEY *pkey,
+ X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert,
+ int iter, int mac_iter, int keytype,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert);
+PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags,
+ EVP_PKEY *key, int key_usage, int iter,
+ int key_nid, const char *pass);
+PKCS12_SAFEBAG *PKCS12_add_key_ex(STACK_OF(PKCS12_SAFEBAG) **pbags,
+ EVP_PKEY *key, int key_usage, int iter,
+ int key_nid, const char *pass,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+PKCS12_SAFEBAG *PKCS12_add_secret(STACK_OF(PKCS12_SAFEBAG) **pbags,
+ int nid_type, const unsigned char *value, int len);
+int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags,
+ int safe_nid, int iter, const char *pass);
+int PKCS12_add_safe_ex(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags,
+ int safe_nid, int iter, const char *pass,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int p7_nid);
+PKCS12 *PKCS12_add_safes_ex(STACK_OF(PKCS7) *safes, int p7_nid,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int i2d_PKCS12_bio(BIO *bp, const PKCS12 *p12);
+# ifndef OPENSSL_NO_STDIO
+int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12);
+# endif
+PKCS12 *d2i_PKCS12_bio(BIO *bp, PKCS12 **p12);
+# ifndef OPENSSL_NO_STDIO
+PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12);
+# endif
+int PKCS12_newpass(PKCS12 *p12, const char *oldpass, const char *newpass);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/pkcs12.h.in b/include/openssl/pkcs12.h.in
new file mode 100644
index 00000000..c98eebfb
--- /dev/null
+++ b/include/openssl/pkcs12.h.in
@@ -0,0 +1,327 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_PKCS12_H
+# define OPENSSL_PKCS12_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_PKCS12_H
+# endif
+
+# include <openssl/bio.h>
+# include <openssl/core.h>
+# include <openssl/x509.h>
+# include <openssl/pkcs12err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define PKCS12_KEY_ID 1
+# define PKCS12_IV_ID 2
+# define PKCS12_MAC_ID 3
+
+/* Default iteration count */
+# ifndef PKCS12_DEFAULT_ITER
+# define PKCS12_DEFAULT_ITER PKCS5_DEFAULT_ITER
+# endif
+
+# define PKCS12_MAC_KEY_LENGTH 20
+
+# define PKCS12_SALT_LEN 8
+
+/* It's not clear if these are actually needed... */
+# define PKCS12_key_gen PKCS12_key_gen_utf8
+# define PKCS12_add_friendlyname PKCS12_add_friendlyname_utf8
+
+/* MS key usage constants */
+
+# define KEY_EX 0x10
+# define KEY_SIG 0x80
+
+typedef struct PKCS12_MAC_DATA_st PKCS12_MAC_DATA;
+
+typedef struct PKCS12_st PKCS12;
+
+typedef struct PKCS12_SAFEBAG_st PKCS12_SAFEBAG;
+
+{-
+ generate_stack_macros("PKCS12_SAFEBAG");
+-}
+
+typedef struct pkcs12_bag_st PKCS12_BAGS;
+
+# define PKCS12_ERROR 0
+# define PKCS12_OK 1
+
+/* Compatibility macros */
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+
+# define M_PKCS12_bag_type PKCS12_bag_type
+# define M_PKCS12_cert_bag_type PKCS12_cert_bag_type
+# define M_PKCS12_crl_bag_type PKCS12_cert_bag_type
+
+# define PKCS12_certbag2x509 PKCS12_SAFEBAG_get1_cert
+# define PKCS12_certbag2scrl PKCS12_SAFEBAG_get1_crl
+# define PKCS12_bag_type PKCS12_SAFEBAG_get_nid
+# define PKCS12_cert_bag_type PKCS12_SAFEBAG_get_bag_nid
+# define PKCS12_x5092certbag PKCS12_SAFEBAG_create_cert
+# define PKCS12_x509crl2certbag PKCS12_SAFEBAG_create_crl
+# define PKCS12_MAKE_KEYBAG PKCS12_SAFEBAG_create0_p8inf
+# define PKCS12_MAKE_SHKEYBAG PKCS12_SAFEBAG_create_pkcs8_encrypt
+
+#endif
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 ASN1_TYPE *PKCS12_get_attr(const PKCS12_SAFEBAG *bag,
+ int attr_nid);
+#endif
+
+ASN1_TYPE *PKCS8_get_attr(PKCS8_PRIV_KEY_INFO *p8, int attr_nid);
+int PKCS12_mac_present(const PKCS12 *p12);
+void PKCS12_get0_mac(const ASN1_OCTET_STRING **pmac,
+ const X509_ALGOR **pmacalg,
+ const ASN1_OCTET_STRING **psalt,
+ const ASN1_INTEGER **piter,
+ const PKCS12 *p12);
+
+const ASN1_TYPE *PKCS12_SAFEBAG_get0_attr(const PKCS12_SAFEBAG *bag,
+ int attr_nid);
+const ASN1_OBJECT *PKCS12_SAFEBAG_get0_type(const PKCS12_SAFEBAG *bag);
+int PKCS12_SAFEBAG_get_nid(const PKCS12_SAFEBAG *bag);
+int PKCS12_SAFEBAG_get_bag_nid(const PKCS12_SAFEBAG *bag);
+const ASN1_TYPE *PKCS12_SAFEBAG_get0_bag_obj(const PKCS12_SAFEBAG *bag);
+const ASN1_OBJECT *PKCS12_SAFEBAG_get0_bag_type(const PKCS12_SAFEBAG *bag);
+
+X509 *PKCS12_SAFEBAG_get1_cert(const PKCS12_SAFEBAG *bag);
+X509_CRL *PKCS12_SAFEBAG_get1_crl(const PKCS12_SAFEBAG *bag);
+const STACK_OF(PKCS12_SAFEBAG) *
+PKCS12_SAFEBAG_get0_safes(const PKCS12_SAFEBAG *bag);
+const PKCS8_PRIV_KEY_INFO *PKCS12_SAFEBAG_get0_p8inf(const PKCS12_SAFEBAG *bag);
+const X509_SIG *PKCS12_SAFEBAG_get0_pkcs8(const PKCS12_SAFEBAG *bag);
+
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_cert(X509 *x509);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_crl(X509_CRL *crl);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_secret(int type, int vtype, const unsigned char *value, int len);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_p8inf(PKCS8_PRIV_KEY_INFO *p8);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create0_pkcs8(X509_SIG *p8);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt(int pbe_nid,
+ const char *pass,
+ int passlen,
+ unsigned char *salt,
+ int saltlen, int iter,
+ PKCS8_PRIV_KEY_INFO *p8inf);
+PKCS12_SAFEBAG *PKCS12_SAFEBAG_create_pkcs8_encrypt_ex(int pbe_nid,
+ const char *pass,
+ int passlen,
+ unsigned char *salt,
+ int saltlen, int iter,
+ PKCS8_PRIV_KEY_INFO *p8inf,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+
+PKCS12_SAFEBAG *PKCS12_item_pack_safebag(void *obj, const ASN1_ITEM *it,
+ int nid1, int nid2);
+PKCS8_PRIV_KEY_INFO *PKCS8_decrypt(const X509_SIG *p8, const char *pass,
+ int passlen);
+PKCS8_PRIV_KEY_INFO *PKCS8_decrypt_ex(const X509_SIG *p8, const char *pass,
+ int passlen, OSSL_LIB_CTX *ctx,
+ const char *propq);
+PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey(const PKCS12_SAFEBAG *bag,
+ const char *pass, int passlen);
+PKCS8_PRIV_KEY_INFO *PKCS12_decrypt_skey_ex(const PKCS12_SAFEBAG *bag,
+ const char *pass, int passlen,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+X509_SIG *PKCS8_encrypt(int pbe_nid, const EVP_CIPHER *cipher,
+ const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8);
+X509_SIG *PKCS8_encrypt_ex(int pbe_nid, const EVP_CIPHER *cipher,
+ const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int iter, PKCS8_PRIV_KEY_INFO *p8,
+ OSSL_LIB_CTX *ctx, const char *propq);
+X509_SIG *PKCS8_set0_pbe(const char *pass, int passlen,
+ PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe);
+X509_SIG *PKCS8_set0_pbe_ex(const char *pass, int passlen,
+ PKCS8_PRIV_KEY_INFO *p8inf, X509_ALGOR *pbe,
+ OSSL_LIB_CTX *ctx, const char *propq);
+PKCS7 *PKCS12_pack_p7data(STACK_OF(PKCS12_SAFEBAG) *sk);
+STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7data(PKCS7 *p7);
+PKCS7 *PKCS12_pack_p7encdata(int pbe_nid, const char *pass, int passlen,
+ unsigned char *salt, int saltlen, int iter,
+ STACK_OF(PKCS12_SAFEBAG) *bags);
+PKCS7 *PKCS12_pack_p7encdata_ex(int pbe_nid, const char *pass, int passlen,
+ unsigned char *salt, int saltlen, int iter,
+ STACK_OF(PKCS12_SAFEBAG) *bags,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+STACK_OF(PKCS12_SAFEBAG) *PKCS12_unpack_p7encdata(PKCS7 *p7, const char *pass,
+ int passlen);
+
+int PKCS12_pack_authsafes(PKCS12 *p12, STACK_OF(PKCS7) *safes);
+STACK_OF(PKCS7) *PKCS12_unpack_authsafes(const PKCS12 *p12);
+
+int PKCS12_add_localkeyid(PKCS12_SAFEBAG *bag, unsigned char *name,
+ int namelen);
+int PKCS12_add_friendlyname_asc(PKCS12_SAFEBAG *bag, const char *name,
+ int namelen);
+int PKCS12_add_friendlyname_utf8(PKCS12_SAFEBAG *bag, const char *name,
+ int namelen);
+int PKCS12_add_CSPName_asc(PKCS12_SAFEBAG *bag, const char *name,
+ int namelen);
+int PKCS12_add_friendlyname_uni(PKCS12_SAFEBAG *bag,
+ const unsigned char *name, int namelen);
+int PKCS12_add1_attr_by_NID(PKCS12_SAFEBAG *bag, int nid, int type,
+ const unsigned char *bytes, int len);
+int PKCS12_add1_attr_by_txt(PKCS12_SAFEBAG *bag, const char *attrname, int type,
+ const unsigned char *bytes, int len);
+int PKCS8_add_keyusage(PKCS8_PRIV_KEY_INFO *p8, int usage);
+ASN1_TYPE *PKCS12_get_attr_gen(const STACK_OF(X509_ATTRIBUTE) *attrs,
+ int attr_nid);
+char *PKCS12_get_friendlyname(PKCS12_SAFEBAG *bag);
+const STACK_OF(X509_ATTRIBUTE) *
+PKCS12_SAFEBAG_get0_attrs(const PKCS12_SAFEBAG *bag);
+unsigned char *PKCS12_pbe_crypt(const X509_ALGOR *algor,
+ const char *pass, int passlen,
+ const unsigned char *in, int inlen,
+ unsigned char **data, int *datalen,
+ int en_de);
+unsigned char *PKCS12_pbe_crypt_ex(const X509_ALGOR *algor,
+ const char *pass, int passlen,
+ const unsigned char *in, int inlen,
+ unsigned char **data, int *datalen,
+ int en_de, OSSL_LIB_CTX *libctx,
+ const char *propq);
+void *PKCS12_item_decrypt_d2i(const X509_ALGOR *algor, const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ const ASN1_OCTET_STRING *oct, int zbuf);
+void *PKCS12_item_decrypt_d2i_ex(const X509_ALGOR *algor, const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ const ASN1_OCTET_STRING *oct, int zbuf,
+ OSSL_LIB_CTX *libctx,
+ const char *propq);
+ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt(X509_ALGOR *algor,
+ const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ void *obj, int zbuf);
+ASN1_OCTET_STRING *PKCS12_item_i2d_encrypt_ex(X509_ALGOR *algor,
+ const ASN1_ITEM *it,
+ const char *pass, int passlen,
+ void *obj, int zbuf,
+ OSSL_LIB_CTX *ctx,
+ const char *propq);
+PKCS12 *PKCS12_init(int mode);
+PKCS12 *PKCS12_init_ex(int mode, OSSL_LIB_CTX *ctx, const char *propq);
+
+int PKCS12_key_gen_asc(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type);
+int PKCS12_key_gen_asc_ex(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type,
+ OSSL_LIB_CTX *ctx, const char *propq);
+int PKCS12_key_gen_uni(unsigned char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type);
+int PKCS12_key_gen_uni_ex(unsigned char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type,
+ OSSL_LIB_CTX *ctx, const char *propq);
+int PKCS12_key_gen_utf8(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type);
+int PKCS12_key_gen_utf8_ex(const char *pass, int passlen, unsigned char *salt,
+ int saltlen, int id, int iter, int n,
+ unsigned char *out, const EVP_MD *md_type,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int PKCS12_PBE_keyivgen(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md_type, int en_de);
+int PKCS12_PBE_keyivgen_ex(EVP_CIPHER_CTX *ctx, const char *pass, int passlen,
+ ASN1_TYPE *param, const EVP_CIPHER *cipher,
+ const EVP_MD *md_type, int en_de,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int PKCS12_gen_mac(PKCS12 *p12, const char *pass, int passlen,
+ unsigned char *mac, unsigned int *maclen);
+int PKCS12_verify_mac(PKCS12 *p12, const char *pass, int passlen);
+int PKCS12_set_mac(PKCS12 *p12, const char *pass, int passlen,
+ unsigned char *salt, int saltlen, int iter,
+ const EVP_MD *md_type);
+int PKCS12_setup_mac(PKCS12 *p12, int iter, unsigned char *salt,
+ int saltlen, const EVP_MD *md_type);
+unsigned char *OPENSSL_asc2uni(const char *asc, int asclen,
+ unsigned char **uni, int *unilen);
+char *OPENSSL_uni2asc(const unsigned char *uni, int unilen);
+unsigned char *OPENSSL_utf82uni(const char *asc, int asclen,
+ unsigned char **uni, int *unilen);
+char *OPENSSL_uni2utf8(const unsigned char *uni, int unilen);
+
+DECLARE_ASN1_FUNCTIONS(PKCS12)
+DECLARE_ASN1_FUNCTIONS(PKCS12_MAC_DATA)
+DECLARE_ASN1_FUNCTIONS(PKCS12_SAFEBAG)
+DECLARE_ASN1_FUNCTIONS(PKCS12_BAGS)
+
+DECLARE_ASN1_ITEM(PKCS12_SAFEBAGS)
+DECLARE_ASN1_ITEM(PKCS12_AUTHSAFES)
+
+void PKCS12_PBE_add(void);
+int PKCS12_parse(PKCS12 *p12, const char *pass, EVP_PKEY **pkey, X509 **cert,
+ STACK_OF(X509) **ca);
+PKCS12 *PKCS12_create(const char *pass, const char *name, EVP_PKEY *pkey,
+ X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert,
+ int iter, int mac_iter, int keytype);
+PKCS12 *PKCS12_create_ex(const char *pass, const char *name, EVP_PKEY *pkey,
+ X509 *cert, STACK_OF(X509) *ca, int nid_key, int nid_cert,
+ int iter, int mac_iter, int keytype,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+PKCS12_SAFEBAG *PKCS12_add_cert(STACK_OF(PKCS12_SAFEBAG) **pbags, X509 *cert);
+PKCS12_SAFEBAG *PKCS12_add_key(STACK_OF(PKCS12_SAFEBAG) **pbags,
+ EVP_PKEY *key, int key_usage, int iter,
+ int key_nid, const char *pass);
+PKCS12_SAFEBAG *PKCS12_add_key_ex(STACK_OF(PKCS12_SAFEBAG) **pbags,
+ EVP_PKEY *key, int key_usage, int iter,
+ int key_nid, const char *pass,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+PKCS12_SAFEBAG *PKCS12_add_secret(STACK_OF(PKCS12_SAFEBAG) **pbags,
+ int nid_type, const unsigned char *value, int len);
+int PKCS12_add_safe(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags,
+ int safe_nid, int iter, const char *pass);
+int PKCS12_add_safe_ex(STACK_OF(PKCS7) **psafes, STACK_OF(PKCS12_SAFEBAG) *bags,
+ int safe_nid, int iter, const char *pass,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+PKCS12 *PKCS12_add_safes(STACK_OF(PKCS7) *safes, int p7_nid);
+PKCS12 *PKCS12_add_safes_ex(STACK_OF(PKCS7) *safes, int p7_nid,
+ OSSL_LIB_CTX *ctx, const char *propq);
+
+int i2d_PKCS12_bio(BIO *bp, const PKCS12 *p12);
+# ifndef OPENSSL_NO_STDIO
+int i2d_PKCS12_fp(FILE *fp, const PKCS12 *p12);
+# endif
+PKCS12 *d2i_PKCS12_bio(BIO *bp, PKCS12 **p12);
+# ifndef OPENSSL_NO_STDIO
+PKCS12 *d2i_PKCS12_fp(FILE *fp, PKCS12 **p12);
+# endif
+int PKCS12_newpass(PKCS12 *p12, const char *oldpass, const char *newpass);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/pkcs12err.h b/include/openssl/pkcs12err.h
new file mode 100644
index 00000000..933c8329
--- /dev/null
+++ b/include/openssl/pkcs12err.h
@@ -0,0 +1,45 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PKCS12ERR_H
+# define OPENSSL_PKCS12ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * PKCS12 reason codes.
+ */
+# define PKCS12_R_CANT_PACK_STRUCTURE 100
+# define PKCS12_R_CONTENT_TYPE_NOT_DATA 121
+# define PKCS12_R_DECODE_ERROR 101
+# define PKCS12_R_ENCODE_ERROR 102
+# define PKCS12_R_ENCRYPT_ERROR 103
+# define PKCS12_R_ERROR_SETTING_ENCRYPTED_DATA_TYPE 120
+# define PKCS12_R_INVALID_NULL_ARGUMENT 104
+# define PKCS12_R_INVALID_NULL_PKCS12_POINTER 105
+# define PKCS12_R_INVALID_TYPE 112
+# define PKCS12_R_IV_GEN_ERROR 106
+# define PKCS12_R_KEY_GEN_ERROR 107
+# define PKCS12_R_MAC_ABSENT 108
+# define PKCS12_R_MAC_GENERATION_ERROR 109
+# define PKCS12_R_MAC_SETUP_ERROR 110
+# define PKCS12_R_MAC_STRING_SET_ERROR 111
+# define PKCS12_R_MAC_VERIFY_FAILURE 113
+# define PKCS12_R_PARSE_ERROR 114
+# define PKCS12_R_PKCS12_CIPHERFINAL_ERROR 116
+# define PKCS12_R_UNKNOWN_DIGEST_ALGORITHM 118
+# define PKCS12_R_UNSUPPORTED_PKCS12_MODE 119
+
+#endif
diff --git a/include/openssl/pkcs7.h b/include/openssl/pkcs7.h
new file mode 100644
index 00000000..097d2dbb
--- /dev/null
+++ b/include/openssl/pkcs7.h
@@ -0,0 +1,427 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\pkcs7.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_PKCS7_H
+# define OPENSSL_PKCS7_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_PKCS7_H
+# endif
+
+# include <openssl/asn1.h>
+# include <openssl/bio.h>
+# include <openssl/e_os2.h>
+
+# include <openssl/symhacks.h>
+# include <openssl/types.h>
+# include <openssl/pkcs7err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*-
+Encryption_ID DES-CBC
+Digest_ID MD5
+Digest_Encryption_ID rsaEncryption
+Key_Encryption_ID rsaEncryption
+*/
+
+typedef struct PKCS7_CTX_st {
+ OSSL_LIB_CTX *libctx;
+ char *propq;
+} PKCS7_CTX;
+
+typedef struct pkcs7_issuer_and_serial_st {
+ X509_NAME *issuer;
+ ASN1_INTEGER *serial;
+} PKCS7_ISSUER_AND_SERIAL;
+
+typedef struct pkcs7_signer_info_st {
+ ASN1_INTEGER *version; /* version 1 */
+ PKCS7_ISSUER_AND_SERIAL *issuer_and_serial;
+ X509_ALGOR *digest_alg;
+ STACK_OF(X509_ATTRIBUTE) *auth_attr; /* [ 0 ] */
+ X509_ALGOR *digest_enc_alg;
+ ASN1_OCTET_STRING *enc_digest;
+ STACK_OF(X509_ATTRIBUTE) *unauth_attr; /* [ 1 ] */
+ /* The private key to sign with */
+ EVP_PKEY *pkey;
+ const PKCS7_CTX *ctx;
+} PKCS7_SIGNER_INFO;
+SKM_DEFINE_STACK_OF_INTERNAL(PKCS7_SIGNER_INFO, PKCS7_SIGNER_INFO, PKCS7_SIGNER_INFO)
+#define sk_PKCS7_SIGNER_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_PKCS7_SIGNER_INFO_sk_type(sk))
+#define sk_PKCS7_SIGNER_INFO_value(sk, idx) ((PKCS7_SIGNER_INFO *)OPENSSL_sk_value(ossl_check_const_PKCS7_SIGNER_INFO_sk_type(sk), (idx)))
+#define sk_PKCS7_SIGNER_INFO_new(cmp) ((STACK_OF(PKCS7_SIGNER_INFO) *)OPENSSL_sk_new(ossl_check_PKCS7_SIGNER_INFO_compfunc_type(cmp)))
+#define sk_PKCS7_SIGNER_INFO_new_null() ((STACK_OF(PKCS7_SIGNER_INFO) *)OPENSSL_sk_new_null())
+#define sk_PKCS7_SIGNER_INFO_new_reserve(cmp, n) ((STACK_OF(PKCS7_SIGNER_INFO) *)OPENSSL_sk_new_reserve(ossl_check_PKCS7_SIGNER_INFO_compfunc_type(cmp), (n)))
+#define sk_PKCS7_SIGNER_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), (n))
+#define sk_PKCS7_SIGNER_INFO_free(sk) OPENSSL_sk_free(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk))
+#define sk_PKCS7_SIGNER_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk))
+#define sk_PKCS7_SIGNER_INFO_delete(sk, i) ((PKCS7_SIGNER_INFO *)OPENSSL_sk_delete(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), (i)))
+#define sk_PKCS7_SIGNER_INFO_delete_ptr(sk, ptr) ((PKCS7_SIGNER_INFO *)OPENSSL_sk_delete_ptr(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_type(ptr)))
+#define sk_PKCS7_SIGNER_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_type(ptr))
+#define sk_PKCS7_SIGNER_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_type(ptr))
+#define sk_PKCS7_SIGNER_INFO_pop(sk) ((PKCS7_SIGNER_INFO *)OPENSSL_sk_pop(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk)))
+#define sk_PKCS7_SIGNER_INFO_shift(sk) ((PKCS7_SIGNER_INFO *)OPENSSL_sk_shift(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk)))
+#define sk_PKCS7_SIGNER_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk),ossl_check_PKCS7_SIGNER_INFO_freefunc_type(freefunc))
+#define sk_PKCS7_SIGNER_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_type(ptr), (idx))
+#define sk_PKCS7_SIGNER_INFO_set(sk, idx, ptr) ((PKCS7_SIGNER_INFO *)OPENSSL_sk_set(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), (idx), ossl_check_PKCS7_SIGNER_INFO_type(ptr)))
+#define sk_PKCS7_SIGNER_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_type(ptr))
+#define sk_PKCS7_SIGNER_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_type(ptr))
+#define sk_PKCS7_SIGNER_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_type(ptr), pnum)
+#define sk_PKCS7_SIGNER_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk))
+#define sk_PKCS7_SIGNER_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_PKCS7_SIGNER_INFO_sk_type(sk))
+#define sk_PKCS7_SIGNER_INFO_dup(sk) ((STACK_OF(PKCS7_SIGNER_INFO) *)OPENSSL_sk_dup(ossl_check_const_PKCS7_SIGNER_INFO_sk_type(sk)))
+#define sk_PKCS7_SIGNER_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(PKCS7_SIGNER_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_copyfunc_type(copyfunc), ossl_check_PKCS7_SIGNER_INFO_freefunc_type(freefunc)))
+#define sk_PKCS7_SIGNER_INFO_set_cmp_func(sk, cmp) ((sk_PKCS7_SIGNER_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_PKCS7_SIGNER_INFO_sk_type(sk), ossl_check_PKCS7_SIGNER_INFO_compfunc_type(cmp)))
+
+
+typedef struct pkcs7_recip_info_st {
+ ASN1_INTEGER *version; /* version 0 */
+ PKCS7_ISSUER_AND_SERIAL *issuer_and_serial;
+ X509_ALGOR *key_enc_algor;
+ ASN1_OCTET_STRING *enc_key;
+ X509 *cert; /* get the pub-key from this */
+ const PKCS7_CTX *ctx;
+} PKCS7_RECIP_INFO;
+SKM_DEFINE_STACK_OF_INTERNAL(PKCS7_RECIP_INFO, PKCS7_RECIP_INFO, PKCS7_RECIP_INFO)
+#define sk_PKCS7_RECIP_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_PKCS7_RECIP_INFO_sk_type(sk))
+#define sk_PKCS7_RECIP_INFO_value(sk, idx) ((PKCS7_RECIP_INFO *)OPENSSL_sk_value(ossl_check_const_PKCS7_RECIP_INFO_sk_type(sk), (idx)))
+#define sk_PKCS7_RECIP_INFO_new(cmp) ((STACK_OF(PKCS7_RECIP_INFO) *)OPENSSL_sk_new(ossl_check_PKCS7_RECIP_INFO_compfunc_type(cmp)))
+#define sk_PKCS7_RECIP_INFO_new_null() ((STACK_OF(PKCS7_RECIP_INFO) *)OPENSSL_sk_new_null())
+#define sk_PKCS7_RECIP_INFO_new_reserve(cmp, n) ((STACK_OF(PKCS7_RECIP_INFO) *)OPENSSL_sk_new_reserve(ossl_check_PKCS7_RECIP_INFO_compfunc_type(cmp), (n)))
+#define sk_PKCS7_RECIP_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), (n))
+#define sk_PKCS7_RECIP_INFO_free(sk) OPENSSL_sk_free(ossl_check_PKCS7_RECIP_INFO_sk_type(sk))
+#define sk_PKCS7_RECIP_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_PKCS7_RECIP_INFO_sk_type(sk))
+#define sk_PKCS7_RECIP_INFO_delete(sk, i) ((PKCS7_RECIP_INFO *)OPENSSL_sk_delete(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), (i)))
+#define sk_PKCS7_RECIP_INFO_delete_ptr(sk, ptr) ((PKCS7_RECIP_INFO *)OPENSSL_sk_delete_ptr(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_type(ptr)))
+#define sk_PKCS7_RECIP_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_type(ptr))
+#define sk_PKCS7_RECIP_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_type(ptr))
+#define sk_PKCS7_RECIP_INFO_pop(sk) ((PKCS7_RECIP_INFO *)OPENSSL_sk_pop(ossl_check_PKCS7_RECIP_INFO_sk_type(sk)))
+#define sk_PKCS7_RECIP_INFO_shift(sk) ((PKCS7_RECIP_INFO *)OPENSSL_sk_shift(ossl_check_PKCS7_RECIP_INFO_sk_type(sk)))
+#define sk_PKCS7_RECIP_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_PKCS7_RECIP_INFO_sk_type(sk),ossl_check_PKCS7_RECIP_INFO_freefunc_type(freefunc))
+#define sk_PKCS7_RECIP_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_type(ptr), (idx))
+#define sk_PKCS7_RECIP_INFO_set(sk, idx, ptr) ((PKCS7_RECIP_INFO *)OPENSSL_sk_set(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), (idx), ossl_check_PKCS7_RECIP_INFO_type(ptr)))
+#define sk_PKCS7_RECIP_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_type(ptr))
+#define sk_PKCS7_RECIP_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_type(ptr))
+#define sk_PKCS7_RECIP_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_type(ptr), pnum)
+#define sk_PKCS7_RECIP_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_PKCS7_RECIP_INFO_sk_type(sk))
+#define sk_PKCS7_RECIP_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_PKCS7_RECIP_INFO_sk_type(sk))
+#define sk_PKCS7_RECIP_INFO_dup(sk) ((STACK_OF(PKCS7_RECIP_INFO) *)OPENSSL_sk_dup(ossl_check_const_PKCS7_RECIP_INFO_sk_type(sk)))
+#define sk_PKCS7_RECIP_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(PKCS7_RECIP_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_copyfunc_type(copyfunc), ossl_check_PKCS7_RECIP_INFO_freefunc_type(freefunc)))
+#define sk_PKCS7_RECIP_INFO_set_cmp_func(sk, cmp) ((sk_PKCS7_RECIP_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_PKCS7_RECIP_INFO_sk_type(sk), ossl_check_PKCS7_RECIP_INFO_compfunc_type(cmp)))
+
+
+
+typedef struct pkcs7_signed_st {
+ ASN1_INTEGER *version; /* version 1 */
+ STACK_OF(X509_ALGOR) *md_algs; /* md used */
+ STACK_OF(X509) *cert; /* [ 0 ] */
+ STACK_OF(X509_CRL) *crl; /* [ 1 ] */
+ STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
+ struct pkcs7_st *contents;
+} PKCS7_SIGNED;
+/*
+ * The above structure is very very similar to PKCS7_SIGN_ENVELOPE. How about
+ * merging the two
+ */
+
+typedef struct pkcs7_enc_content_st {
+ ASN1_OBJECT *content_type;
+ X509_ALGOR *algorithm;
+ ASN1_OCTET_STRING *enc_data; /* [ 0 ] */
+ const EVP_CIPHER *cipher;
+ const PKCS7_CTX *ctx;
+} PKCS7_ENC_CONTENT;
+
+typedef struct pkcs7_enveloped_st {
+ ASN1_INTEGER *version; /* version 0 */
+ STACK_OF(PKCS7_RECIP_INFO) *recipientinfo;
+ PKCS7_ENC_CONTENT *enc_data;
+} PKCS7_ENVELOPE;
+
+typedef struct pkcs7_signedandenveloped_st {
+ ASN1_INTEGER *version; /* version 1 */
+ STACK_OF(X509_ALGOR) *md_algs; /* md used */
+ STACK_OF(X509) *cert; /* [ 0 ] */
+ STACK_OF(X509_CRL) *crl; /* [ 1 ] */
+ STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
+ PKCS7_ENC_CONTENT *enc_data;
+ STACK_OF(PKCS7_RECIP_INFO) *recipientinfo;
+} PKCS7_SIGN_ENVELOPE;
+
+typedef struct pkcs7_digest_st {
+ ASN1_INTEGER *version; /* version 0 */
+ X509_ALGOR *md; /* md used */
+ struct pkcs7_st *contents;
+ ASN1_OCTET_STRING *digest;
+} PKCS7_DIGEST;
+
+typedef struct pkcs7_encrypted_st {
+ ASN1_INTEGER *version; /* version 0 */
+ PKCS7_ENC_CONTENT *enc_data;
+} PKCS7_ENCRYPT;
+
+typedef struct pkcs7_st {
+ /*
+ * The following is non NULL if it contains ASN1 encoding of this
+ * structure
+ */
+ unsigned char *asn1;
+ long length;
+# define PKCS7_S_HEADER 0
+# define PKCS7_S_BODY 1
+# define PKCS7_S_TAIL 2
+ int state; /* used during processing */
+ int detached;
+ ASN1_OBJECT *type;
+ /* content as defined by the type */
+ /*
+ * all encryption/message digests are applied to the 'contents', leaving
+ * out the 'type' field.
+ */
+ union {
+ char *ptr;
+ /* NID_pkcs7_data */
+ ASN1_OCTET_STRING *data;
+ /* NID_pkcs7_signed */
+ PKCS7_SIGNED *sign;
+ /* NID_pkcs7_enveloped */
+ PKCS7_ENVELOPE *enveloped;
+ /* NID_pkcs7_signedAndEnveloped */
+ PKCS7_SIGN_ENVELOPE *signed_and_enveloped;
+ /* NID_pkcs7_digest */
+ PKCS7_DIGEST *digest;
+ /* NID_pkcs7_encrypted */
+ PKCS7_ENCRYPT *encrypted;
+ /* Anything else */
+ ASN1_TYPE *other;
+ } d;
+ PKCS7_CTX ctx;
+} PKCS7;
+SKM_DEFINE_STACK_OF_INTERNAL(PKCS7, PKCS7, PKCS7)
+#define sk_PKCS7_num(sk) OPENSSL_sk_num(ossl_check_const_PKCS7_sk_type(sk))
+#define sk_PKCS7_value(sk, idx) ((PKCS7 *)OPENSSL_sk_value(ossl_check_const_PKCS7_sk_type(sk), (idx)))
+#define sk_PKCS7_new(cmp) ((STACK_OF(PKCS7) *)OPENSSL_sk_new(ossl_check_PKCS7_compfunc_type(cmp)))
+#define sk_PKCS7_new_null() ((STACK_OF(PKCS7) *)OPENSSL_sk_new_null())
+#define sk_PKCS7_new_reserve(cmp, n) ((STACK_OF(PKCS7) *)OPENSSL_sk_new_reserve(ossl_check_PKCS7_compfunc_type(cmp), (n)))
+#define sk_PKCS7_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_PKCS7_sk_type(sk), (n))
+#define sk_PKCS7_free(sk) OPENSSL_sk_free(ossl_check_PKCS7_sk_type(sk))
+#define sk_PKCS7_zero(sk) OPENSSL_sk_zero(ossl_check_PKCS7_sk_type(sk))
+#define sk_PKCS7_delete(sk, i) ((PKCS7 *)OPENSSL_sk_delete(ossl_check_PKCS7_sk_type(sk), (i)))
+#define sk_PKCS7_delete_ptr(sk, ptr) ((PKCS7 *)OPENSSL_sk_delete_ptr(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_type(ptr)))
+#define sk_PKCS7_push(sk, ptr) OPENSSL_sk_push(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_type(ptr))
+#define sk_PKCS7_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_type(ptr))
+#define sk_PKCS7_pop(sk) ((PKCS7 *)OPENSSL_sk_pop(ossl_check_PKCS7_sk_type(sk)))
+#define sk_PKCS7_shift(sk) ((PKCS7 *)OPENSSL_sk_shift(ossl_check_PKCS7_sk_type(sk)))
+#define sk_PKCS7_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_PKCS7_sk_type(sk),ossl_check_PKCS7_freefunc_type(freefunc))
+#define sk_PKCS7_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_type(ptr), (idx))
+#define sk_PKCS7_set(sk, idx, ptr) ((PKCS7 *)OPENSSL_sk_set(ossl_check_PKCS7_sk_type(sk), (idx), ossl_check_PKCS7_type(ptr)))
+#define sk_PKCS7_find(sk, ptr) OPENSSL_sk_find(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_type(ptr))
+#define sk_PKCS7_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_type(ptr))
+#define sk_PKCS7_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_type(ptr), pnum)
+#define sk_PKCS7_sort(sk) OPENSSL_sk_sort(ossl_check_PKCS7_sk_type(sk))
+#define sk_PKCS7_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_PKCS7_sk_type(sk))
+#define sk_PKCS7_dup(sk) ((STACK_OF(PKCS7) *)OPENSSL_sk_dup(ossl_check_const_PKCS7_sk_type(sk)))
+#define sk_PKCS7_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(PKCS7) *)OPENSSL_sk_deep_copy(ossl_check_const_PKCS7_sk_type(sk), ossl_check_PKCS7_copyfunc_type(copyfunc), ossl_check_PKCS7_freefunc_type(freefunc)))
+#define sk_PKCS7_set_cmp_func(sk, cmp) ((sk_PKCS7_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_PKCS7_sk_type(sk), ossl_check_PKCS7_compfunc_type(cmp)))
+
+
+
+# define PKCS7_OP_SET_DETACHED_SIGNATURE 1
+# define PKCS7_OP_GET_DETACHED_SIGNATURE 2
+
+# define PKCS7_get_signed_attributes(si) ((si)->auth_attr)
+# define PKCS7_get_attributes(si) ((si)->unauth_attr)
+
+# define PKCS7_type_is_signed(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_signed)
+# define PKCS7_type_is_encrypted(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_encrypted)
+# define PKCS7_type_is_enveloped(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_enveloped)
+# define PKCS7_type_is_signedAndEnveloped(a) \
+ (OBJ_obj2nid((a)->type) == NID_pkcs7_signedAndEnveloped)
+# define PKCS7_type_is_data(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_data)
+# define PKCS7_type_is_digest(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_digest)
+
+# define PKCS7_set_detached(p,v) \
+ PKCS7_ctrl(p,PKCS7_OP_SET_DETACHED_SIGNATURE,v,NULL)
+# define PKCS7_get_detached(p) \
+ PKCS7_ctrl(p,PKCS7_OP_GET_DETACHED_SIGNATURE,0,NULL)
+
+# define PKCS7_is_detached(p7) (PKCS7_type_is_signed(p7) && PKCS7_get_detached(p7))
+
+/* S/MIME related flags */
+
+# define PKCS7_TEXT 0x1
+# define PKCS7_NOCERTS 0x2
+# define PKCS7_NOSIGS 0x4
+# define PKCS7_NOCHAIN 0x8
+# define PKCS7_NOINTERN 0x10
+# define PKCS7_NOVERIFY 0x20
+# define PKCS7_DETACHED 0x40
+# define PKCS7_BINARY 0x80
+# define PKCS7_NOATTR 0x100
+# define PKCS7_NOSMIMECAP 0x200
+# define PKCS7_NOOLDMIMETYPE 0x400
+# define PKCS7_CRLFEOL 0x800
+# define PKCS7_STREAM 0x1000
+# define PKCS7_NOCRL 0x2000
+# define PKCS7_PARTIAL 0x4000
+# define PKCS7_REUSE_DIGEST 0x8000
+# define PKCS7_NO_DUAL_CONTENT 0x10000
+
+/* Flags: for compatibility with older code */
+
+# define SMIME_TEXT PKCS7_TEXT
+# define SMIME_NOCERTS PKCS7_NOCERTS
+# define SMIME_NOSIGS PKCS7_NOSIGS
+# define SMIME_NOCHAIN PKCS7_NOCHAIN
+# define SMIME_NOINTERN PKCS7_NOINTERN
+# define SMIME_NOVERIFY PKCS7_NOVERIFY
+# define SMIME_DETACHED PKCS7_DETACHED
+# define SMIME_BINARY PKCS7_BINARY
+# define SMIME_NOATTR PKCS7_NOATTR
+
+/* CRLF ASCII canonicalisation */
+# define SMIME_ASCIICRLF 0x80000
+
+DECLARE_ASN1_FUNCTIONS(PKCS7_ISSUER_AND_SERIAL)
+
+int PKCS7_ISSUER_AND_SERIAL_digest(PKCS7_ISSUER_AND_SERIAL *data,
+ const EVP_MD *type, unsigned char *md,
+ unsigned int *len);
+# ifndef OPENSSL_NO_STDIO
+PKCS7 *d2i_PKCS7_fp(FILE *fp, PKCS7 **p7);
+int i2d_PKCS7_fp(FILE *fp, const PKCS7 *p7);
+# endif
+DECLARE_ASN1_DUP_FUNCTION(PKCS7)
+PKCS7 *d2i_PKCS7_bio(BIO *bp, PKCS7 **p7);
+int i2d_PKCS7_bio(BIO *bp, const PKCS7 *p7);
+int i2d_PKCS7_bio_stream(BIO *out, PKCS7 *p7, BIO *in, int flags);
+int PEM_write_bio_PKCS7_stream(BIO *out, PKCS7 *p7, BIO *in, int flags);
+
+DECLARE_ASN1_FUNCTIONS(PKCS7_SIGNER_INFO)
+DECLARE_ASN1_FUNCTIONS(PKCS7_RECIP_INFO)
+DECLARE_ASN1_FUNCTIONS(PKCS7_SIGNED)
+DECLARE_ASN1_FUNCTIONS(PKCS7_ENC_CONTENT)
+DECLARE_ASN1_FUNCTIONS(PKCS7_ENVELOPE)
+DECLARE_ASN1_FUNCTIONS(PKCS7_SIGN_ENVELOPE)
+DECLARE_ASN1_FUNCTIONS(PKCS7_DIGEST)
+DECLARE_ASN1_FUNCTIONS(PKCS7_ENCRYPT)
+DECLARE_ASN1_FUNCTIONS(PKCS7)
+PKCS7 *PKCS7_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+DECLARE_ASN1_ITEM(PKCS7_ATTR_SIGN)
+DECLARE_ASN1_ITEM(PKCS7_ATTR_VERIFY)
+
+DECLARE_ASN1_NDEF_FUNCTION(PKCS7)
+DECLARE_ASN1_PRINT_FUNCTION(PKCS7)
+
+long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg);
+
+int PKCS7_type_is_other(PKCS7 *p7);
+int PKCS7_set_type(PKCS7 *p7, int type);
+int PKCS7_set0_type_other(PKCS7 *p7, int type, ASN1_TYPE *other);
+int PKCS7_set_content(PKCS7 *p7, PKCS7 *p7_data);
+int PKCS7_SIGNER_INFO_set(PKCS7_SIGNER_INFO *p7i, X509 *x509, EVP_PKEY *pkey,
+ const EVP_MD *dgst);
+int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si);
+int PKCS7_add_signer(PKCS7 *p7, PKCS7_SIGNER_INFO *p7i);
+int PKCS7_add_certificate(PKCS7 *p7, X509 *x509);
+int PKCS7_add_crl(PKCS7 *p7, X509_CRL *x509);
+int PKCS7_content_new(PKCS7 *p7, int nid);
+int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx,
+ BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si);
+int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
+ X509 *x509);
+
+BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio);
+int PKCS7_dataFinal(PKCS7 *p7, BIO *bio);
+BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert);
+
+PKCS7_SIGNER_INFO *PKCS7_add_signature(PKCS7 *p7, X509 *x509,
+ EVP_PKEY *pkey, const EVP_MD *dgst);
+X509 *PKCS7_cert_from_signer_info(PKCS7 *p7, PKCS7_SIGNER_INFO *si);
+int PKCS7_set_digest(PKCS7 *p7, const EVP_MD *md);
+STACK_OF(PKCS7_SIGNER_INFO) *PKCS7_get_signer_info(PKCS7 *p7);
+
+PKCS7_RECIP_INFO *PKCS7_add_recipient(PKCS7 *p7, X509 *x509);
+void PKCS7_SIGNER_INFO_get0_algs(PKCS7_SIGNER_INFO *si, EVP_PKEY **pk,
+ X509_ALGOR **pdig, X509_ALGOR **psig);
+void PKCS7_RECIP_INFO_get0_alg(PKCS7_RECIP_INFO *ri, X509_ALGOR **penc);
+int PKCS7_add_recipient_info(PKCS7 *p7, PKCS7_RECIP_INFO *ri);
+int PKCS7_RECIP_INFO_set(PKCS7_RECIP_INFO *p7i, X509 *x509);
+int PKCS7_set_cipher(PKCS7 *p7, const EVP_CIPHER *cipher);
+int PKCS7_stream(unsigned char ***boundary, PKCS7 *p7);
+
+PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx);
+ASN1_OCTET_STRING *PKCS7_get_octet_string(PKCS7 *p7);
+ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk);
+int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int type,
+ void *data);
+int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
+ void *value);
+ASN1_TYPE *PKCS7_get_attribute(const PKCS7_SIGNER_INFO *si, int nid);
+ASN1_TYPE *PKCS7_get_signed_attribute(const PKCS7_SIGNER_INFO *si, int nid);
+int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si,
+ STACK_OF(X509_ATTRIBUTE) *sk);
+int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si,
+ STACK_OF(X509_ATTRIBUTE) *sk);
+
+PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
+ BIO *data, int flags);
+PKCS7 *PKCS7_sign_ex(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
+ BIO *data, int flags, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+PKCS7_SIGNER_INFO *PKCS7_sign_add_signer(PKCS7 *p7,
+ X509 *signcert, EVP_PKEY *pkey,
+ const EVP_MD *md, int flags);
+
+int PKCS7_final(PKCS7 *p7, BIO *data, int flags);
+int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store,
+ BIO *indata, BIO *out, int flags);
+STACK_OF(X509) *PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs,
+ int flags);
+PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher,
+ int flags);
+PKCS7 *PKCS7_encrypt_ex(STACK_OF(X509) *certs, BIO *in,
+ const EVP_CIPHER *cipher, int flags,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data,
+ int flags);
+
+int PKCS7_add_attrib_smimecap(PKCS7_SIGNER_INFO *si,
+ STACK_OF(X509_ALGOR) *cap);
+STACK_OF(X509_ALGOR) *PKCS7_get_smimecap(PKCS7_SIGNER_INFO *si);
+int PKCS7_simple_smimecap(STACK_OF(X509_ALGOR) *sk, int nid, int arg);
+
+int PKCS7_add_attrib_content_type(PKCS7_SIGNER_INFO *si, ASN1_OBJECT *coid);
+int PKCS7_add0_attrib_signing_time(PKCS7_SIGNER_INFO *si, ASN1_TIME *t);
+int PKCS7_add1_attrib_digest(PKCS7_SIGNER_INFO *si,
+ const unsigned char *md, int mdlen);
+
+int SMIME_write_PKCS7(BIO *bio, PKCS7 *p7, BIO *data, int flags);
+PKCS7 *SMIME_read_PKCS7_ex(BIO *bio, BIO **bcont, PKCS7 **p7);
+PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont);
+
+BIO *BIO_new_PKCS7(BIO *out, PKCS7 *p7);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/pkcs7.h.in b/include/openssl/pkcs7.h.in
new file mode 100644
index 00000000..f5c55a3f
--- /dev/null
+++ b/include/openssl/pkcs7.h.in
@@ -0,0 +1,356 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_PKCS7_H
+# define OPENSSL_PKCS7_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_PKCS7_H
+# endif
+
+# include <openssl/asn1.h>
+# include <openssl/bio.h>
+# include <openssl/e_os2.h>
+
+# include <openssl/symhacks.h>
+# include <openssl/types.h>
+# include <openssl/pkcs7err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+/*-
+Encryption_ID DES-CBC
+Digest_ID MD5
+Digest_Encryption_ID rsaEncryption
+Key_Encryption_ID rsaEncryption
+*/
+
+typedef struct PKCS7_CTX_st {
+ OSSL_LIB_CTX *libctx;
+ char *propq;
+} PKCS7_CTX;
+
+typedef struct pkcs7_issuer_and_serial_st {
+ X509_NAME *issuer;
+ ASN1_INTEGER *serial;
+} PKCS7_ISSUER_AND_SERIAL;
+
+typedef struct pkcs7_signer_info_st {
+ ASN1_INTEGER *version; /* version 1 */
+ PKCS7_ISSUER_AND_SERIAL *issuer_and_serial;
+ X509_ALGOR *digest_alg;
+ STACK_OF(X509_ATTRIBUTE) *auth_attr; /* [ 0 ] */
+ X509_ALGOR *digest_enc_alg;
+ ASN1_OCTET_STRING *enc_digest;
+ STACK_OF(X509_ATTRIBUTE) *unauth_attr; /* [ 1 ] */
+ /* The private key to sign with */
+ EVP_PKEY *pkey;
+ const PKCS7_CTX *ctx;
+} PKCS7_SIGNER_INFO;
+{-
+ generate_stack_macros("PKCS7_SIGNER_INFO");
+-}
+
+typedef struct pkcs7_recip_info_st {
+ ASN1_INTEGER *version; /* version 0 */
+ PKCS7_ISSUER_AND_SERIAL *issuer_and_serial;
+ X509_ALGOR *key_enc_algor;
+ ASN1_OCTET_STRING *enc_key;
+ X509 *cert; /* get the pub-key from this */
+ const PKCS7_CTX *ctx;
+} PKCS7_RECIP_INFO;
+{-
+ generate_stack_macros("PKCS7_RECIP_INFO");
+-}
+
+
+typedef struct pkcs7_signed_st {
+ ASN1_INTEGER *version; /* version 1 */
+ STACK_OF(X509_ALGOR) *md_algs; /* md used */
+ STACK_OF(X509) *cert; /* [ 0 ] */
+ STACK_OF(X509_CRL) *crl; /* [ 1 ] */
+ STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
+ struct pkcs7_st *contents;
+} PKCS7_SIGNED;
+/*
+ * The above structure is very very similar to PKCS7_SIGN_ENVELOPE. How about
+ * merging the two
+ */
+
+typedef struct pkcs7_enc_content_st {
+ ASN1_OBJECT *content_type;
+ X509_ALGOR *algorithm;
+ ASN1_OCTET_STRING *enc_data; /* [ 0 ] */
+ const EVP_CIPHER *cipher;
+ const PKCS7_CTX *ctx;
+} PKCS7_ENC_CONTENT;
+
+typedef struct pkcs7_enveloped_st {
+ ASN1_INTEGER *version; /* version 0 */
+ STACK_OF(PKCS7_RECIP_INFO) *recipientinfo;
+ PKCS7_ENC_CONTENT *enc_data;
+} PKCS7_ENVELOPE;
+
+typedef struct pkcs7_signedandenveloped_st {
+ ASN1_INTEGER *version; /* version 1 */
+ STACK_OF(X509_ALGOR) *md_algs; /* md used */
+ STACK_OF(X509) *cert; /* [ 0 ] */
+ STACK_OF(X509_CRL) *crl; /* [ 1 ] */
+ STACK_OF(PKCS7_SIGNER_INFO) *signer_info;
+ PKCS7_ENC_CONTENT *enc_data;
+ STACK_OF(PKCS7_RECIP_INFO) *recipientinfo;
+} PKCS7_SIGN_ENVELOPE;
+
+typedef struct pkcs7_digest_st {
+ ASN1_INTEGER *version; /* version 0 */
+ X509_ALGOR *md; /* md used */
+ struct pkcs7_st *contents;
+ ASN1_OCTET_STRING *digest;
+} PKCS7_DIGEST;
+
+typedef struct pkcs7_encrypted_st {
+ ASN1_INTEGER *version; /* version 0 */
+ PKCS7_ENC_CONTENT *enc_data;
+} PKCS7_ENCRYPT;
+
+typedef struct pkcs7_st {
+ /*
+ * The following is non NULL if it contains ASN1 encoding of this
+ * structure
+ */
+ unsigned char *asn1;
+ long length;
+# define PKCS7_S_HEADER 0
+# define PKCS7_S_BODY 1
+# define PKCS7_S_TAIL 2
+ int state; /* used during processing */
+ int detached;
+ ASN1_OBJECT *type;
+ /* content as defined by the type */
+ /*
+ * all encryption/message digests are applied to the 'contents', leaving
+ * out the 'type' field.
+ */
+ union {
+ char *ptr;
+ /* NID_pkcs7_data */
+ ASN1_OCTET_STRING *data;
+ /* NID_pkcs7_signed */
+ PKCS7_SIGNED *sign;
+ /* NID_pkcs7_enveloped */
+ PKCS7_ENVELOPE *enveloped;
+ /* NID_pkcs7_signedAndEnveloped */
+ PKCS7_SIGN_ENVELOPE *signed_and_enveloped;
+ /* NID_pkcs7_digest */
+ PKCS7_DIGEST *digest;
+ /* NID_pkcs7_encrypted */
+ PKCS7_ENCRYPT *encrypted;
+ /* Anything else */
+ ASN1_TYPE *other;
+ } d;
+ PKCS7_CTX ctx;
+} PKCS7;
+{-
+ generate_stack_macros("PKCS7");
+-}
+
+
+# define PKCS7_OP_SET_DETACHED_SIGNATURE 1
+# define PKCS7_OP_GET_DETACHED_SIGNATURE 2
+
+# define PKCS7_get_signed_attributes(si) ((si)->auth_attr)
+# define PKCS7_get_attributes(si) ((si)->unauth_attr)
+
+# define PKCS7_type_is_signed(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_signed)
+# define PKCS7_type_is_encrypted(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_encrypted)
+# define PKCS7_type_is_enveloped(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_enveloped)
+# define PKCS7_type_is_signedAndEnveloped(a) \
+ (OBJ_obj2nid((a)->type) == NID_pkcs7_signedAndEnveloped)
+# define PKCS7_type_is_data(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_data)
+# define PKCS7_type_is_digest(a) (OBJ_obj2nid((a)->type) == NID_pkcs7_digest)
+
+# define PKCS7_set_detached(p,v) \
+ PKCS7_ctrl(p,PKCS7_OP_SET_DETACHED_SIGNATURE,v,NULL)
+# define PKCS7_get_detached(p) \
+ PKCS7_ctrl(p,PKCS7_OP_GET_DETACHED_SIGNATURE,0,NULL)
+
+# define PKCS7_is_detached(p7) (PKCS7_type_is_signed(p7) && PKCS7_get_detached(p7))
+
+/* S/MIME related flags */
+
+# define PKCS7_TEXT 0x1
+# define PKCS7_NOCERTS 0x2
+# define PKCS7_NOSIGS 0x4
+# define PKCS7_NOCHAIN 0x8
+# define PKCS7_NOINTERN 0x10
+# define PKCS7_NOVERIFY 0x20
+# define PKCS7_DETACHED 0x40
+# define PKCS7_BINARY 0x80
+# define PKCS7_NOATTR 0x100
+# define PKCS7_NOSMIMECAP 0x200
+# define PKCS7_NOOLDMIMETYPE 0x400
+# define PKCS7_CRLFEOL 0x800
+# define PKCS7_STREAM 0x1000
+# define PKCS7_NOCRL 0x2000
+# define PKCS7_PARTIAL 0x4000
+# define PKCS7_REUSE_DIGEST 0x8000
+# define PKCS7_NO_DUAL_CONTENT 0x10000
+
+/* Flags: for compatibility with older code */
+
+# define SMIME_TEXT PKCS7_TEXT
+# define SMIME_NOCERTS PKCS7_NOCERTS
+# define SMIME_NOSIGS PKCS7_NOSIGS
+# define SMIME_NOCHAIN PKCS7_NOCHAIN
+# define SMIME_NOINTERN PKCS7_NOINTERN
+# define SMIME_NOVERIFY PKCS7_NOVERIFY
+# define SMIME_DETACHED PKCS7_DETACHED
+# define SMIME_BINARY PKCS7_BINARY
+# define SMIME_NOATTR PKCS7_NOATTR
+
+/* CRLF ASCII canonicalisation */
+# define SMIME_ASCIICRLF 0x80000
+
+DECLARE_ASN1_FUNCTIONS(PKCS7_ISSUER_AND_SERIAL)
+
+int PKCS7_ISSUER_AND_SERIAL_digest(PKCS7_ISSUER_AND_SERIAL *data,
+ const EVP_MD *type, unsigned char *md,
+ unsigned int *len);
+# ifndef OPENSSL_NO_STDIO
+PKCS7 *d2i_PKCS7_fp(FILE *fp, PKCS7 **p7);
+int i2d_PKCS7_fp(FILE *fp, const PKCS7 *p7);
+# endif
+DECLARE_ASN1_DUP_FUNCTION(PKCS7)
+PKCS7 *d2i_PKCS7_bio(BIO *bp, PKCS7 **p7);
+int i2d_PKCS7_bio(BIO *bp, const PKCS7 *p7);
+int i2d_PKCS7_bio_stream(BIO *out, PKCS7 *p7, BIO *in, int flags);
+int PEM_write_bio_PKCS7_stream(BIO *out, PKCS7 *p7, BIO *in, int flags);
+
+DECLARE_ASN1_FUNCTIONS(PKCS7_SIGNER_INFO)
+DECLARE_ASN1_FUNCTIONS(PKCS7_RECIP_INFO)
+DECLARE_ASN1_FUNCTIONS(PKCS7_SIGNED)
+DECLARE_ASN1_FUNCTIONS(PKCS7_ENC_CONTENT)
+DECLARE_ASN1_FUNCTIONS(PKCS7_ENVELOPE)
+DECLARE_ASN1_FUNCTIONS(PKCS7_SIGN_ENVELOPE)
+DECLARE_ASN1_FUNCTIONS(PKCS7_DIGEST)
+DECLARE_ASN1_FUNCTIONS(PKCS7_ENCRYPT)
+DECLARE_ASN1_FUNCTIONS(PKCS7)
+PKCS7 *PKCS7_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+DECLARE_ASN1_ITEM(PKCS7_ATTR_SIGN)
+DECLARE_ASN1_ITEM(PKCS7_ATTR_VERIFY)
+
+DECLARE_ASN1_NDEF_FUNCTION(PKCS7)
+DECLARE_ASN1_PRINT_FUNCTION(PKCS7)
+
+long PKCS7_ctrl(PKCS7 *p7, int cmd, long larg, char *parg);
+
+int PKCS7_type_is_other(PKCS7 *p7);
+int PKCS7_set_type(PKCS7 *p7, int type);
+int PKCS7_set0_type_other(PKCS7 *p7, int type, ASN1_TYPE *other);
+int PKCS7_set_content(PKCS7 *p7, PKCS7 *p7_data);
+int PKCS7_SIGNER_INFO_set(PKCS7_SIGNER_INFO *p7i, X509 *x509, EVP_PKEY *pkey,
+ const EVP_MD *dgst);
+int PKCS7_SIGNER_INFO_sign(PKCS7_SIGNER_INFO *si);
+int PKCS7_add_signer(PKCS7 *p7, PKCS7_SIGNER_INFO *p7i);
+int PKCS7_add_certificate(PKCS7 *p7, X509 *x509);
+int PKCS7_add_crl(PKCS7 *p7, X509_CRL *x509);
+int PKCS7_content_new(PKCS7 *p7, int nid);
+int PKCS7_dataVerify(X509_STORE *cert_store, X509_STORE_CTX *ctx,
+ BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si);
+int PKCS7_signatureVerify(BIO *bio, PKCS7 *p7, PKCS7_SIGNER_INFO *si,
+ X509 *x509);
+
+BIO *PKCS7_dataInit(PKCS7 *p7, BIO *bio);
+int PKCS7_dataFinal(PKCS7 *p7, BIO *bio);
+BIO *PKCS7_dataDecode(PKCS7 *p7, EVP_PKEY *pkey, BIO *in_bio, X509 *pcert);
+
+PKCS7_SIGNER_INFO *PKCS7_add_signature(PKCS7 *p7, X509 *x509,
+ EVP_PKEY *pkey, const EVP_MD *dgst);
+X509 *PKCS7_cert_from_signer_info(PKCS7 *p7, PKCS7_SIGNER_INFO *si);
+int PKCS7_set_digest(PKCS7 *p7, const EVP_MD *md);
+STACK_OF(PKCS7_SIGNER_INFO) *PKCS7_get_signer_info(PKCS7 *p7);
+
+PKCS7_RECIP_INFO *PKCS7_add_recipient(PKCS7 *p7, X509 *x509);
+void PKCS7_SIGNER_INFO_get0_algs(PKCS7_SIGNER_INFO *si, EVP_PKEY **pk,
+ X509_ALGOR **pdig, X509_ALGOR **psig);
+void PKCS7_RECIP_INFO_get0_alg(PKCS7_RECIP_INFO *ri, X509_ALGOR **penc);
+int PKCS7_add_recipient_info(PKCS7 *p7, PKCS7_RECIP_INFO *ri);
+int PKCS7_RECIP_INFO_set(PKCS7_RECIP_INFO *p7i, X509 *x509);
+int PKCS7_set_cipher(PKCS7 *p7, const EVP_CIPHER *cipher);
+int PKCS7_stream(unsigned char ***boundary, PKCS7 *p7);
+
+PKCS7_ISSUER_AND_SERIAL *PKCS7_get_issuer_and_serial(PKCS7 *p7, int idx);
+ASN1_OCTET_STRING *PKCS7_get_octet_string(PKCS7 *p7);
+ASN1_OCTET_STRING *PKCS7_digest_from_attributes(STACK_OF(X509_ATTRIBUTE) *sk);
+int PKCS7_add_signed_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int type,
+ void *data);
+int PKCS7_add_attribute(PKCS7_SIGNER_INFO *p7si, int nid, int atrtype,
+ void *value);
+ASN1_TYPE *PKCS7_get_attribute(const PKCS7_SIGNER_INFO *si, int nid);
+ASN1_TYPE *PKCS7_get_signed_attribute(const PKCS7_SIGNER_INFO *si, int nid);
+int PKCS7_set_signed_attributes(PKCS7_SIGNER_INFO *p7si,
+ STACK_OF(X509_ATTRIBUTE) *sk);
+int PKCS7_set_attributes(PKCS7_SIGNER_INFO *p7si,
+ STACK_OF(X509_ATTRIBUTE) *sk);
+
+PKCS7 *PKCS7_sign(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
+ BIO *data, int flags);
+PKCS7 *PKCS7_sign_ex(X509 *signcert, EVP_PKEY *pkey, STACK_OF(X509) *certs,
+ BIO *data, int flags, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+PKCS7_SIGNER_INFO *PKCS7_sign_add_signer(PKCS7 *p7,
+ X509 *signcert, EVP_PKEY *pkey,
+ const EVP_MD *md, int flags);
+
+int PKCS7_final(PKCS7 *p7, BIO *data, int flags);
+int PKCS7_verify(PKCS7 *p7, STACK_OF(X509) *certs, X509_STORE *store,
+ BIO *indata, BIO *out, int flags);
+STACK_OF(X509) *PKCS7_get0_signers(PKCS7 *p7, STACK_OF(X509) *certs,
+ int flags);
+PKCS7 *PKCS7_encrypt(STACK_OF(X509) *certs, BIO *in, const EVP_CIPHER *cipher,
+ int flags);
+PKCS7 *PKCS7_encrypt_ex(STACK_OF(X509) *certs, BIO *in,
+ const EVP_CIPHER *cipher, int flags,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int PKCS7_decrypt(PKCS7 *p7, EVP_PKEY *pkey, X509 *cert, BIO *data,
+ int flags);
+
+int PKCS7_add_attrib_smimecap(PKCS7_SIGNER_INFO *si,
+ STACK_OF(X509_ALGOR) *cap);
+STACK_OF(X509_ALGOR) *PKCS7_get_smimecap(PKCS7_SIGNER_INFO *si);
+int PKCS7_simple_smimecap(STACK_OF(X509_ALGOR) *sk, int nid, int arg);
+
+int PKCS7_add_attrib_content_type(PKCS7_SIGNER_INFO *si, ASN1_OBJECT *coid);
+int PKCS7_add0_attrib_signing_time(PKCS7_SIGNER_INFO *si, ASN1_TIME *t);
+int PKCS7_add1_attrib_digest(PKCS7_SIGNER_INFO *si,
+ const unsigned char *md, int mdlen);
+
+int SMIME_write_PKCS7(BIO *bio, PKCS7 *p7, BIO *data, int flags);
+PKCS7 *SMIME_read_PKCS7_ex(BIO *bio, BIO **bcont, PKCS7 **p7);
+PKCS7 *SMIME_read_PKCS7(BIO *bio, BIO **bcont);
+
+BIO *BIO_new_PKCS7(BIO *out, PKCS7 *p7);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/pkcs7err.h b/include/openssl/pkcs7err.h
new file mode 100644
index 00000000..ceb1a501
--- /dev/null
+++ b/include/openssl/pkcs7err.h
@@ -0,0 +1,63 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PKCS7ERR_H
+# define OPENSSL_PKCS7ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * PKCS7 reason codes.
+ */
+# define PKCS7_R_CERTIFICATE_VERIFY_ERROR 117
+# define PKCS7_R_CIPHER_HAS_NO_OBJECT_IDENTIFIER 144
+# define PKCS7_R_CIPHER_NOT_INITIALIZED 116
+# define PKCS7_R_CONTENT_AND_DATA_PRESENT 118
+# define PKCS7_R_CTRL_ERROR 152
+# define PKCS7_R_DECRYPT_ERROR 119
+# define PKCS7_R_DIGEST_FAILURE 101
+# define PKCS7_R_ENCRYPTION_CTRL_FAILURE 149
+# define PKCS7_R_ENCRYPTION_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 150
+# define PKCS7_R_ERROR_ADDING_RECIPIENT 120
+# define PKCS7_R_ERROR_SETTING_CIPHER 121
+# define PKCS7_R_INVALID_NULL_POINTER 143
+# define PKCS7_R_INVALID_SIGNED_DATA_TYPE 155
+# define PKCS7_R_NO_CONTENT 122
+# define PKCS7_R_NO_DEFAULT_DIGEST 151
+# define PKCS7_R_NO_MATCHING_DIGEST_TYPE_FOUND 154
+# define PKCS7_R_NO_RECIPIENT_MATCHES_CERTIFICATE 115
+# define PKCS7_R_NO_SIGNATURES_ON_DATA 123
+# define PKCS7_R_NO_SIGNERS 142
+# define PKCS7_R_OPERATION_NOT_SUPPORTED_ON_THIS_TYPE 104
+# define PKCS7_R_PKCS7_ADD_SIGNATURE_ERROR 124
+# define PKCS7_R_PKCS7_ADD_SIGNER_ERROR 153
+# define PKCS7_R_PKCS7_DATASIGN 145
+# define PKCS7_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 127
+# define PKCS7_R_SIGNATURE_FAILURE 105
+# define PKCS7_R_SIGNER_CERTIFICATE_NOT_FOUND 128
+# define PKCS7_R_SIGNING_CTRL_FAILURE 147
+# define PKCS7_R_SIGNING_NOT_SUPPORTED_FOR_THIS_KEY_TYPE 148
+# define PKCS7_R_SMIME_TEXT_ERROR 129
+# define PKCS7_R_UNABLE_TO_FIND_CERTIFICATE 106
+# define PKCS7_R_UNABLE_TO_FIND_MEM_BIO 107
+# define PKCS7_R_UNABLE_TO_FIND_MESSAGE_DIGEST 108
+# define PKCS7_R_UNKNOWN_DIGEST_TYPE 109
+# define PKCS7_R_UNKNOWN_OPERATION 110
+# define PKCS7_R_UNSUPPORTED_CIPHER_TYPE 111
+# define PKCS7_R_UNSUPPORTED_CONTENT_TYPE 112
+# define PKCS7_R_WRONG_CONTENT_TYPE 113
+# define PKCS7_R_WRONG_PKCS7_TYPE 114
+
+#endif
diff --git a/include/openssl/prov_ssl.h b/include/openssl/prov_ssl.h
new file mode 100644
index 00000000..d3e0896c
--- /dev/null
+++ b/include/openssl/prov_ssl.h
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PROV_SSL_H
+# define OPENSSL_PROV_SSL_H
+# pragma once
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* SSL/TLS related defines useful to providers */
+
+# define SSL_MAX_MASTER_KEY_LENGTH 48
+
+# define SSL3_VERSION 0x0300
+# define TLS1_VERSION 0x0301
+# define TLS1_1_VERSION 0x0302
+# define TLS1_2_VERSION 0x0303
+# define TLS1_3_VERSION 0x0304
+# define DTLS1_VERSION 0xFEFF
+# define DTLS1_2_VERSION 0xFEFD
+# define DTLS1_BAD_VER 0x0100
+
+# ifdef __cplusplus
+}
+# endif
+#endif /* OPENSSL_PROV_SSL_H */
diff --git a/include/openssl/proverr.h b/include/openssl/proverr.h
new file mode 100644
index 00000000..ad67a8f8
--- /dev/null
+++ b/include/openssl/proverr.h
@@ -0,0 +1,148 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PROVERR_H
+# define OPENSSL_PROVERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * PROV reason codes.
+ */
+# define PROV_R_ADDITIONAL_INPUT_TOO_LONG 184
+# define PROV_R_ALGORITHM_MISMATCH 173
+# define PROV_R_ALREADY_INSTANTIATED 185
+# define PROV_R_BAD_DECRYPT 100
+# define PROV_R_BAD_ENCODING 141
+# define PROV_R_BAD_LENGTH 142
+# define PROV_R_BAD_TLS_CLIENT_VERSION 161
+# define PROV_R_BN_ERROR 160
+# define PROV_R_CIPHER_OPERATION_FAILED 102
+# define PROV_R_DERIVATION_FUNCTION_INIT_FAILED 205
+# define PROV_R_DIGEST_NOT_ALLOWED 174
+# define PROV_R_ENTROPY_SOURCE_STRENGTH_TOO_WEAK 186
+# define PROV_R_ERROR_INSTANTIATING_DRBG 188
+# define PROV_R_ERROR_RETRIEVING_ENTROPY 189
+# define PROV_R_ERROR_RETRIEVING_NONCE 190
+# define PROV_R_FAILED_DURING_DERIVATION 164
+# define PROV_R_FAILED_TO_CREATE_LOCK 180
+# define PROV_R_FAILED_TO_DECRYPT 162
+# define PROV_R_FAILED_TO_GENERATE_KEY 121
+# define PROV_R_FAILED_TO_GET_PARAMETER 103
+# define PROV_R_FAILED_TO_SET_PARAMETER 104
+# define PROV_R_FAILED_TO_SIGN 175
+# define PROV_R_FIPS_MODULE_CONDITIONAL_ERROR 227
+# define PROV_R_FIPS_MODULE_ENTERING_ERROR_STATE 224
+# define PROV_R_FIPS_MODULE_IN_ERROR_STATE 225
+# define PROV_R_GENERATE_ERROR 191
+# define PROV_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE 165
+# define PROV_R_INDICATOR_INTEGRITY_FAILURE 210
+# define PROV_R_INSUFFICIENT_DRBG_STRENGTH 181
+# define PROV_R_INVALID_AAD 108
+# define PROV_R_INVALID_CONFIG_DATA 211
+# define PROV_R_INVALID_CONSTANT_LENGTH 157
+# define PROV_R_INVALID_CURVE 176
+# define PROV_R_INVALID_CUSTOM_LENGTH 111
+# define PROV_R_INVALID_DATA 115
+# define PROV_R_INVALID_DIGEST 122
+# define PROV_R_INVALID_DIGEST_LENGTH 166
+# define PROV_R_INVALID_DIGEST_SIZE 218
+# define PROV_R_INVALID_INPUT_LENGTH 230
+# define PROV_R_INVALID_ITERATION_COUNT 123
+# define PROV_R_INVALID_IV_LENGTH 109
+# define PROV_R_INVALID_KEY 158
+# define PROV_R_INVALID_KEY_LENGTH 105
+# define PROV_R_INVALID_MAC 151
+# define PROV_R_INVALID_MGF1_MD 167
+# define PROV_R_INVALID_MODE 125
+# define PROV_R_INVALID_OUTPUT_LENGTH 217
+# define PROV_R_INVALID_PADDING_MODE 168
+# define PROV_R_INVALID_PUBINFO 198
+# define PROV_R_INVALID_SALT_LENGTH 112
+# define PROV_R_INVALID_SEED_LENGTH 154
+# define PROV_R_INVALID_SIGNATURE_SIZE 179
+# define PROV_R_INVALID_STATE 212
+# define PROV_R_INVALID_TAG 110
+# define PROV_R_INVALID_TAG_LENGTH 118
+# define PROV_R_INVALID_UKM_LENGTH 200
+# define PROV_R_INVALID_X931_DIGEST 170
+# define PROV_R_IN_ERROR_STATE 192
+# define PROV_R_KEY_SETUP_FAILED 101
+# define PROV_R_KEY_SIZE_TOO_SMALL 171
+# define PROV_R_LENGTH_TOO_LARGE 202
+# define PROV_R_MISMATCHING_DOMAIN_PARAMETERS 203
+# define PROV_R_MISSING_CEK_ALG 144
+# define PROV_R_MISSING_CIPHER 155
+# define PROV_R_MISSING_CONFIG_DATA 213
+# define PROV_R_MISSING_CONSTANT 156
+# define PROV_R_MISSING_KEY 128
+# define PROV_R_MISSING_MAC 150
+# define PROV_R_MISSING_MESSAGE_DIGEST 129
+# define PROV_R_MISSING_OID 209
+# define PROV_R_MISSING_PASS 130
+# define PROV_R_MISSING_SALT 131
+# define PROV_R_MISSING_SECRET 132
+# define PROV_R_MISSING_SEED 140
+# define PROV_R_MISSING_SESSION_ID 133
+# define PROV_R_MISSING_TYPE 134
+# define PROV_R_MISSING_XCGHASH 135
+# define PROV_R_MODULE_INTEGRITY_FAILURE 214
+# define PROV_R_NOT_A_PRIVATE_KEY 221
+# define PROV_R_NOT_A_PUBLIC_KEY 220
+# define PROV_R_NOT_INSTANTIATED 193
+# define PROV_R_NOT_PARAMETERS 226
+# define PROV_R_NOT_SUPPORTED 136
+# define PROV_R_NOT_XOF_OR_INVALID_LENGTH 113
+# define PROV_R_NO_KEY_SET 114
+# define PROV_R_NO_PARAMETERS_SET 177
+# define PROV_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 178
+# define PROV_R_OUTPUT_BUFFER_TOO_SMALL 106
+# define PROV_R_PARENT_CANNOT_GENERATE_RANDOM_NUMBERS 228
+# define PROV_R_PARENT_CANNOT_SUPPLY_ENTROPY_SEED 187
+# define PROV_R_PARENT_LOCKING_NOT_ENABLED 182
+# define PROV_R_PARENT_STRENGTH_TOO_WEAK 194
+# define PROV_R_PATH_MUST_BE_ABSOLUTE 219
+# define PROV_R_PERSONALISATION_STRING_TOO_LONG 195
+# define PROV_R_PSS_SALTLEN_TOO_SMALL 172
+# define PROV_R_REQUEST_TOO_LARGE_FOR_DRBG 196
+# define PROV_R_REQUIRE_CTR_MODE_CIPHER 206
+# define PROV_R_RESEED_ERROR 197
+# define PROV_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES 222
+# define PROV_R_SEED_SOURCES_MUST_NOT_HAVE_A_PARENT 229
+# define PROV_R_SELF_TEST_KAT_FAILURE 215
+# define PROV_R_SELF_TEST_POST_FAILURE 216
+# define PROV_R_TAG_NOT_NEEDED 120
+# define PROV_R_TAG_NOT_SET 119
+# define PROV_R_TOO_MANY_RECORDS 126
+# define PROV_R_UNABLE_TO_FIND_CIPHERS 207
+# define PROV_R_UNABLE_TO_GET_PARENT_STRENGTH 199
+# define PROV_R_UNABLE_TO_GET_PASSPHRASE 159
+# define PROV_R_UNABLE_TO_INITIALISE_CIPHERS 208
+# define PROV_R_UNABLE_TO_LOAD_SHA256 147
+# define PROV_R_UNABLE_TO_LOCK_PARENT 201
+# define PROV_R_UNABLE_TO_RESEED 204
+# define PROV_R_UNSUPPORTED_CEK_ALG 145
+# define PROV_R_UNSUPPORTED_KEY_SIZE 153
+# define PROV_R_UNSUPPORTED_MAC_TYPE 137
+# define PROV_R_UNSUPPORTED_NUMBER_OF_ROUNDS 152
+# define PROV_R_URI_AUTHORITY_UNSUPPORTED 223
+# define PROV_R_VALUE_ERROR 138
+# define PROV_R_WRONG_FINAL_BLOCK_LENGTH 107
+# define PROV_R_WRONG_OUTPUT_BUFFER_SIZE 139
+# define PROV_R_XOF_DIGESTS_NOT_ALLOWED 183
+# define PROV_R_XTS_DATA_UNIT_IS_TOO_LARGE 148
+# define PROV_R_XTS_DUPLICATED_KEYS 149
+
+#endif
diff --git a/include/openssl/provider.h b/include/openssl/provider.h
new file mode 100644
index 00000000..dc86ff58
--- /dev/null
+++ b/include/openssl/provider.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_PROVIDER_H
+# define OPENSSL_PROVIDER_H
+# pragma once
+
+# include <openssl/core.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* Set the default provider search path */
+int OSSL_PROVIDER_set_default_search_path(OSSL_LIB_CTX *, const char *path);
+
+/* Load and unload a provider */
+OSSL_PROVIDER *OSSL_PROVIDER_load(OSSL_LIB_CTX *, const char *name);
+OSSL_PROVIDER *OSSL_PROVIDER_try_load(OSSL_LIB_CTX *, const char *name,
+ int retain_fallbacks);
+int OSSL_PROVIDER_unload(OSSL_PROVIDER *prov);
+int OSSL_PROVIDER_available(OSSL_LIB_CTX *, const char *name);
+int OSSL_PROVIDER_do_all(OSSL_LIB_CTX *ctx,
+ int (*cb)(OSSL_PROVIDER *provider, void *cbdata),
+ void *cbdata);
+
+const OSSL_PARAM *OSSL_PROVIDER_gettable_params(const OSSL_PROVIDER *prov);
+int OSSL_PROVIDER_get_params(const OSSL_PROVIDER *prov, OSSL_PARAM params[]);
+int OSSL_PROVIDER_self_test(const OSSL_PROVIDER *prov);
+int OSSL_PROVIDER_get_capabilities(const OSSL_PROVIDER *prov,
+ const char *capability,
+ OSSL_CALLBACK *cb,
+ void *arg);
+
+const OSSL_ALGORITHM *OSSL_PROVIDER_query_operation(const OSSL_PROVIDER *prov,
+ int operation_id,
+ int *no_cache);
+void OSSL_PROVIDER_unquery_operation(const OSSL_PROVIDER *prov,
+ int operation_id, const OSSL_ALGORITHM *algs);
+void *OSSL_PROVIDER_get0_provider_ctx(const OSSL_PROVIDER *prov);
+const OSSL_DISPATCH *OSSL_PROVIDER_get0_dispatch(const OSSL_PROVIDER *prov);
+
+/* Add a built in providers */
+int OSSL_PROVIDER_add_builtin(OSSL_LIB_CTX *, const char *name,
+ OSSL_provider_init_fn *init_fn);
+
+/* Information */
+const char *OSSL_PROVIDER_get0_name(const OSSL_PROVIDER *prov);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/rand.h b/include/openssl/rand.h
new file mode 100644
index 00000000..ad3054fd
--- /dev/null
+++ b/include/openssl/rand.h
@@ -0,0 +1,123 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RAND_H
+# define OPENSSL_RAND_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_RAND_H
+# endif
+
+# include <stdlib.h>
+# include <openssl/types.h>
+# include <openssl/e_os2.h>
+# include <openssl/randerr.h>
+# include <openssl/evp.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Default security strength (in the sense of [NIST SP 800-90Ar1])
+ *
+ * NIST SP 800-90Ar1 supports the strength of the DRBG being smaller than that
+ * of the cipher by collecting less entropy. The current DRBG implementation
+ * does not take RAND_DRBG_STRENGTH into account and sets the strength of the
+ * DRBG to that of the cipher.
+ */
+# define RAND_DRBG_STRENGTH 256
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+struct rand_meth_st {
+ int (*seed) (const void *buf, int num);
+ int (*bytes) (unsigned char *buf, int num);
+ void (*cleanup) (void);
+ int (*add) (const void *buf, int num, double randomness);
+ int (*pseudorand) (unsigned char *buf, int num);
+ int (*status) (void);
+};
+
+OSSL_DEPRECATEDIN_3_0 int RAND_set_rand_method(const RAND_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 const RAND_METHOD *RAND_get_rand_method(void);
+# ifndef OPENSSL_NO_ENGINE
+OSSL_DEPRECATEDIN_3_0 int RAND_set_rand_engine(ENGINE *engine);
+# endif
+
+OSSL_DEPRECATEDIN_3_0 RAND_METHOD *RAND_OpenSSL(void);
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define RAND_cleanup() while(0) continue
+# endif
+int RAND_bytes(unsigned char *buf, int num);
+int RAND_priv_bytes(unsigned char *buf, int num);
+
+/*
+ * Equivalent of RAND_priv_bytes() but additionally taking an OSSL_LIB_CTX and
+ * a strength.
+ */
+int RAND_priv_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num,
+ unsigned int strength);
+
+/*
+ * Equivalent of RAND_bytes() but additionally taking an OSSL_LIB_CTX and
+ * a strength.
+ */
+int RAND_bytes_ex(OSSL_LIB_CTX *ctx, unsigned char *buf, size_t num,
+ unsigned int strength);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 int RAND_pseudo_bytes(unsigned char *buf, int num);
+# endif
+
+EVP_RAND_CTX *RAND_get0_primary(OSSL_LIB_CTX *ctx);
+EVP_RAND_CTX *RAND_get0_public(OSSL_LIB_CTX *ctx);
+EVP_RAND_CTX *RAND_get0_private(OSSL_LIB_CTX *ctx);
+
+int RAND_set_DRBG_type(OSSL_LIB_CTX *ctx, const char *drbg, const char *propq,
+ const char *cipher, const char *digest);
+int RAND_set_seed_source_type(OSSL_LIB_CTX *ctx, const char *seed,
+ const char *propq);
+
+void RAND_seed(const void *buf, int num);
+void RAND_keep_random_devices_open(int keep);
+
+# if defined(__ANDROID__) && defined(__NDK_FPABI__)
+__NDK_FPABI__ /* __attribute__((pcs("aapcs"))) on ARM */
+# endif
+void RAND_add(const void *buf, int num, double randomness);
+int RAND_load_file(const char *file, long max_bytes);
+int RAND_write_file(const char *file);
+const char *RAND_file_name(char *file, size_t num);
+int RAND_status(void);
+
+# ifndef OPENSSL_NO_EGD
+int RAND_query_egd_bytes(const char *path, unsigned char *buf, int bytes);
+int RAND_egd(const char *path);
+int RAND_egd_bytes(const char *path, int bytes);
+# endif
+
+int RAND_poll(void);
+
+# if defined(_WIN32) && (defined(BASETYPES) || defined(_WINDEF_H))
+/* application has to include <windows.h> in order to use these */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void RAND_screen(void);
+OSSL_DEPRECATEDIN_1_1_0 int RAND_event(UINT, WPARAM, LPARAM);
+# endif
+# endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/randerr.h b/include/openssl/randerr.h
new file mode 100644
index 00000000..b5e08e43
--- /dev/null
+++ b/include/openssl/randerr.h
@@ -0,0 +1,68 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RANDERR_H
+# define OPENSSL_RANDERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * RAND reason codes.
+ */
+# define RAND_R_ADDITIONAL_INPUT_TOO_LONG 102
+# define RAND_R_ALREADY_INSTANTIATED 103
+# define RAND_R_ARGUMENT_OUT_OF_RANGE 105
+# define RAND_R_CANNOT_OPEN_FILE 121
+# define RAND_R_DRBG_ALREADY_INITIALIZED 129
+# define RAND_R_DRBG_NOT_INITIALISED 104
+# define RAND_R_ENTROPY_INPUT_TOO_LONG 106
+# define RAND_R_ENTROPY_OUT_OF_RANGE 124
+# define RAND_R_ERROR_ENTROPY_POOL_WAS_IGNORED 127
+# define RAND_R_ERROR_INITIALISING_DRBG 107
+# define RAND_R_ERROR_INSTANTIATING_DRBG 108
+# define RAND_R_ERROR_RETRIEVING_ADDITIONAL_INPUT 109
+# define RAND_R_ERROR_RETRIEVING_ENTROPY 110
+# define RAND_R_ERROR_RETRIEVING_NONCE 111
+# define RAND_R_FAILED_TO_CREATE_LOCK 126
+# define RAND_R_FUNC_NOT_IMPLEMENTED 101
+# define RAND_R_FWRITE_ERROR 123
+# define RAND_R_GENERATE_ERROR 112
+# define RAND_R_INSUFFICIENT_DRBG_STRENGTH 139
+# define RAND_R_INTERNAL_ERROR 113
+# define RAND_R_IN_ERROR_STATE 114
+# define RAND_R_NOT_A_REGULAR_FILE 122
+# define RAND_R_NOT_INSTANTIATED 115
+# define RAND_R_NO_DRBG_IMPLEMENTATION_SELECTED 128
+# define RAND_R_PARENT_LOCKING_NOT_ENABLED 130
+# define RAND_R_PARENT_STRENGTH_TOO_WEAK 131
+# define RAND_R_PERSONALISATION_STRING_TOO_LONG 116
+# define RAND_R_PREDICTION_RESISTANCE_NOT_SUPPORTED 133
+# define RAND_R_PRNG_NOT_SEEDED 100
+# define RAND_R_RANDOM_POOL_OVERFLOW 125
+# define RAND_R_RANDOM_POOL_UNDERFLOW 134
+# define RAND_R_REQUEST_TOO_LARGE_FOR_DRBG 117
+# define RAND_R_RESEED_ERROR 118
+# define RAND_R_SELFTEST_FAILURE 119
+# define RAND_R_TOO_LITTLE_NONCE_REQUESTED 135
+# define RAND_R_TOO_MUCH_NONCE_REQUESTED 136
+# define RAND_R_UNABLE_TO_CREATE_DRBG 143
+# define RAND_R_UNABLE_TO_FETCH_DRBG 144
+# define RAND_R_UNABLE_TO_GET_PARENT_RESEED_PROP_COUNTER 141
+# define RAND_R_UNABLE_TO_GET_PARENT_STRENGTH 138
+# define RAND_R_UNABLE_TO_LOCK_PARENT 140
+# define RAND_R_UNSUPPORTED_DRBG_FLAGS 132
+# define RAND_R_UNSUPPORTED_DRBG_TYPE 120
+
+#endif
diff --git a/include/openssl/rc2.h b/include/openssl/rc2.h
new file mode 100644
index 00000000..ff633fd8
--- /dev/null
+++ b/include/openssl/rc2.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RC2_H
+# define OPENSSL_RC2_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_RC2_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_RC2
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define RC2_BLOCK 8
+# define RC2_KEY_LENGTH 16
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef unsigned int RC2_INT;
+
+# define RC2_ENCRYPT 1
+# define RC2_DECRYPT 0
+
+typedef struct rc2_key_st {
+ RC2_INT data[64];
+} RC2_KEY;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 void RC2_set_key(RC2_KEY *key, int len,
+ const unsigned char *data, int bits);
+OSSL_DEPRECATEDIN_3_0 void RC2_ecb_encrypt(const unsigned char *in,
+ unsigned char *out, RC2_KEY *key,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void RC2_encrypt(unsigned long *data, RC2_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void RC2_decrypt(unsigned long *data, RC2_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void RC2_cbc_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ RC2_KEY *ks, unsigned char *iv,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void RC2_cfb64_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ RC2_KEY *schedule,
+ unsigned char *ivec,
+ int *num, int enc);
+OSSL_DEPRECATEDIN_3_0 void RC2_ofb64_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ RC2_KEY *schedule,
+ unsigned char *ivec,
+ int *num);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/rc4.h b/include/openssl/rc4.h
new file mode 100644
index 00000000..600b2885
--- /dev/null
+++ b/include/openssl/rc4.h
@@ -0,0 +1,47 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RC4_H
+# define OPENSSL_RC4_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_RC4_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_RC4
+# include <stddef.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef struct rc4_key_st {
+ RC4_INT x, y;
+ RC4_INT data[256];
+} RC4_KEY;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 const char *RC4_options(void);
+OSSL_DEPRECATEDIN_3_0 void RC4_set_key(RC4_KEY *key, int len,
+ const unsigned char *data);
+OSSL_DEPRECATEDIN_3_0 void RC4(RC4_KEY *key, size_t len,
+ const unsigned char *indata,
+ unsigned char *outdata);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/rc5.h b/include/openssl/rc5.h
new file mode 100644
index 00000000..de833523
--- /dev/null
+++ b/include/openssl/rc5.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RC5_H
+# define OPENSSL_RC5_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_RC5_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_RC5
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define RC5_32_BLOCK 8
+# define RC5_32_KEY_LENGTH 16/* This is a default, max is 255 */
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define RC5_ENCRYPT 1
+# define RC5_DECRYPT 0
+
+# define RC5_32_INT unsigned int
+
+/*
+ * This are the only values supported. Tweak the code if you want more The
+ * most supported modes will be RC5-32/12/16 RC5-32/16/8
+ */
+# define RC5_8_ROUNDS 8
+# define RC5_12_ROUNDS 12
+# define RC5_16_ROUNDS 16
+
+typedef struct rc5_key_st {
+ /* Number of rounds */
+ int rounds;
+ RC5_32_INT data[2 * (RC5_16_ROUNDS + 1)];
+} RC5_32_KEY;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int RC5_32_set_key(RC5_32_KEY *key, int len,
+ const unsigned char *data,
+ int rounds);
+OSSL_DEPRECATEDIN_3_0 void RC5_32_ecb_encrypt(const unsigned char *in,
+ unsigned char *out,
+ RC5_32_KEY *key,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void RC5_32_encrypt(unsigned long *data, RC5_32_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void RC5_32_decrypt(unsigned long *data, RC5_32_KEY *key);
+OSSL_DEPRECATEDIN_3_0 void RC5_32_cbc_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ RC5_32_KEY *ks, unsigned char *iv,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void RC5_32_cfb64_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ RC5_32_KEY *schedule,
+ unsigned char *ivec, int *num,
+ int enc);
+OSSL_DEPRECATEDIN_3_0 void RC5_32_ofb64_encrypt(const unsigned char *in,
+ unsigned char *out, long length,
+ RC5_32_KEY *schedule,
+ unsigned char *ivec, int *num);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/ripemd.h b/include/openssl/ripemd.h
new file mode 100644
index 00000000..900ee317
--- /dev/null
+++ b/include/openssl/ripemd.h
@@ -0,0 +1,59 @@
+/*
+ * Copyright 1995-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RIPEMD_H
+# define OPENSSL_RIPEMD_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_RIPEMD_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_RMD160
+# include <openssl/e_os2.h>
+# include <stddef.h>
+
+# define RIPEMD160_DIGEST_LENGTH 20
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+# if !defined(OPENSSL_NO_DEPRECATED_3_0)
+
+# define RIPEMD160_LONG unsigned int
+
+# define RIPEMD160_CBLOCK 64
+# define RIPEMD160_LBLOCK (RIPEMD160_CBLOCK/4)
+
+typedef struct RIPEMD160state_st {
+ RIPEMD160_LONG A, B, C, D, E;
+ RIPEMD160_LONG Nl, Nh;
+ RIPEMD160_LONG data[RIPEMD160_LBLOCK];
+ unsigned int num;
+} RIPEMD160_CTX;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int RIPEMD160_Init(RIPEMD160_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int RIPEMD160_Update(RIPEMD160_CTX *c, const void *data,
+ size_t len);
+OSSL_DEPRECATEDIN_3_0 int RIPEMD160_Final(unsigned char *md, RIPEMD160_CTX *c);
+OSSL_DEPRECATEDIN_3_0 unsigned char *RIPEMD160(const unsigned char *d, size_t n,
+ unsigned char *md);
+OSSL_DEPRECATEDIN_3_0 void RIPEMD160_Transform(RIPEMD160_CTX *c,
+ const unsigned char *b);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/rsa.h b/include/openssl/rsa.h
new file mode 100644
index 00000000..a55c9727
--- /dev/null
+++ b/include/openssl/rsa.h
@@ -0,0 +1,604 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RSA_H
+# define OPENSSL_RSA_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_RSA_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# include <openssl/asn1.h>
+# include <openssl/bio.h>
+# include <openssl/crypto.h>
+# include <openssl/types.h>
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/bn.h>
+# endif
+# include <openssl/rsaerr.h>
+# include <openssl/safestack.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_RSA_MAX_MODULUS_BITS
+# define OPENSSL_RSA_MAX_MODULUS_BITS 16384
+# endif
+
+# define RSA_3 0x3L
+# define RSA_F4 0x10001L
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* The types RSA and RSA_METHOD are defined in ossl_typ.h */
+
+# define OPENSSL_RSA_FIPS_MIN_MODULUS_BITS 2048
+
+# ifndef OPENSSL_RSA_SMALL_MODULUS_BITS
+# define OPENSSL_RSA_SMALL_MODULUS_BITS 3072
+# endif
+
+/* exponent limit enforced for "large" modulus only */
+# ifndef OPENSSL_RSA_MAX_PUBEXP_BITS
+# define OPENSSL_RSA_MAX_PUBEXP_BITS 64
+# endif
+/* based on RFC 8017 appendix A.1.2 */
+# define RSA_ASN1_VERSION_DEFAULT 0
+# define RSA_ASN1_VERSION_MULTI 1
+
+# define RSA_DEFAULT_PRIME_NUM 2
+
+# define RSA_METHOD_FLAG_NO_CHECK 0x0001
+# define RSA_FLAG_CACHE_PUBLIC 0x0002
+# define RSA_FLAG_CACHE_PRIVATE 0x0004
+# define RSA_FLAG_BLINDING 0x0008
+# define RSA_FLAG_THREAD_SAFE 0x0010
+/*
+ * This flag means the private key operations will be handled by rsa_mod_exp
+ * and that they do not depend on the private key components being present:
+ * for example a key stored in external hardware. Without this flag
+ * bn_mod_exp gets called when private key components are absent.
+ */
+# define RSA_FLAG_EXT_PKEY 0x0020
+
+/*
+ * new with 0.9.6j and 0.9.7b; the built-in
+ * RSA implementation now uses blinding by
+ * default (ignoring RSA_FLAG_BLINDING),
+ * but other engines might not need it
+ */
+# define RSA_FLAG_NO_BLINDING 0x0080
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+/*
+ * Does nothing. Previously this switched off constant time behaviour.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define RSA_FLAG_NO_CONSTTIME 0x0000
+# endif
+/* deprecated name for the flag*/
+/*
+ * new with 0.9.7h; the built-in RSA
+ * implementation now uses constant time
+ * modular exponentiation for secret exponents
+ * by default. This flag causes the
+ * faster variable sliding window method to
+ * be used for all exponents.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_0_9_8
+# define RSA_FLAG_NO_EXP_CONSTTIME RSA_FLAG_NO_CONSTTIME
+# endif
+
+/*-
+ * New with 3.0: use part of the flags to denote exact type of RSA key,
+ * some of which are limited to specific signature and encryption schemes.
+ * These different types share the same RSA structure, but indicate the
+ * use of certain fields in that structure.
+ * Currently known are:
+ * RSA - this is the "normal" unlimited RSA structure (typenum 0)
+ * RSASSA-PSS - indicates that the PSS parameters are used.
+ * RSAES-OAEP - no specific field used for the moment, but OAEP padding
+ * is expected. (currently unused)
+ *
+ * 4 bits allow for 16 types
+ */
+# define RSA_FLAG_TYPE_MASK 0xF000
+# define RSA_FLAG_TYPE_RSA 0x0000
+# define RSA_FLAG_TYPE_RSASSAPSS 0x1000
+# define RSA_FLAG_TYPE_RSAESOAEP 0x2000
+
+int EVP_PKEY_CTX_set_rsa_padding(EVP_PKEY_CTX *ctx, int pad_mode);
+int EVP_PKEY_CTX_get_rsa_padding(EVP_PKEY_CTX *ctx, int *pad_mode);
+
+int EVP_PKEY_CTX_set_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int saltlen);
+int EVP_PKEY_CTX_get_rsa_pss_saltlen(EVP_PKEY_CTX *ctx, int *saltlen);
+
+int EVP_PKEY_CTX_set_rsa_keygen_bits(EVP_PKEY_CTX *ctx, int bits);
+int EVP_PKEY_CTX_set1_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *pubexp);
+int EVP_PKEY_CTX_set_rsa_keygen_primes(EVP_PKEY_CTX *ctx, int primes);
+int EVP_PKEY_CTX_set_rsa_pss_keygen_saltlen(EVP_PKEY_CTX *ctx, int saltlen);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int EVP_PKEY_CTX_set_rsa_keygen_pubexp(EVP_PKEY_CTX *ctx, BIGNUM *pubexp);
+# endif
+
+/* Salt length matches digest */
+# define RSA_PSS_SALTLEN_DIGEST -1
+/* Verify only: auto detect salt length */
+# define RSA_PSS_SALTLEN_AUTO -2
+/* Set salt length to maximum possible */
+# define RSA_PSS_SALTLEN_MAX -3
+/* Old compatible max salt length for sign only */
+# define RSA_PSS_SALTLEN_MAX_SIGN -2
+
+int EVP_PKEY_CTX_set_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+int EVP_PKEY_CTX_set_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, const char *mdname,
+ const char *mdprops);
+int EVP_PKEY_CTX_get_rsa_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD **md);
+int EVP_PKEY_CTX_get_rsa_mgf1_md_name(EVP_PKEY_CTX *ctx, char *name,
+ size_t namelen);
+int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+int EVP_PKEY_CTX_set_rsa_pss_keygen_mgf1_md_name(EVP_PKEY_CTX *ctx,
+ const char *mdname);
+
+int EVP_PKEY_CTX_set_rsa_pss_keygen_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+int EVP_PKEY_CTX_set_rsa_pss_keygen_md_name(EVP_PKEY_CTX *ctx,
+ const char *mdname,
+ const char *mdprops);
+
+int EVP_PKEY_CTX_set_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD *md);
+int EVP_PKEY_CTX_set_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, const char *mdname,
+ const char *mdprops);
+int EVP_PKEY_CTX_get_rsa_oaep_md(EVP_PKEY_CTX *ctx, const EVP_MD **md);
+int EVP_PKEY_CTX_get_rsa_oaep_md_name(EVP_PKEY_CTX *ctx, char *name,
+ size_t namelen);
+int EVP_PKEY_CTX_set0_rsa_oaep_label(EVP_PKEY_CTX *ctx, void *label, int llen);
+int EVP_PKEY_CTX_get0_rsa_oaep_label(EVP_PKEY_CTX *ctx, unsigned char **label);
+
+# define EVP_PKEY_CTRL_RSA_PADDING (EVP_PKEY_ALG_CTRL + 1)
+# define EVP_PKEY_CTRL_RSA_PSS_SALTLEN (EVP_PKEY_ALG_CTRL + 2)
+
+# define EVP_PKEY_CTRL_RSA_KEYGEN_BITS (EVP_PKEY_ALG_CTRL + 3)
+# define EVP_PKEY_CTRL_RSA_KEYGEN_PUBEXP (EVP_PKEY_ALG_CTRL + 4)
+# define EVP_PKEY_CTRL_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 5)
+
+# define EVP_PKEY_CTRL_GET_RSA_PADDING (EVP_PKEY_ALG_CTRL + 6)
+# define EVP_PKEY_CTRL_GET_RSA_PSS_SALTLEN (EVP_PKEY_ALG_CTRL + 7)
+# define EVP_PKEY_CTRL_GET_RSA_MGF1_MD (EVP_PKEY_ALG_CTRL + 8)
+
+# define EVP_PKEY_CTRL_RSA_OAEP_MD (EVP_PKEY_ALG_CTRL + 9)
+# define EVP_PKEY_CTRL_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 10)
+
+# define EVP_PKEY_CTRL_GET_RSA_OAEP_MD (EVP_PKEY_ALG_CTRL + 11)
+# define EVP_PKEY_CTRL_GET_RSA_OAEP_LABEL (EVP_PKEY_ALG_CTRL + 12)
+
+# define EVP_PKEY_CTRL_RSA_KEYGEN_PRIMES (EVP_PKEY_ALG_CTRL + 13)
+
+# define RSA_PKCS1_PADDING 1
+# define RSA_NO_PADDING 3
+# define RSA_PKCS1_OAEP_PADDING 4
+# define RSA_X931_PADDING 5
+
+/* EVP_PKEY_ only */
+# define RSA_PKCS1_PSS_PADDING 6
+# define RSA_PKCS1_WITH_TLS_PADDING 7
+
+# define RSA_PKCS1_PADDING_SIZE 11
+
+# define RSA_set_app_data(s,arg) RSA_set_ex_data(s,0,arg)
+# define RSA_get_app_data(s) RSA_get_ex_data(s,0)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 RSA *RSA_new(void);
+OSSL_DEPRECATEDIN_3_0 RSA *RSA_new_method(ENGINE *engine);
+OSSL_DEPRECATEDIN_3_0 int RSA_bits(const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 int RSA_size(const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 int RSA_security_bits(const RSA *rsa);
+
+OSSL_DEPRECATEDIN_3_0 int RSA_set0_key(RSA *r, BIGNUM *n, BIGNUM *e, BIGNUM *d);
+OSSL_DEPRECATEDIN_3_0 int RSA_set0_factors(RSA *r, BIGNUM *p, BIGNUM *q);
+OSSL_DEPRECATEDIN_3_0 int RSA_set0_crt_params(RSA *r,
+ BIGNUM *dmp1, BIGNUM *dmq1,
+ BIGNUM *iqmp);
+OSSL_DEPRECATEDIN_3_0 int RSA_set0_multi_prime_params(RSA *r,
+ BIGNUM *primes[],
+ BIGNUM *exps[],
+ BIGNUM *coeffs[],
+ int pnum);
+OSSL_DEPRECATEDIN_3_0 void RSA_get0_key(const RSA *r,
+ const BIGNUM **n, const BIGNUM **e,
+ const BIGNUM **d);
+OSSL_DEPRECATEDIN_3_0 void RSA_get0_factors(const RSA *r,
+ const BIGNUM **p, const BIGNUM **q);
+OSSL_DEPRECATEDIN_3_0 int RSA_get_multi_prime_extra_count(const RSA *r);
+OSSL_DEPRECATEDIN_3_0 int RSA_get0_multi_prime_factors(const RSA *r,
+ const BIGNUM *primes[]);
+OSSL_DEPRECATEDIN_3_0 void RSA_get0_crt_params(const RSA *r,
+ const BIGNUM **dmp1,
+ const BIGNUM **dmq1,
+ const BIGNUM **iqmp);
+OSSL_DEPRECATEDIN_3_0
+int RSA_get0_multi_prime_crt_params(const RSA *r, const BIGNUM *exps[],
+ const BIGNUM *coeffs[]);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_n(const RSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_e(const RSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_d(const RSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_p(const RSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_q(const RSA *d);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_dmp1(const RSA *r);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_dmq1(const RSA *r);
+OSSL_DEPRECATEDIN_3_0 const BIGNUM *RSA_get0_iqmp(const RSA *r);
+OSSL_DEPRECATEDIN_3_0 const RSA_PSS_PARAMS *RSA_get0_pss_params(const RSA *r);
+OSSL_DEPRECATEDIN_3_0 void RSA_clear_flags(RSA *r, int flags);
+OSSL_DEPRECATEDIN_3_0 int RSA_test_flags(const RSA *r, int flags);
+OSSL_DEPRECATEDIN_3_0 void RSA_set_flags(RSA *r, int flags);
+OSSL_DEPRECATEDIN_3_0 int RSA_get_version(RSA *r);
+OSSL_DEPRECATEDIN_3_0 ENGINE *RSA_get0_engine(const RSA *r);
+# endif /* !OPENSSL_NO_DEPRECATED_3_0 */
+
+# define EVP_RSA_gen(bits) \
+ EVP_PKEY_Q_keygen(NULL, NULL, "RSA", (size_t)(0 + (bits)))
+
+/* Deprecated version */
+# ifndef OPENSSL_NO_DEPRECATED_0_9_8
+OSSL_DEPRECATEDIN_0_9_8 RSA *RSA_generate_key(int bits, unsigned long e, void
+ (*callback) (int, int, void *),
+ void *cb_arg);
+# endif
+
+/* New version */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int RSA_generate_key_ex(RSA *rsa, int bits, BIGNUM *e,
+ BN_GENCB *cb);
+/* Multi-prime version */
+OSSL_DEPRECATEDIN_3_0 int RSA_generate_multi_prime_key(RSA *rsa, int bits,
+ int primes, BIGNUM *e,
+ BN_GENCB *cb);
+
+OSSL_DEPRECATEDIN_3_0
+int RSA_X931_derive_ex(RSA *rsa, BIGNUM *p1, BIGNUM *p2,
+ BIGNUM *q1, BIGNUM *q2,
+ const BIGNUM *Xp1, const BIGNUM *Xp2,
+ const BIGNUM *Xp, const BIGNUM *Xq1,
+ const BIGNUM *Xq2, const BIGNUM *Xq,
+ const BIGNUM *e, BN_GENCB *cb);
+OSSL_DEPRECATEDIN_3_0 int RSA_X931_generate_key_ex(RSA *rsa, int bits,
+ const BIGNUM *e,
+ BN_GENCB *cb);
+
+OSSL_DEPRECATEDIN_3_0 int RSA_check_key(const RSA *);
+OSSL_DEPRECATEDIN_3_0 int RSA_check_key_ex(const RSA *, BN_GENCB *cb);
+ /* next 4 return -1 on error */
+OSSL_DEPRECATEDIN_3_0
+int RSA_public_encrypt(int flen, const unsigned char *from, unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0
+int RSA_private_encrypt(int flen, const unsigned char *from, unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0
+int RSA_public_decrypt(int flen, const unsigned char *from, unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0
+int RSA_private_decrypt(int flen, const unsigned char *from, unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0 void RSA_free(RSA *r);
+/* "up" the RSA object's reference count */
+OSSL_DEPRECATEDIN_3_0 int RSA_up_ref(RSA *r);
+OSSL_DEPRECATEDIN_3_0 int RSA_flags(const RSA *r);
+
+OSSL_DEPRECATEDIN_3_0 void RSA_set_default_method(const RSA_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 const RSA_METHOD *RSA_get_default_method(void);
+OSSL_DEPRECATEDIN_3_0 const RSA_METHOD *RSA_null_method(void);
+OSSL_DEPRECATEDIN_3_0 const RSA_METHOD *RSA_get_method(const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 int RSA_set_method(RSA *rsa, const RSA_METHOD *meth);
+
+/* these are the actual RSA functions */
+OSSL_DEPRECATEDIN_3_0 const RSA_METHOD *RSA_PKCS1_OpenSSL(void);
+
+DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(OSSL_DEPRECATEDIN_3_0,
+ RSA, RSAPublicKey)
+DECLARE_ASN1_ENCODE_FUNCTIONS_name_attr(OSSL_DEPRECATEDIN_3_0,
+ RSA, RSAPrivateKey)
+# endif /* !OPENSSL_NO_DEPRECATED_3_0 */
+
+int RSA_pkey_ctx_ctrl(EVP_PKEY_CTX *ctx, int optype, int cmd, int p1, void *p2);
+
+struct rsa_pss_params_st {
+ X509_ALGOR *hashAlgorithm;
+ X509_ALGOR *maskGenAlgorithm;
+ ASN1_INTEGER *saltLength;
+ ASN1_INTEGER *trailerField;
+ /* Decoded hash algorithm from maskGenAlgorithm */
+ X509_ALGOR *maskHash;
+};
+
+DECLARE_ASN1_FUNCTIONS(RSA_PSS_PARAMS)
+DECLARE_ASN1_DUP_FUNCTION(RSA_PSS_PARAMS)
+
+typedef struct rsa_oaep_params_st {
+ X509_ALGOR *hashFunc;
+ X509_ALGOR *maskGenFunc;
+ X509_ALGOR *pSourceFunc;
+ /* Decoded hash algorithm from maskGenFunc */
+ X509_ALGOR *maskHash;
+} RSA_OAEP_PARAMS;
+
+DECLARE_ASN1_FUNCTIONS(RSA_OAEP_PARAMS)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_STDIO
+OSSL_DEPRECATEDIN_3_0 int RSA_print_fp(FILE *fp, const RSA *r, int offset);
+# endif
+
+OSSL_DEPRECATEDIN_3_0 int RSA_print(BIO *bp, const RSA *r, int offset);
+
+/*
+ * The following 2 functions sign and verify a X509_SIG ASN1 object inside
+ * PKCS#1 padded RSA encryption
+ */
+OSSL_DEPRECATEDIN_3_0 int RSA_sign(int type, const unsigned char *m,
+ unsigned int m_length, unsigned char *sigret,
+ unsigned int *siglen, RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 int RSA_verify(int type, const unsigned char *m,
+ unsigned int m_length,
+ const unsigned char *sigbuf,
+ unsigned int siglen, RSA *rsa);
+
+/*
+ * The following 2 function sign and verify a ASN1_OCTET_STRING object inside
+ * PKCS#1 padded RSA encryption
+ */
+OSSL_DEPRECATEDIN_3_0
+int RSA_sign_ASN1_OCTET_STRING(int type,
+ const unsigned char *m, unsigned int m_length,
+ unsigned char *sigret, unsigned int *siglen,
+ RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+int RSA_verify_ASN1_OCTET_STRING(int type,
+ const unsigned char *m, unsigned int m_length,
+ unsigned char *sigbuf, unsigned int siglen,
+ RSA *rsa);
+
+OSSL_DEPRECATEDIN_3_0 int RSA_blinding_on(RSA *rsa, BN_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 void RSA_blinding_off(RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 BN_BLINDING *RSA_setup_blinding(RSA *rsa, BN_CTX *ctx);
+
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_add_PKCS1_type_1(unsigned char *to, int tlen,
+ const unsigned char *f, int fl);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_check_PKCS1_type_1(unsigned char *to, int tlen,
+ const unsigned char *f, int fl,
+ int rsa_len);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_add_PKCS1_type_2(unsigned char *to, int tlen,
+ const unsigned char *f, int fl);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_check_PKCS1_type_2(unsigned char *to, int tlen,
+ const unsigned char *f, int fl,
+ int rsa_len);
+OSSL_DEPRECATEDIN_3_0 int PKCS1_MGF1(unsigned char *mask, long len,
+ const unsigned char *seed, long seedlen,
+ const EVP_MD *dgst);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_add_PKCS1_OAEP(unsigned char *to, int tlen,
+ const unsigned char *f, int fl,
+ const unsigned char *p, int pl);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_check_PKCS1_OAEP(unsigned char *to, int tlen,
+ const unsigned char *f, int fl, int rsa_len,
+ const unsigned char *p, int pl);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_add_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
+ const unsigned char *from, int flen,
+ const unsigned char *param, int plen,
+ const EVP_MD *md, const EVP_MD *mgf1md);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_check_PKCS1_OAEP_mgf1(unsigned char *to, int tlen,
+ const unsigned char *from, int flen,
+ int num,
+ const unsigned char *param, int plen,
+ const EVP_MD *md, const EVP_MD *mgf1md);
+OSSL_DEPRECATEDIN_3_0 int RSA_padding_add_none(unsigned char *to, int tlen,
+ const unsigned char *f, int fl);
+OSSL_DEPRECATEDIN_3_0 int RSA_padding_check_none(unsigned char *to, int tlen,
+ const unsigned char *f, int fl,
+ int rsa_len);
+OSSL_DEPRECATEDIN_3_0 int RSA_padding_add_X931(unsigned char *to, int tlen,
+ const unsigned char *f, int fl);
+OSSL_DEPRECATEDIN_3_0 int RSA_padding_check_X931(unsigned char *to, int tlen,
+ const unsigned char *f, int fl,
+ int rsa_len);
+OSSL_DEPRECATEDIN_3_0 int RSA_X931_hash_id(int nid);
+
+OSSL_DEPRECATEDIN_3_0
+int RSA_verify_PKCS1_PSS(RSA *rsa, const unsigned char *mHash,
+ const EVP_MD *Hash, const unsigned char *EM,
+ int sLen);
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_add_PKCS1_PSS(RSA *rsa, unsigned char *EM,
+ const unsigned char *mHash, const EVP_MD *Hash,
+ int sLen);
+
+OSSL_DEPRECATEDIN_3_0
+int RSA_verify_PKCS1_PSS_mgf1(RSA *rsa, const unsigned char *mHash,
+ const EVP_MD *Hash, const EVP_MD *mgf1Hash,
+ const unsigned char *EM, int sLen);
+
+OSSL_DEPRECATEDIN_3_0
+int RSA_padding_add_PKCS1_PSS_mgf1(RSA *rsa, unsigned char *EM,
+ const unsigned char *mHash,
+ const EVP_MD *Hash, const EVP_MD *mgf1Hash,
+ int sLen);
+
+# define RSA_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_RSA, l, p, newf, dupf, freef)
+OSSL_DEPRECATEDIN_3_0 int RSA_set_ex_data(RSA *r, int idx, void *arg);
+OSSL_DEPRECATEDIN_3_0 void *RSA_get_ex_data(const RSA *r, int idx);
+
+DECLARE_ASN1_DUP_FUNCTION_name_attr(OSSL_DEPRECATEDIN_3_0, RSA, RSAPublicKey)
+DECLARE_ASN1_DUP_FUNCTION_name_attr(OSSL_DEPRECATEDIN_3_0, RSA, RSAPrivateKey)
+
+/*
+ * If this flag is set the RSA method is FIPS compliant and can be used in
+ * FIPS mode. This is set in the validated module method. If an application
+ * sets this flag in its own methods it is its responsibility to ensure the
+ * result is compliant.
+ */
+
+# define RSA_FLAG_FIPS_METHOD 0x0400
+
+/*
+ * If this flag is set the operations normally disabled in FIPS mode are
+ * permitted it is then the applications responsibility to ensure that the
+ * usage is compliant.
+ */
+
+# define RSA_FLAG_NON_FIPS_ALLOW 0x0400
+/*
+ * Application has decided PRNG is good enough to generate a key: don't
+ * check.
+ */
+# define RSA_FLAG_CHECKED 0x0800
+
+OSSL_DEPRECATEDIN_3_0 RSA_METHOD *RSA_meth_new(const char *name, int flags);
+OSSL_DEPRECATEDIN_3_0 void RSA_meth_free(RSA_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 RSA_METHOD *RSA_meth_dup(const RSA_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 const char *RSA_meth_get0_name(const RSA_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 int RSA_meth_set1_name(RSA_METHOD *meth,
+ const char *name);
+OSSL_DEPRECATEDIN_3_0 int RSA_meth_get_flags(const RSA_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 int RSA_meth_set_flags(RSA_METHOD *meth, int flags);
+OSSL_DEPRECATEDIN_3_0 void *RSA_meth_get0_app_data(const RSA_METHOD *meth);
+OSSL_DEPRECATEDIN_3_0 int RSA_meth_set0_app_data(RSA_METHOD *meth,
+ void *app_data);
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_pub_enc(const RSA_METHOD *meth)) (int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_pub_enc(RSA_METHOD *rsa,
+ int (*pub_enc) (int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa,
+ int padding));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_pub_dec(const RSA_METHOD *meth)) (int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_pub_dec(RSA_METHOD *rsa,
+ int (*pub_dec) (int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa,
+ int padding));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_priv_enc(const RSA_METHOD *meth)) (int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_priv_enc(RSA_METHOD *rsa,
+ int (*priv_enc) (int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa,
+ int padding));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_priv_dec(const RSA_METHOD *meth)) (int flen,
+ const unsigned char *from,
+ unsigned char *to,
+ RSA *rsa, int padding);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_priv_dec(RSA_METHOD *rsa,
+ int (*priv_dec) (int flen, const unsigned char *from,
+ unsigned char *to, RSA *rsa,
+ int padding));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_mod_exp(const RSA_METHOD *meth)) (BIGNUM *r0,
+ const BIGNUM *i,
+ RSA *rsa, BN_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_mod_exp(RSA_METHOD *rsa,
+ int (*mod_exp) (BIGNUM *r0, const BIGNUM *i, RSA *rsa,
+ BN_CTX *ctx));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_bn_mod_exp(const RSA_METHOD *meth)) (BIGNUM *r,
+ const BIGNUM *a,
+ const BIGNUM *p,
+ const BIGNUM *m,
+ BN_CTX *ctx,
+ BN_MONT_CTX *m_ctx);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_bn_mod_exp(RSA_METHOD *rsa,
+ int (*bn_mod_exp) (BIGNUM *r,
+ const BIGNUM *a,
+ const BIGNUM *p,
+ const BIGNUM *m,
+ BN_CTX *ctx,
+ BN_MONT_CTX *m_ctx));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_init(const RSA_METHOD *meth)) (RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_init(RSA_METHOD *rsa, int (*init) (RSA *rsa));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_finish(const RSA_METHOD *meth)) (RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_finish(RSA_METHOD *rsa, int (*finish) (RSA *rsa));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_sign(const RSA_METHOD *meth)) (int type,
+ const unsigned char *m,
+ unsigned int m_length,
+ unsigned char *sigret,
+ unsigned int *siglen,
+ const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_sign(RSA_METHOD *rsa,
+ int (*sign) (int type, const unsigned char *m,
+ unsigned int m_length,
+ unsigned char *sigret, unsigned int *siglen,
+ const RSA *rsa));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_verify(const RSA_METHOD *meth)) (int dtype,
+ const unsigned char *m,
+ unsigned int m_length,
+ const unsigned char *sigbuf,
+ unsigned int siglen,
+ const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_verify(RSA_METHOD *rsa,
+ int (*verify) (int dtype, const unsigned char *m,
+ unsigned int m_length,
+ const unsigned char *sigbuf,
+ unsigned int siglen, const RSA *rsa));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_keygen(const RSA_METHOD *meth)) (RSA *rsa, int bits,
+ BIGNUM *e, BN_GENCB *cb);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_keygen(RSA_METHOD *rsa,
+ int (*keygen) (RSA *rsa, int bits, BIGNUM *e,
+ BN_GENCB *cb));
+OSSL_DEPRECATEDIN_3_0
+int (*RSA_meth_get_multi_prime_keygen(const RSA_METHOD *meth)) (RSA *rsa,
+ int bits,
+ int primes,
+ BIGNUM *e,
+ BN_GENCB *cb);
+OSSL_DEPRECATEDIN_3_0
+int RSA_meth_set_multi_prime_keygen(RSA_METHOD *meth,
+ int (*keygen) (RSA *rsa, int bits,
+ int primes, BIGNUM *e,
+ BN_GENCB *cb));
+#endif /* !OPENSSL_NO_DEPRECATED_3_0 */
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/rsaerr.h b/include/openssl/rsaerr.h
new file mode 100644
index 00000000..c58463c7
--- /dev/null
+++ b/include/openssl/rsaerr.h
@@ -0,0 +1,107 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_RSAERR_H
+# define OPENSSL_RSAERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * RSA reason codes.
+ */
+# define RSA_R_ALGORITHM_MISMATCH 100
+# define RSA_R_BAD_E_VALUE 101
+# define RSA_R_BAD_FIXED_HEADER_DECRYPT 102
+# define RSA_R_BAD_PAD_BYTE_COUNT 103
+# define RSA_R_BAD_SIGNATURE 104
+# define RSA_R_BLOCK_TYPE_IS_NOT_01 106
+# define RSA_R_BLOCK_TYPE_IS_NOT_02 107
+# define RSA_R_DATA_GREATER_THAN_MOD_LEN 108
+# define RSA_R_DATA_TOO_LARGE 109
+# define RSA_R_DATA_TOO_LARGE_FOR_KEY_SIZE 110
+# define RSA_R_DATA_TOO_LARGE_FOR_MODULUS 132
+# define RSA_R_DATA_TOO_SMALL 111
+# define RSA_R_DATA_TOO_SMALL_FOR_KEY_SIZE 122
+# define RSA_R_DIGEST_DOES_NOT_MATCH 158
+# define RSA_R_DIGEST_NOT_ALLOWED 145
+# define RSA_R_DIGEST_TOO_BIG_FOR_RSA_KEY 112
+# define RSA_R_DMP1_NOT_CONGRUENT_TO_D 124
+# define RSA_R_DMQ1_NOT_CONGRUENT_TO_D 125
+# define RSA_R_D_E_NOT_CONGRUENT_TO_1 123
+# define RSA_R_FIRST_OCTET_INVALID 133
+# define RSA_R_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE 144
+# define RSA_R_INVALID_DIGEST 157
+# define RSA_R_INVALID_DIGEST_LENGTH 143
+# define RSA_R_INVALID_HEADER 137
+# define RSA_R_INVALID_KEYPAIR 171
+# define RSA_R_INVALID_KEY_LENGTH 173
+# define RSA_R_INVALID_LABEL 160
+# define RSA_R_INVALID_LENGTH 181
+# define RSA_R_INVALID_MESSAGE_LENGTH 131
+# define RSA_R_INVALID_MGF1_MD 156
+# define RSA_R_INVALID_MODULUS 174
+# define RSA_R_INVALID_MULTI_PRIME_KEY 167
+# define RSA_R_INVALID_OAEP_PARAMETERS 161
+# define RSA_R_INVALID_PADDING 138
+# define RSA_R_INVALID_PADDING_MODE 141
+# define RSA_R_INVALID_PSS_PARAMETERS 149
+# define RSA_R_INVALID_PSS_SALTLEN 146
+# define RSA_R_INVALID_REQUEST 175
+# define RSA_R_INVALID_SALT_LENGTH 150
+# define RSA_R_INVALID_STRENGTH 176
+# define RSA_R_INVALID_TRAILER 139
+# define RSA_R_INVALID_X931_DIGEST 142
+# define RSA_R_IQMP_NOT_INVERSE_OF_Q 126
+# define RSA_R_KEY_PRIME_NUM_INVALID 165
+# define RSA_R_KEY_SIZE_TOO_SMALL 120
+# define RSA_R_LAST_OCTET_INVALID 134
+# define RSA_R_MGF1_DIGEST_NOT_ALLOWED 152
+# define RSA_R_MISSING_PRIVATE_KEY 179
+# define RSA_R_MODULUS_TOO_LARGE 105
+# define RSA_R_MP_COEFFICIENT_NOT_INVERSE_OF_R 168
+# define RSA_R_MP_EXPONENT_NOT_CONGRUENT_TO_D 169
+# define RSA_R_MP_R_NOT_PRIME 170
+# define RSA_R_NO_PUBLIC_EXPONENT 140
+# define RSA_R_NULL_BEFORE_BLOCK_MISSING 113
+# define RSA_R_N_DOES_NOT_EQUAL_PRODUCT_OF_PRIMES 172
+# define RSA_R_N_DOES_NOT_EQUAL_P_Q 127
+# define RSA_R_OAEP_DECODING_ERROR 121
+# define RSA_R_OPERATION_NOT_SUPPORTED_FOR_THIS_KEYTYPE 148
+# define RSA_R_PADDING_CHECK_FAILED 114
+# define RSA_R_PAIRWISE_TEST_FAILURE 177
+# define RSA_R_PKCS_DECODING_ERROR 159
+# define RSA_R_PSS_SALTLEN_TOO_SMALL 164
+# define RSA_R_PUB_EXPONENT_OUT_OF_RANGE 178
+# define RSA_R_P_NOT_PRIME 128
+# define RSA_R_Q_NOT_PRIME 129
+# define RSA_R_RANDOMNESS_SOURCE_STRENGTH_INSUFFICIENT 180
+# define RSA_R_RSA_OPERATIONS_NOT_SUPPORTED 130
+# define RSA_R_SLEN_CHECK_FAILED 136
+# define RSA_R_SLEN_RECOVERY_FAILED 135
+# define RSA_R_SSLV3_ROLLBACK_ATTACK 115
+# define RSA_R_THE_ASN1_OBJECT_IDENTIFIER_IS_NOT_KNOWN_FOR_THIS_MD 116
+# define RSA_R_UNKNOWN_ALGORITHM_TYPE 117
+# define RSA_R_UNKNOWN_DIGEST 166
+# define RSA_R_UNKNOWN_MASK_DIGEST 151
+# define RSA_R_UNKNOWN_PADDING_TYPE 118
+# define RSA_R_UNSUPPORTED_ENCRYPTION_TYPE 162
+# define RSA_R_UNSUPPORTED_LABEL_SOURCE 163
+# define RSA_R_UNSUPPORTED_MASK_ALGORITHM 153
+# define RSA_R_UNSUPPORTED_MASK_PARAMETER 154
+# define RSA_R_UNSUPPORTED_SIGNATURE_TYPE 155
+# define RSA_R_VALUE_MISSING 147
+# define RSA_R_WRONG_SIGNATURE_LENGTH 119
+
+#endif
diff --git a/include/openssl/safestack.h b/include/openssl/safestack.h
new file mode 100644
index 00000000..159ccf2a
--- /dev/null
+++ b/include/openssl/safestack.h
@@ -0,0 +1,297 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\safestack.h.in
+ *
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_SAFESTACK_H
+# define OPENSSL_SAFESTACK_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SAFESTACK_H
+# endif
+
+# include <openssl/stack.h>
+# include <openssl/e_os2.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define STACK_OF(type) struct stack_st_##type
+
+/* Helper macro for internal use */
+# define SKM_DEFINE_STACK_OF_INTERNAL(t1, t2, t3) \
+ STACK_OF(t1); \
+ typedef int (*sk_##t1##_compfunc)(const t3 * const *a, const t3 *const *b); \
+ typedef void (*sk_##t1##_freefunc)(t3 *a); \
+ typedef t3 * (*sk_##t1##_copyfunc)(const t3 *a); \
+ static ossl_unused ossl_inline t2 *ossl_check_##t1##_type(t2 *ptr) \
+ { \
+ return ptr; \
+ } \
+ static ossl_unused ossl_inline const OPENSSL_STACK *ossl_check_const_##t1##_sk_type(const STACK_OF(t1) *sk) \
+ { \
+ return (const OPENSSL_STACK *)sk; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_STACK *ossl_check_##t1##_sk_type(STACK_OF(t1) *sk) \
+ { \
+ return (OPENSSL_STACK *)sk; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_sk_compfunc ossl_check_##t1##_compfunc_type(sk_##t1##_compfunc cmp) \
+ { \
+ return (OPENSSL_sk_compfunc)cmp; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_sk_copyfunc ossl_check_##t1##_copyfunc_type(sk_##t1##_copyfunc cpy) \
+ { \
+ return (OPENSSL_sk_copyfunc)cpy; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_sk_freefunc ossl_check_##t1##_freefunc_type(sk_##t1##_freefunc fr) \
+ { \
+ return (OPENSSL_sk_freefunc)fr; \
+ }
+
+# define SKM_DEFINE_STACK_OF(t1, t2, t3) \
+ STACK_OF(t1); \
+ typedef int (*sk_##t1##_compfunc)(const t3 * const *a, const t3 *const *b); \
+ typedef void (*sk_##t1##_freefunc)(t3 *a); \
+ typedef t3 * (*sk_##t1##_copyfunc)(const t3 *a); \
+ static ossl_unused ossl_inline int sk_##t1##_num(const STACK_OF(t1) *sk) \
+ { \
+ return OPENSSL_sk_num((const OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_value(const STACK_OF(t1) *sk, int idx) \
+ { \
+ return (t2 *)OPENSSL_sk_value((const OPENSSL_STACK *)sk, idx); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_new(sk_##t1##_compfunc compare) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_new((OPENSSL_sk_compfunc)compare); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_new_null(void) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_new_null(); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_new_reserve(sk_##t1##_compfunc compare, int n) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_new_reserve((OPENSSL_sk_compfunc)compare, n); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_reserve(STACK_OF(t1) *sk, int n) \
+ { \
+ return OPENSSL_sk_reserve((OPENSSL_STACK *)sk, n); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_free(STACK_OF(t1) *sk) \
+ { \
+ OPENSSL_sk_free((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_zero(STACK_OF(t1) *sk) \
+ { \
+ OPENSSL_sk_zero((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_delete(STACK_OF(t1) *sk, int i) \
+ { \
+ return (t2 *)OPENSSL_sk_delete((OPENSSL_STACK *)sk, i); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_delete_ptr(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return (t2 *)OPENSSL_sk_delete_ptr((OPENSSL_STACK *)sk, \
+ (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_push(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_push((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_unshift(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_unshift((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_pop(STACK_OF(t1) *sk) \
+ { \
+ return (t2 *)OPENSSL_sk_pop((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_shift(STACK_OF(t1) *sk) \
+ { \
+ return (t2 *)OPENSSL_sk_shift((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_pop_free(STACK_OF(t1) *sk, sk_##t1##_freefunc freefunc) \
+ { \
+ OPENSSL_sk_pop_free((OPENSSL_STACK *)sk, (OPENSSL_sk_freefunc)freefunc); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_insert(STACK_OF(t1) *sk, t2 *ptr, int idx) \
+ { \
+ return OPENSSL_sk_insert((OPENSSL_STACK *)sk, (const void *)ptr, idx); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_set(STACK_OF(t1) *sk, int idx, t2 *ptr) \
+ { \
+ return (t2 *)OPENSSL_sk_set((OPENSSL_STACK *)sk, idx, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_find(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_find((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_find_ex(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_find_ex((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_find_all(STACK_OF(t1) *sk, t2 *ptr, int *pnum) \
+ { \
+ return OPENSSL_sk_find_all((OPENSSL_STACK *)sk, (const void *)ptr, pnum); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_sort(STACK_OF(t1) *sk) \
+ { \
+ OPENSSL_sk_sort((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_is_sorted(const STACK_OF(t1) *sk) \
+ { \
+ return OPENSSL_sk_is_sorted((const OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) * sk_##t1##_dup(const STACK_OF(t1) *sk) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_dup((const OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_deep_copy(const STACK_OF(t1) *sk, \
+ sk_##t1##_copyfunc copyfunc, \
+ sk_##t1##_freefunc freefunc) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_deep_copy((const OPENSSL_STACK *)sk, \
+ (OPENSSL_sk_copyfunc)copyfunc, \
+ (OPENSSL_sk_freefunc)freefunc); \
+ } \
+ static ossl_unused ossl_inline sk_##t1##_compfunc sk_##t1##_set_cmp_func(STACK_OF(t1) *sk, sk_##t1##_compfunc compare) \
+ { \
+ return (sk_##t1##_compfunc)OPENSSL_sk_set_cmp_func((OPENSSL_STACK *)sk, (OPENSSL_sk_compfunc)compare); \
+ }
+
+# define DEFINE_STACK_OF(t) SKM_DEFINE_STACK_OF(t, t, t)
+# define DEFINE_STACK_OF_CONST(t) SKM_DEFINE_STACK_OF(t, const t, t)
+# define DEFINE_SPECIAL_STACK_OF(t1, t2) SKM_DEFINE_STACK_OF(t1, t2, t2)
+# define DEFINE_SPECIAL_STACK_OF_CONST(t1, t2) \
+ SKM_DEFINE_STACK_OF(t1, const t2, t2)
+
+/*-
+ * Strings are special: normally an lhash entry will point to a single
+ * (somewhat) mutable object. In the case of strings:
+ *
+ * a) Instead of a single char, there is an array of chars, NUL-terminated.
+ * b) The string may have be immutable.
+ *
+ * So, they need their own declarations. Especially important for
+ * type-checking tools, such as Deputy.
+ *
+ * In practice, however, it appears to be hard to have a const
+ * string. For now, I'm settling for dealing with the fact it is a
+ * string at all.
+ */
+typedef char *OPENSSL_STRING;
+typedef const char *OPENSSL_CSTRING;
+
+/*-
+ * Confusingly, LHASH_OF(STRING) deals with char ** throughout, but
+ * STACK_OF(STRING) is really more like STACK_OF(char), only, as mentioned
+ * above, instead of a single char each entry is a NUL-terminated array of
+ * chars. So, we have to implement STRING specially for STACK_OF. This is
+ * dealt with in the autogenerated macros below.
+ */
+SKM_DEFINE_STACK_OF_INTERNAL(OPENSSL_STRING, char, char)
+#define sk_OPENSSL_STRING_num(sk) OPENSSL_sk_num(ossl_check_const_OPENSSL_STRING_sk_type(sk))
+#define sk_OPENSSL_STRING_value(sk, idx) ((char *)OPENSSL_sk_value(ossl_check_const_OPENSSL_STRING_sk_type(sk), (idx)))
+#define sk_OPENSSL_STRING_new(cmp) ((STACK_OF(OPENSSL_STRING) *)OPENSSL_sk_new(ossl_check_OPENSSL_STRING_compfunc_type(cmp)))
+#define sk_OPENSSL_STRING_new_null() ((STACK_OF(OPENSSL_STRING) *)OPENSSL_sk_new_null())
+#define sk_OPENSSL_STRING_new_reserve(cmp, n) ((STACK_OF(OPENSSL_STRING) *)OPENSSL_sk_new_reserve(ossl_check_OPENSSL_STRING_compfunc_type(cmp), (n)))
+#define sk_OPENSSL_STRING_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OPENSSL_STRING_sk_type(sk), (n))
+#define sk_OPENSSL_STRING_free(sk) OPENSSL_sk_free(ossl_check_OPENSSL_STRING_sk_type(sk))
+#define sk_OPENSSL_STRING_zero(sk) OPENSSL_sk_zero(ossl_check_OPENSSL_STRING_sk_type(sk))
+#define sk_OPENSSL_STRING_delete(sk, i) ((char *)OPENSSL_sk_delete(ossl_check_OPENSSL_STRING_sk_type(sk), (i)))
+#define sk_OPENSSL_STRING_delete_ptr(sk, ptr) ((char *)OPENSSL_sk_delete_ptr(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_type(ptr)))
+#define sk_OPENSSL_STRING_push(sk, ptr) OPENSSL_sk_push(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_type(ptr))
+#define sk_OPENSSL_STRING_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_type(ptr))
+#define sk_OPENSSL_STRING_pop(sk) ((char *)OPENSSL_sk_pop(ossl_check_OPENSSL_STRING_sk_type(sk)))
+#define sk_OPENSSL_STRING_shift(sk) ((char *)OPENSSL_sk_shift(ossl_check_OPENSSL_STRING_sk_type(sk)))
+#define sk_OPENSSL_STRING_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OPENSSL_STRING_sk_type(sk),ossl_check_OPENSSL_STRING_freefunc_type(freefunc))
+#define sk_OPENSSL_STRING_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_type(ptr), (idx))
+#define sk_OPENSSL_STRING_set(sk, idx, ptr) ((char *)OPENSSL_sk_set(ossl_check_OPENSSL_STRING_sk_type(sk), (idx), ossl_check_OPENSSL_STRING_type(ptr)))
+#define sk_OPENSSL_STRING_find(sk, ptr) OPENSSL_sk_find(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_type(ptr))
+#define sk_OPENSSL_STRING_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_type(ptr))
+#define sk_OPENSSL_STRING_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_type(ptr), pnum)
+#define sk_OPENSSL_STRING_sort(sk) OPENSSL_sk_sort(ossl_check_OPENSSL_STRING_sk_type(sk))
+#define sk_OPENSSL_STRING_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OPENSSL_STRING_sk_type(sk))
+#define sk_OPENSSL_STRING_dup(sk) ((STACK_OF(OPENSSL_STRING) *)OPENSSL_sk_dup(ossl_check_const_OPENSSL_STRING_sk_type(sk)))
+#define sk_OPENSSL_STRING_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OPENSSL_STRING) *)OPENSSL_sk_deep_copy(ossl_check_const_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_copyfunc_type(copyfunc), ossl_check_OPENSSL_STRING_freefunc_type(freefunc)))
+#define sk_OPENSSL_STRING_set_cmp_func(sk, cmp) ((sk_OPENSSL_STRING_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OPENSSL_STRING_sk_type(sk), ossl_check_OPENSSL_STRING_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(OPENSSL_CSTRING, const char, char)
+#define sk_OPENSSL_CSTRING_num(sk) OPENSSL_sk_num(ossl_check_const_OPENSSL_CSTRING_sk_type(sk))
+#define sk_OPENSSL_CSTRING_value(sk, idx) ((const char *)OPENSSL_sk_value(ossl_check_const_OPENSSL_CSTRING_sk_type(sk), (idx)))
+#define sk_OPENSSL_CSTRING_new(cmp) ((STACK_OF(OPENSSL_CSTRING) *)OPENSSL_sk_new(ossl_check_OPENSSL_CSTRING_compfunc_type(cmp)))
+#define sk_OPENSSL_CSTRING_new_null() ((STACK_OF(OPENSSL_CSTRING) *)OPENSSL_sk_new_null())
+#define sk_OPENSSL_CSTRING_new_reserve(cmp, n) ((STACK_OF(OPENSSL_CSTRING) *)OPENSSL_sk_new_reserve(ossl_check_OPENSSL_CSTRING_compfunc_type(cmp), (n)))
+#define sk_OPENSSL_CSTRING_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OPENSSL_CSTRING_sk_type(sk), (n))
+#define sk_OPENSSL_CSTRING_free(sk) OPENSSL_sk_free(ossl_check_OPENSSL_CSTRING_sk_type(sk))
+#define sk_OPENSSL_CSTRING_zero(sk) OPENSSL_sk_zero(ossl_check_OPENSSL_CSTRING_sk_type(sk))
+#define sk_OPENSSL_CSTRING_delete(sk, i) ((const char *)OPENSSL_sk_delete(ossl_check_OPENSSL_CSTRING_sk_type(sk), (i)))
+#define sk_OPENSSL_CSTRING_delete_ptr(sk, ptr) ((const char *)OPENSSL_sk_delete_ptr(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_type(ptr)))
+#define sk_OPENSSL_CSTRING_push(sk, ptr) OPENSSL_sk_push(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_type(ptr))
+#define sk_OPENSSL_CSTRING_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_type(ptr))
+#define sk_OPENSSL_CSTRING_pop(sk) ((const char *)OPENSSL_sk_pop(ossl_check_OPENSSL_CSTRING_sk_type(sk)))
+#define sk_OPENSSL_CSTRING_shift(sk) ((const char *)OPENSSL_sk_shift(ossl_check_OPENSSL_CSTRING_sk_type(sk)))
+#define sk_OPENSSL_CSTRING_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OPENSSL_CSTRING_sk_type(sk),ossl_check_OPENSSL_CSTRING_freefunc_type(freefunc))
+#define sk_OPENSSL_CSTRING_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_type(ptr), (idx))
+#define sk_OPENSSL_CSTRING_set(sk, idx, ptr) ((const char *)OPENSSL_sk_set(ossl_check_OPENSSL_CSTRING_sk_type(sk), (idx), ossl_check_OPENSSL_CSTRING_type(ptr)))
+#define sk_OPENSSL_CSTRING_find(sk, ptr) OPENSSL_sk_find(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_type(ptr))
+#define sk_OPENSSL_CSTRING_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_type(ptr))
+#define sk_OPENSSL_CSTRING_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_type(ptr), pnum)
+#define sk_OPENSSL_CSTRING_sort(sk) OPENSSL_sk_sort(ossl_check_OPENSSL_CSTRING_sk_type(sk))
+#define sk_OPENSSL_CSTRING_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OPENSSL_CSTRING_sk_type(sk))
+#define sk_OPENSSL_CSTRING_dup(sk) ((STACK_OF(OPENSSL_CSTRING) *)OPENSSL_sk_dup(ossl_check_const_OPENSSL_CSTRING_sk_type(sk)))
+#define sk_OPENSSL_CSTRING_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OPENSSL_CSTRING) *)OPENSSL_sk_deep_copy(ossl_check_const_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_copyfunc_type(copyfunc), ossl_check_OPENSSL_CSTRING_freefunc_type(freefunc)))
+#define sk_OPENSSL_CSTRING_set_cmp_func(sk, cmp) ((sk_OPENSSL_CSTRING_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OPENSSL_CSTRING_sk_type(sk), ossl_check_OPENSSL_CSTRING_compfunc_type(cmp)))
+
+
+#if !defined(OPENSSL_NO_DEPRECATED_3_0)
+/*
+ * This is not used by OpenSSL. A block of bytes, NOT nul-terminated.
+ * These should also be distinguished from "normal" stacks.
+ */
+typedef void *OPENSSL_BLOCK;
+SKM_DEFINE_STACK_OF_INTERNAL(OPENSSL_BLOCK, void, void)
+#define sk_OPENSSL_BLOCK_num(sk) OPENSSL_sk_num(ossl_check_const_OPENSSL_BLOCK_sk_type(sk))
+#define sk_OPENSSL_BLOCK_value(sk, idx) ((void *)OPENSSL_sk_value(ossl_check_const_OPENSSL_BLOCK_sk_type(sk), (idx)))
+#define sk_OPENSSL_BLOCK_new(cmp) ((STACK_OF(OPENSSL_BLOCK) *)OPENSSL_sk_new(ossl_check_OPENSSL_BLOCK_compfunc_type(cmp)))
+#define sk_OPENSSL_BLOCK_new_null() ((STACK_OF(OPENSSL_BLOCK) *)OPENSSL_sk_new_null())
+#define sk_OPENSSL_BLOCK_new_reserve(cmp, n) ((STACK_OF(OPENSSL_BLOCK) *)OPENSSL_sk_new_reserve(ossl_check_OPENSSL_BLOCK_compfunc_type(cmp), (n)))
+#define sk_OPENSSL_BLOCK_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_OPENSSL_BLOCK_sk_type(sk), (n))
+#define sk_OPENSSL_BLOCK_free(sk) OPENSSL_sk_free(ossl_check_OPENSSL_BLOCK_sk_type(sk))
+#define sk_OPENSSL_BLOCK_zero(sk) OPENSSL_sk_zero(ossl_check_OPENSSL_BLOCK_sk_type(sk))
+#define sk_OPENSSL_BLOCK_delete(sk, i) ((void *)OPENSSL_sk_delete(ossl_check_OPENSSL_BLOCK_sk_type(sk), (i)))
+#define sk_OPENSSL_BLOCK_delete_ptr(sk, ptr) ((void *)OPENSSL_sk_delete_ptr(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_type(ptr)))
+#define sk_OPENSSL_BLOCK_push(sk, ptr) OPENSSL_sk_push(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_type(ptr))
+#define sk_OPENSSL_BLOCK_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_type(ptr))
+#define sk_OPENSSL_BLOCK_pop(sk) ((void *)OPENSSL_sk_pop(ossl_check_OPENSSL_BLOCK_sk_type(sk)))
+#define sk_OPENSSL_BLOCK_shift(sk) ((void *)OPENSSL_sk_shift(ossl_check_OPENSSL_BLOCK_sk_type(sk)))
+#define sk_OPENSSL_BLOCK_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_OPENSSL_BLOCK_sk_type(sk),ossl_check_OPENSSL_BLOCK_freefunc_type(freefunc))
+#define sk_OPENSSL_BLOCK_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_type(ptr), (idx))
+#define sk_OPENSSL_BLOCK_set(sk, idx, ptr) ((void *)OPENSSL_sk_set(ossl_check_OPENSSL_BLOCK_sk_type(sk), (idx), ossl_check_OPENSSL_BLOCK_type(ptr)))
+#define sk_OPENSSL_BLOCK_find(sk, ptr) OPENSSL_sk_find(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_type(ptr))
+#define sk_OPENSSL_BLOCK_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_type(ptr))
+#define sk_OPENSSL_BLOCK_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_type(ptr), pnum)
+#define sk_OPENSSL_BLOCK_sort(sk) OPENSSL_sk_sort(ossl_check_OPENSSL_BLOCK_sk_type(sk))
+#define sk_OPENSSL_BLOCK_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_OPENSSL_BLOCK_sk_type(sk))
+#define sk_OPENSSL_BLOCK_dup(sk) ((STACK_OF(OPENSSL_BLOCK) *)OPENSSL_sk_dup(ossl_check_const_OPENSSL_BLOCK_sk_type(sk)))
+#define sk_OPENSSL_BLOCK_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(OPENSSL_BLOCK) *)OPENSSL_sk_deep_copy(ossl_check_const_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_copyfunc_type(copyfunc), ossl_check_OPENSSL_BLOCK_freefunc_type(freefunc)))
+#define sk_OPENSSL_BLOCK_set_cmp_func(sk, cmp) ((sk_OPENSSL_BLOCK_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_OPENSSL_BLOCK_sk_type(sk), ossl_check_OPENSSL_BLOCK_compfunc_type(cmp)))
+
+#endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/safestack.h.in b/include/openssl/safestack.h.in
new file mode 100644
index 00000000..6b366079
--- /dev/null
+++ b/include/openssl/safestack.h.in
@@ -0,0 +1,227 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_string_macros
+ generate_stack_const_string_macros
+ generate_stack_block_macros);
+-}
+
+#ifndef OPENSSL_SAFESTACK_H
+# define OPENSSL_SAFESTACK_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SAFESTACK_H
+# endif
+
+# include <openssl/stack.h>
+# include <openssl/e_os2.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define STACK_OF(type) struct stack_st_##type
+
+/* Helper macro for internal use */
+# define SKM_DEFINE_STACK_OF_INTERNAL(t1, t2, t3) \
+ STACK_OF(t1); \
+ typedef int (*sk_##t1##_compfunc)(const t3 * const *a, const t3 *const *b); \
+ typedef void (*sk_##t1##_freefunc)(t3 *a); \
+ typedef t3 * (*sk_##t1##_copyfunc)(const t3 *a); \
+ static ossl_unused ossl_inline t2 *ossl_check_##t1##_type(t2 *ptr) \
+ { \
+ return ptr; \
+ } \
+ static ossl_unused ossl_inline const OPENSSL_STACK *ossl_check_const_##t1##_sk_type(const STACK_OF(t1) *sk) \
+ { \
+ return (const OPENSSL_STACK *)sk; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_STACK *ossl_check_##t1##_sk_type(STACK_OF(t1) *sk) \
+ { \
+ return (OPENSSL_STACK *)sk; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_sk_compfunc ossl_check_##t1##_compfunc_type(sk_##t1##_compfunc cmp) \
+ { \
+ return (OPENSSL_sk_compfunc)cmp; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_sk_copyfunc ossl_check_##t1##_copyfunc_type(sk_##t1##_copyfunc cpy) \
+ { \
+ return (OPENSSL_sk_copyfunc)cpy; \
+ } \
+ static ossl_unused ossl_inline OPENSSL_sk_freefunc ossl_check_##t1##_freefunc_type(sk_##t1##_freefunc fr) \
+ { \
+ return (OPENSSL_sk_freefunc)fr; \
+ }
+
+# define SKM_DEFINE_STACK_OF(t1, t2, t3) \
+ STACK_OF(t1); \
+ typedef int (*sk_##t1##_compfunc)(const t3 * const *a, const t3 *const *b); \
+ typedef void (*sk_##t1##_freefunc)(t3 *a); \
+ typedef t3 * (*sk_##t1##_copyfunc)(const t3 *a); \
+ static ossl_unused ossl_inline int sk_##t1##_num(const STACK_OF(t1) *sk) \
+ { \
+ return OPENSSL_sk_num((const OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_value(const STACK_OF(t1) *sk, int idx) \
+ { \
+ return (t2 *)OPENSSL_sk_value((const OPENSSL_STACK *)sk, idx); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_new(sk_##t1##_compfunc compare) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_new((OPENSSL_sk_compfunc)compare); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_new_null(void) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_new_null(); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_new_reserve(sk_##t1##_compfunc compare, int n) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_new_reserve((OPENSSL_sk_compfunc)compare, n); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_reserve(STACK_OF(t1) *sk, int n) \
+ { \
+ return OPENSSL_sk_reserve((OPENSSL_STACK *)sk, n); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_free(STACK_OF(t1) *sk) \
+ { \
+ OPENSSL_sk_free((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_zero(STACK_OF(t1) *sk) \
+ { \
+ OPENSSL_sk_zero((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_delete(STACK_OF(t1) *sk, int i) \
+ { \
+ return (t2 *)OPENSSL_sk_delete((OPENSSL_STACK *)sk, i); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_delete_ptr(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return (t2 *)OPENSSL_sk_delete_ptr((OPENSSL_STACK *)sk, \
+ (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_push(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_push((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_unshift(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_unshift((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_pop(STACK_OF(t1) *sk) \
+ { \
+ return (t2 *)OPENSSL_sk_pop((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_shift(STACK_OF(t1) *sk) \
+ { \
+ return (t2 *)OPENSSL_sk_shift((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_pop_free(STACK_OF(t1) *sk, sk_##t1##_freefunc freefunc) \
+ { \
+ OPENSSL_sk_pop_free((OPENSSL_STACK *)sk, (OPENSSL_sk_freefunc)freefunc); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_insert(STACK_OF(t1) *sk, t2 *ptr, int idx) \
+ { \
+ return OPENSSL_sk_insert((OPENSSL_STACK *)sk, (const void *)ptr, idx); \
+ } \
+ static ossl_unused ossl_inline t2 *sk_##t1##_set(STACK_OF(t1) *sk, int idx, t2 *ptr) \
+ { \
+ return (t2 *)OPENSSL_sk_set((OPENSSL_STACK *)sk, idx, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_find(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_find((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_find_ex(STACK_OF(t1) *sk, t2 *ptr) \
+ { \
+ return OPENSSL_sk_find_ex((OPENSSL_STACK *)sk, (const void *)ptr); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_find_all(STACK_OF(t1) *sk, t2 *ptr, int *pnum) \
+ { \
+ return OPENSSL_sk_find_all((OPENSSL_STACK *)sk, (const void *)ptr, pnum); \
+ } \
+ static ossl_unused ossl_inline void sk_##t1##_sort(STACK_OF(t1) *sk) \
+ { \
+ OPENSSL_sk_sort((OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline int sk_##t1##_is_sorted(const STACK_OF(t1) *sk) \
+ { \
+ return OPENSSL_sk_is_sorted((const OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) * sk_##t1##_dup(const STACK_OF(t1) *sk) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_dup((const OPENSSL_STACK *)sk); \
+ } \
+ static ossl_unused ossl_inline STACK_OF(t1) *sk_##t1##_deep_copy(const STACK_OF(t1) *sk, \
+ sk_##t1##_copyfunc copyfunc, \
+ sk_##t1##_freefunc freefunc) \
+ { \
+ return (STACK_OF(t1) *)OPENSSL_sk_deep_copy((const OPENSSL_STACK *)sk, \
+ (OPENSSL_sk_copyfunc)copyfunc, \
+ (OPENSSL_sk_freefunc)freefunc); \
+ } \
+ static ossl_unused ossl_inline sk_##t1##_compfunc sk_##t1##_set_cmp_func(STACK_OF(t1) *sk, sk_##t1##_compfunc compare) \
+ { \
+ return (sk_##t1##_compfunc)OPENSSL_sk_set_cmp_func((OPENSSL_STACK *)sk, (OPENSSL_sk_compfunc)compare); \
+ }
+
+# define DEFINE_STACK_OF(t) SKM_DEFINE_STACK_OF(t, t, t)
+# define DEFINE_STACK_OF_CONST(t) SKM_DEFINE_STACK_OF(t, const t, t)
+# define DEFINE_SPECIAL_STACK_OF(t1, t2) SKM_DEFINE_STACK_OF(t1, t2, t2)
+# define DEFINE_SPECIAL_STACK_OF_CONST(t1, t2) \
+ SKM_DEFINE_STACK_OF(t1, const t2, t2)
+
+/*-
+ * Strings are special: normally an lhash entry will point to a single
+ * (somewhat) mutable object. In the case of strings:
+ *
+ * a) Instead of a single char, there is an array of chars, NUL-terminated.
+ * b) The string may have be immutable.
+ *
+ * So, they need their own declarations. Especially important for
+ * type-checking tools, such as Deputy.
+ *
+ * In practice, however, it appears to be hard to have a const
+ * string. For now, I'm settling for dealing with the fact it is a
+ * string at all.
+ */
+typedef char *OPENSSL_STRING;
+typedef const char *OPENSSL_CSTRING;
+
+/*-
+ * Confusingly, LHASH_OF(STRING) deals with char ** throughout, but
+ * STACK_OF(STRING) is really more like STACK_OF(char), only, as mentioned
+ * above, instead of a single char each entry is a NUL-terminated array of
+ * chars. So, we have to implement STRING specially for STACK_OF. This is
+ * dealt with in the autogenerated macros below.
+ */
+{-
+ generate_stack_string_macros()
+ .generate_stack_const_string_macros();
+-}
+
+#if !defined(OPENSSL_NO_DEPRECATED_3_0)
+/*
+ * This is not used by OpenSSL. A block of bytes, NOT nul-terminated.
+ * These should also be distinguished from "normal" stacks.
+ */
+typedef void *OPENSSL_BLOCK;
+{-
+ generate_stack_block_macros();
+-}
+#endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/seed.h b/include/openssl/seed.h
new file mode 100644
index 00000000..edb218ae
--- /dev/null
+++ b/include/openssl/seed.h
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2007-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * Copyright (c) 2007 KISA(Korea Information Security Agency). All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Neither the name of 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 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 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 OPENSSL_SEED_H
+# define OPENSSL_SEED_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SEED_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_SEED
+# include <openssl/e_os2.h>
+# include <openssl/crypto.h>
+# include <sys/types.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define SEED_BLOCK_SIZE 16
+# define SEED_KEY_LENGTH 16
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* look whether we need 'long' to get 32 bits */
+# ifdef AES_LONG
+# ifndef SEED_LONG
+# define SEED_LONG 1
+# endif
+# endif
+
+
+typedef struct seed_key_st {
+# ifdef SEED_LONG
+ unsigned long data[32];
+# else
+ unsigned int data[32];
+# endif
+} SEED_KEY_SCHEDULE;
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+void SEED_set_key(const unsigned char rawkey[SEED_KEY_LENGTH],
+ SEED_KEY_SCHEDULE *ks);
+OSSL_DEPRECATEDIN_3_0
+void SEED_encrypt(const unsigned char s[SEED_BLOCK_SIZE],
+ unsigned char d[SEED_BLOCK_SIZE],
+ const SEED_KEY_SCHEDULE *ks);
+OSSL_DEPRECATEDIN_3_0
+void SEED_decrypt(const unsigned char s[SEED_BLOCK_SIZE],
+ unsigned char d[SEED_BLOCK_SIZE],
+ const SEED_KEY_SCHEDULE *ks);
+OSSL_DEPRECATEDIN_3_0
+void SEED_ecb_encrypt(const unsigned char *in,
+ unsigned char *out,
+ const SEED_KEY_SCHEDULE *ks, int enc);
+OSSL_DEPRECATEDIN_3_0
+void SEED_cbc_encrypt(const unsigned char *in, unsigned char *out, size_t len,
+ const SEED_KEY_SCHEDULE *ks,
+ unsigned char ivec[SEED_BLOCK_SIZE],
+ int enc);
+OSSL_DEPRECATEDIN_3_0
+void SEED_cfb128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const SEED_KEY_SCHEDULE *ks,
+ unsigned char ivec[SEED_BLOCK_SIZE],
+ int *num, int enc);
+OSSL_DEPRECATEDIN_3_0
+void SEED_ofb128_encrypt(const unsigned char *in, unsigned char *out,
+ size_t len, const SEED_KEY_SCHEDULE *ks,
+ unsigned char ivec[SEED_BLOCK_SIZE],
+ int *num);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/self_test.h b/include/openssl/self_test.h
new file mode 100644
index 00000000..77c600a0
--- /dev/null
+++ b/include/openssl/self_test.h
@@ -0,0 +1,93 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_SELF_TEST_H
+# define OPENSSL_SELF_TEST_H
+# pragma once
+
+# include <openssl/core.h> /* OSSL_CALLBACK */
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/* The test event phases */
+# define OSSL_SELF_TEST_PHASE_NONE "None"
+# define OSSL_SELF_TEST_PHASE_START "Start"
+# define OSSL_SELF_TEST_PHASE_CORRUPT "Corrupt"
+# define OSSL_SELF_TEST_PHASE_PASS "Pass"
+# define OSSL_SELF_TEST_PHASE_FAIL "Fail"
+
+/* Test event categories */
+# define OSSL_SELF_TEST_TYPE_NONE "None"
+# define OSSL_SELF_TEST_TYPE_MODULE_INTEGRITY "Module_Integrity"
+# define OSSL_SELF_TEST_TYPE_INSTALL_INTEGRITY "Install_Integrity"
+# define OSSL_SELF_TEST_TYPE_CRNG "Continuous_RNG_Test"
+# define OSSL_SELF_TEST_TYPE_PCT "Conditional_PCT"
+# define OSSL_SELF_TEST_TYPE_KAT_CIPHER "KAT_Cipher"
+# define OSSL_SELF_TEST_TYPE_KAT_ASYM_CIPHER "KAT_AsymmetricCipher"
+# define OSSL_SELF_TEST_TYPE_KAT_DIGEST "KAT_Digest"
+# define OSSL_SELF_TEST_TYPE_KAT_SIGNATURE "KAT_Signature"
+# define OSSL_SELF_TEST_TYPE_PCT_SIGNATURE "PCT_Signature"
+# define OSSL_SELF_TEST_TYPE_KAT_KDF "KAT_KDF"
+# define OSSL_SELF_TEST_TYPE_KAT_KA "KAT_KA"
+# define OSSL_SELF_TEST_TYPE_DRBG "DRBG"
+
+/* Test event sub categories */
+# define OSSL_SELF_TEST_DESC_NONE "None"
+# define OSSL_SELF_TEST_DESC_INTEGRITY_HMAC "HMAC"
+# define OSSL_SELF_TEST_DESC_PCT_RSA_PKCS1 "RSA"
+# define OSSL_SELF_TEST_DESC_PCT_ECDSA "ECDSA"
+# define OSSL_SELF_TEST_DESC_PCT_DSA "DSA"
+# define OSSL_SELF_TEST_DESC_CIPHER_AES_GCM "AES_GCM"
+# define OSSL_SELF_TEST_DESC_CIPHER_AES_ECB "AES_ECB_Decrypt"
+# define OSSL_SELF_TEST_DESC_CIPHER_TDES "TDES"
+# define OSSL_SELF_TEST_DESC_ASYM_RSA_ENC "RSA_Encrypt"
+# define OSSL_SELF_TEST_DESC_ASYM_RSA_DEC "RSA_Decrypt"
+# define OSSL_SELF_TEST_DESC_MD_SHA1 "SHA1"
+# define OSSL_SELF_TEST_DESC_MD_SHA2 "SHA2"
+# define OSSL_SELF_TEST_DESC_MD_SHA3 "SHA3"
+# define OSSL_SELF_TEST_DESC_SIGN_DSA "DSA"
+# define OSSL_SELF_TEST_DESC_SIGN_RSA "RSA"
+# define OSSL_SELF_TEST_DESC_SIGN_ECDSA "ECDSA"
+# define OSSL_SELF_TEST_DESC_DRBG_CTR "CTR"
+# define OSSL_SELF_TEST_DESC_DRBG_HASH "HASH"
+# define OSSL_SELF_TEST_DESC_DRBG_HMAC "HMAC"
+# define OSSL_SELF_TEST_DESC_KA_DH "DH"
+# define OSSL_SELF_TEST_DESC_KA_ECDH "ECDH"
+# define OSSL_SELF_TEST_DESC_KDF_HKDF "HKDF"
+# define OSSL_SELF_TEST_DESC_KDF_SSKDF "SSKDF"
+# define OSSL_SELF_TEST_DESC_KDF_X963KDF "X963KDF"
+# define OSSL_SELF_TEST_DESC_KDF_X942KDF "X942KDF"
+# define OSSL_SELF_TEST_DESC_KDF_PBKDF2 "PBKDF2"
+# define OSSL_SELF_TEST_DESC_KDF_SSHKDF "SSHKDF"
+# define OSSL_SELF_TEST_DESC_KDF_TLS12_PRF "TLS12_PRF"
+# define OSSL_SELF_TEST_DESC_KDF_KBKDF "KBKDF"
+# define OSSL_SELF_TEST_DESC_KDF_TLS13_EXTRACT "TLS13_KDF_EXTRACT"
+# define OSSL_SELF_TEST_DESC_KDF_TLS13_EXPAND "TLS13_KDF_EXPAND"
+# define OSSL_SELF_TEST_DESC_RNG "RNG"
+
+# ifdef __cplusplus
+}
+# endif
+
+void OSSL_SELF_TEST_set_callback(OSSL_LIB_CTX *libctx, OSSL_CALLBACK *cb,
+ void *cbarg);
+void OSSL_SELF_TEST_get_callback(OSSL_LIB_CTX *libctx, OSSL_CALLBACK **cb,
+ void **cbarg);
+
+OSSL_SELF_TEST *OSSL_SELF_TEST_new(OSSL_CALLBACK *cb, void *cbarg);
+void OSSL_SELF_TEST_free(OSSL_SELF_TEST *st);
+
+void OSSL_SELF_TEST_onbegin(OSSL_SELF_TEST *st, const char *type,
+ const char *desc);
+int OSSL_SELF_TEST_oncorrupt_byte(OSSL_SELF_TEST *st, unsigned char *bytes);
+void OSSL_SELF_TEST_onend(OSSL_SELF_TEST *st, int ret);
+
+#endif /* OPENSSL_SELF_TEST_H */
diff --git a/include/openssl/sha.h b/include/openssl/sha.h
new file mode 100644
index 00000000..6e65a040
--- /dev/null
+++ b/include/openssl/sha.h
@@ -0,0 +1,138 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_SHA_H
+# define OPENSSL_SHA_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SHA_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <stddef.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define SHA_DIGEST_LENGTH 20
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/*-
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ * ! SHA_LONG has to be at least 32 bits wide. !
+ * !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
+ */
+# define SHA_LONG unsigned int
+
+# define SHA_LBLOCK 16
+# define SHA_CBLOCK (SHA_LBLOCK*4)/* SHA treats input data as a
+ * contiguous array of 32 bit wide
+ * big-endian values. */
+# define SHA_LAST_BLOCK (SHA_CBLOCK-8)
+
+typedef struct SHAstate_st {
+ SHA_LONG h0, h1, h2, h3, h4;
+ SHA_LONG Nl, Nh;
+ SHA_LONG data[SHA_LBLOCK];
+ unsigned int num;
+} SHA_CTX;
+
+OSSL_DEPRECATEDIN_3_0 int SHA1_Init(SHA_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int SHA1_Update(SHA_CTX *c, const void *data, size_t len);
+OSSL_DEPRECATEDIN_3_0 int SHA1_Final(unsigned char *md, SHA_CTX *c);
+OSSL_DEPRECATEDIN_3_0 void SHA1_Transform(SHA_CTX *c, const unsigned char *data);
+# endif
+
+unsigned char *SHA1(const unsigned char *d, size_t n, unsigned char *md);
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SHA256_CBLOCK (SHA_LBLOCK*4)/* SHA-256 treats input data as a
+ * contiguous array of 32 bit wide
+ * big-endian values. */
+
+typedef struct SHA256state_st {
+ SHA_LONG h[8];
+ SHA_LONG Nl, Nh;
+ SHA_LONG data[SHA_LBLOCK];
+ unsigned int num, md_len;
+} SHA256_CTX;
+
+OSSL_DEPRECATEDIN_3_0 int SHA224_Init(SHA256_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int SHA224_Update(SHA256_CTX *c,
+ const void *data, size_t len);
+OSSL_DEPRECATEDIN_3_0 int SHA224_Final(unsigned char *md, SHA256_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int SHA256_Init(SHA256_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int SHA256_Update(SHA256_CTX *c,
+ const void *data, size_t len);
+OSSL_DEPRECATEDIN_3_0 int SHA256_Final(unsigned char *md, SHA256_CTX *c);
+OSSL_DEPRECATEDIN_3_0 void SHA256_Transform(SHA256_CTX *c,
+ const unsigned char *data);
+# endif
+
+unsigned char *SHA224(const unsigned char *d, size_t n, unsigned char *md);
+unsigned char *SHA256(const unsigned char *d, size_t n, unsigned char *md);
+
+# define SHA224_DIGEST_LENGTH 28
+# define SHA256_DIGEST_LENGTH 32
+# define SHA384_DIGEST_LENGTH 48
+# define SHA512_DIGEST_LENGTH 64
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/*
+ * Unlike 32-bit digest algorithms, SHA-512 *relies* on SHA_LONG64
+ * being exactly 64-bit wide. See Implementation Notes in sha512.c
+ * for further details.
+ */
+/*
+ * SHA-512 treats input data as a
+ * contiguous array of 64 bit
+ * wide big-endian values.
+ */
+# define SHA512_CBLOCK (SHA_LBLOCK*8)
+# if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32__)
+# define SHA_LONG64 unsigned __int64
+# elif defined(__arch64__)
+# define SHA_LONG64 unsigned long
+# else
+# define SHA_LONG64 unsigned long long
+# endif
+
+typedef struct SHA512state_st {
+ SHA_LONG64 h[8];
+ SHA_LONG64 Nl, Nh;
+ union {
+ SHA_LONG64 d[SHA_LBLOCK];
+ unsigned char p[SHA512_CBLOCK];
+ } u;
+ unsigned int num, md_len;
+} SHA512_CTX;
+
+OSSL_DEPRECATEDIN_3_0 int SHA384_Init(SHA512_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int SHA384_Update(SHA512_CTX *c,
+ const void *data, size_t len);
+OSSL_DEPRECATEDIN_3_0 int SHA384_Final(unsigned char *md, SHA512_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int SHA512_Init(SHA512_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int SHA512_Update(SHA512_CTX *c,
+ const void *data, size_t len);
+OSSL_DEPRECATEDIN_3_0 int SHA512_Final(unsigned char *md, SHA512_CTX *c);
+OSSL_DEPRECATEDIN_3_0 void SHA512_Transform(SHA512_CTX *c,
+ const unsigned char *data);
+# endif
+
+unsigned char *SHA384(const unsigned char *d, size_t n, unsigned char *md);
+unsigned char *SHA512(const unsigned char *d, size_t n, unsigned char *md);
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/srp.h b/include/openssl/srp.h
new file mode 100644
index 00000000..a86fa5d2
--- /dev/null
+++ b/include/openssl/srp.h
@@ -0,0 +1,285 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\srp.h.in
+ *
+ * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2004, EdelKey Project. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ *
+ * Originally written by Christophe Renou and Peter Sylvester,
+ * for the EdelKey project.
+ */
+
+
+
+#ifndef OPENSSL_SRP_H
+# define OPENSSL_SRP_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SRP_H
+# endif
+
+#include <openssl/opensslconf.h>
+
+#ifndef OPENSSL_NO_SRP
+# include <stdio.h>
+# include <string.h>
+# include <openssl/safestack.h>
+# include <openssl/bn.h>
+# include <openssl/crypto.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+typedef struct SRP_gN_cache_st {
+ char *b64_bn;
+ BIGNUM *bn;
+} SRP_gN_cache;
+SKM_DEFINE_STACK_OF_INTERNAL(SRP_gN_cache, SRP_gN_cache, SRP_gN_cache)
+#define sk_SRP_gN_cache_num(sk) OPENSSL_sk_num(ossl_check_const_SRP_gN_cache_sk_type(sk))
+#define sk_SRP_gN_cache_value(sk, idx) ((SRP_gN_cache *)OPENSSL_sk_value(ossl_check_const_SRP_gN_cache_sk_type(sk), (idx)))
+#define sk_SRP_gN_cache_new(cmp) ((STACK_OF(SRP_gN_cache) *)OPENSSL_sk_new(ossl_check_SRP_gN_cache_compfunc_type(cmp)))
+#define sk_SRP_gN_cache_new_null() ((STACK_OF(SRP_gN_cache) *)OPENSSL_sk_new_null())
+#define sk_SRP_gN_cache_new_reserve(cmp, n) ((STACK_OF(SRP_gN_cache) *)OPENSSL_sk_new_reserve(ossl_check_SRP_gN_cache_compfunc_type(cmp), (n)))
+#define sk_SRP_gN_cache_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SRP_gN_cache_sk_type(sk), (n))
+#define sk_SRP_gN_cache_free(sk) OPENSSL_sk_free(ossl_check_SRP_gN_cache_sk_type(sk))
+#define sk_SRP_gN_cache_zero(sk) OPENSSL_sk_zero(ossl_check_SRP_gN_cache_sk_type(sk))
+#define sk_SRP_gN_cache_delete(sk, i) ((SRP_gN_cache *)OPENSSL_sk_delete(ossl_check_SRP_gN_cache_sk_type(sk), (i)))
+#define sk_SRP_gN_cache_delete_ptr(sk, ptr) ((SRP_gN_cache *)OPENSSL_sk_delete_ptr(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_type(ptr)))
+#define sk_SRP_gN_cache_push(sk, ptr) OPENSSL_sk_push(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_type(ptr))
+#define sk_SRP_gN_cache_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_type(ptr))
+#define sk_SRP_gN_cache_pop(sk) ((SRP_gN_cache *)OPENSSL_sk_pop(ossl_check_SRP_gN_cache_sk_type(sk)))
+#define sk_SRP_gN_cache_shift(sk) ((SRP_gN_cache *)OPENSSL_sk_shift(ossl_check_SRP_gN_cache_sk_type(sk)))
+#define sk_SRP_gN_cache_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SRP_gN_cache_sk_type(sk),ossl_check_SRP_gN_cache_freefunc_type(freefunc))
+#define sk_SRP_gN_cache_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_type(ptr), (idx))
+#define sk_SRP_gN_cache_set(sk, idx, ptr) ((SRP_gN_cache *)OPENSSL_sk_set(ossl_check_SRP_gN_cache_sk_type(sk), (idx), ossl_check_SRP_gN_cache_type(ptr)))
+#define sk_SRP_gN_cache_find(sk, ptr) OPENSSL_sk_find(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_type(ptr))
+#define sk_SRP_gN_cache_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_type(ptr))
+#define sk_SRP_gN_cache_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_type(ptr), pnum)
+#define sk_SRP_gN_cache_sort(sk) OPENSSL_sk_sort(ossl_check_SRP_gN_cache_sk_type(sk))
+#define sk_SRP_gN_cache_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SRP_gN_cache_sk_type(sk))
+#define sk_SRP_gN_cache_dup(sk) ((STACK_OF(SRP_gN_cache) *)OPENSSL_sk_dup(ossl_check_const_SRP_gN_cache_sk_type(sk)))
+#define sk_SRP_gN_cache_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SRP_gN_cache) *)OPENSSL_sk_deep_copy(ossl_check_const_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_copyfunc_type(copyfunc), ossl_check_SRP_gN_cache_freefunc_type(freefunc)))
+#define sk_SRP_gN_cache_set_cmp_func(sk, cmp) ((sk_SRP_gN_cache_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SRP_gN_cache_sk_type(sk), ossl_check_SRP_gN_cache_compfunc_type(cmp)))
+
+
+
+typedef struct SRP_user_pwd_st {
+ /* Owned by us. */
+ char *id;
+ BIGNUM *s;
+ BIGNUM *v;
+ /* Not owned by us. */
+ const BIGNUM *g;
+ const BIGNUM *N;
+ /* Owned by us. */
+ char *info;
+} SRP_user_pwd;
+SKM_DEFINE_STACK_OF_INTERNAL(SRP_user_pwd, SRP_user_pwd, SRP_user_pwd)
+#define sk_SRP_user_pwd_num(sk) OPENSSL_sk_num(ossl_check_const_SRP_user_pwd_sk_type(sk))
+#define sk_SRP_user_pwd_value(sk, idx) ((SRP_user_pwd *)OPENSSL_sk_value(ossl_check_const_SRP_user_pwd_sk_type(sk), (idx)))
+#define sk_SRP_user_pwd_new(cmp) ((STACK_OF(SRP_user_pwd) *)OPENSSL_sk_new(ossl_check_SRP_user_pwd_compfunc_type(cmp)))
+#define sk_SRP_user_pwd_new_null() ((STACK_OF(SRP_user_pwd) *)OPENSSL_sk_new_null())
+#define sk_SRP_user_pwd_new_reserve(cmp, n) ((STACK_OF(SRP_user_pwd) *)OPENSSL_sk_new_reserve(ossl_check_SRP_user_pwd_compfunc_type(cmp), (n)))
+#define sk_SRP_user_pwd_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SRP_user_pwd_sk_type(sk), (n))
+#define sk_SRP_user_pwd_free(sk) OPENSSL_sk_free(ossl_check_SRP_user_pwd_sk_type(sk))
+#define sk_SRP_user_pwd_zero(sk) OPENSSL_sk_zero(ossl_check_SRP_user_pwd_sk_type(sk))
+#define sk_SRP_user_pwd_delete(sk, i) ((SRP_user_pwd *)OPENSSL_sk_delete(ossl_check_SRP_user_pwd_sk_type(sk), (i)))
+#define sk_SRP_user_pwd_delete_ptr(sk, ptr) ((SRP_user_pwd *)OPENSSL_sk_delete_ptr(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_type(ptr)))
+#define sk_SRP_user_pwd_push(sk, ptr) OPENSSL_sk_push(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_type(ptr))
+#define sk_SRP_user_pwd_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_type(ptr))
+#define sk_SRP_user_pwd_pop(sk) ((SRP_user_pwd *)OPENSSL_sk_pop(ossl_check_SRP_user_pwd_sk_type(sk)))
+#define sk_SRP_user_pwd_shift(sk) ((SRP_user_pwd *)OPENSSL_sk_shift(ossl_check_SRP_user_pwd_sk_type(sk)))
+#define sk_SRP_user_pwd_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SRP_user_pwd_sk_type(sk),ossl_check_SRP_user_pwd_freefunc_type(freefunc))
+#define sk_SRP_user_pwd_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_type(ptr), (idx))
+#define sk_SRP_user_pwd_set(sk, idx, ptr) ((SRP_user_pwd *)OPENSSL_sk_set(ossl_check_SRP_user_pwd_sk_type(sk), (idx), ossl_check_SRP_user_pwd_type(ptr)))
+#define sk_SRP_user_pwd_find(sk, ptr) OPENSSL_sk_find(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_type(ptr))
+#define sk_SRP_user_pwd_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_type(ptr))
+#define sk_SRP_user_pwd_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_type(ptr), pnum)
+#define sk_SRP_user_pwd_sort(sk) OPENSSL_sk_sort(ossl_check_SRP_user_pwd_sk_type(sk))
+#define sk_SRP_user_pwd_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SRP_user_pwd_sk_type(sk))
+#define sk_SRP_user_pwd_dup(sk) ((STACK_OF(SRP_user_pwd) *)OPENSSL_sk_dup(ossl_check_const_SRP_user_pwd_sk_type(sk)))
+#define sk_SRP_user_pwd_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SRP_user_pwd) *)OPENSSL_sk_deep_copy(ossl_check_const_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_copyfunc_type(copyfunc), ossl_check_SRP_user_pwd_freefunc_type(freefunc)))
+#define sk_SRP_user_pwd_set_cmp_func(sk, cmp) ((sk_SRP_user_pwd_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SRP_user_pwd_sk_type(sk), ossl_check_SRP_user_pwd_compfunc_type(cmp)))
+
+
+OSSL_DEPRECATEDIN_3_0
+SRP_user_pwd *SRP_user_pwd_new(void);
+OSSL_DEPRECATEDIN_3_0
+void SRP_user_pwd_free(SRP_user_pwd *user_pwd);
+
+OSSL_DEPRECATEDIN_3_0
+void SRP_user_pwd_set_gN(SRP_user_pwd *user_pwd, const BIGNUM *g,
+ const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+int SRP_user_pwd_set1_ids(SRP_user_pwd *user_pwd, const char *id,
+ const char *info);
+OSSL_DEPRECATEDIN_3_0
+int SRP_user_pwd_set0_sv(SRP_user_pwd *user_pwd, BIGNUM *s, BIGNUM *v);
+
+typedef struct SRP_VBASE_st {
+ STACK_OF(SRP_user_pwd) *users_pwd;
+ STACK_OF(SRP_gN_cache) *gN_cache;
+/* to simulate a user */
+ char *seed_key;
+ const BIGNUM *default_g;
+ const BIGNUM *default_N;
+} SRP_VBASE;
+
+/*
+ * Internal structure storing N and g pair
+ */
+typedef struct SRP_gN_st {
+ char *id;
+ const BIGNUM *g;
+ const BIGNUM *N;
+} SRP_gN;
+SKM_DEFINE_STACK_OF_INTERNAL(SRP_gN, SRP_gN, SRP_gN)
+#define sk_SRP_gN_num(sk) OPENSSL_sk_num(ossl_check_const_SRP_gN_sk_type(sk))
+#define sk_SRP_gN_value(sk, idx) ((SRP_gN *)OPENSSL_sk_value(ossl_check_const_SRP_gN_sk_type(sk), (idx)))
+#define sk_SRP_gN_new(cmp) ((STACK_OF(SRP_gN) *)OPENSSL_sk_new(ossl_check_SRP_gN_compfunc_type(cmp)))
+#define sk_SRP_gN_new_null() ((STACK_OF(SRP_gN) *)OPENSSL_sk_new_null())
+#define sk_SRP_gN_new_reserve(cmp, n) ((STACK_OF(SRP_gN) *)OPENSSL_sk_new_reserve(ossl_check_SRP_gN_compfunc_type(cmp), (n)))
+#define sk_SRP_gN_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SRP_gN_sk_type(sk), (n))
+#define sk_SRP_gN_free(sk) OPENSSL_sk_free(ossl_check_SRP_gN_sk_type(sk))
+#define sk_SRP_gN_zero(sk) OPENSSL_sk_zero(ossl_check_SRP_gN_sk_type(sk))
+#define sk_SRP_gN_delete(sk, i) ((SRP_gN *)OPENSSL_sk_delete(ossl_check_SRP_gN_sk_type(sk), (i)))
+#define sk_SRP_gN_delete_ptr(sk, ptr) ((SRP_gN *)OPENSSL_sk_delete_ptr(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_type(ptr)))
+#define sk_SRP_gN_push(sk, ptr) OPENSSL_sk_push(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_type(ptr))
+#define sk_SRP_gN_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_type(ptr))
+#define sk_SRP_gN_pop(sk) ((SRP_gN *)OPENSSL_sk_pop(ossl_check_SRP_gN_sk_type(sk)))
+#define sk_SRP_gN_shift(sk) ((SRP_gN *)OPENSSL_sk_shift(ossl_check_SRP_gN_sk_type(sk)))
+#define sk_SRP_gN_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SRP_gN_sk_type(sk),ossl_check_SRP_gN_freefunc_type(freefunc))
+#define sk_SRP_gN_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_type(ptr), (idx))
+#define sk_SRP_gN_set(sk, idx, ptr) ((SRP_gN *)OPENSSL_sk_set(ossl_check_SRP_gN_sk_type(sk), (idx), ossl_check_SRP_gN_type(ptr)))
+#define sk_SRP_gN_find(sk, ptr) OPENSSL_sk_find(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_type(ptr))
+#define sk_SRP_gN_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_type(ptr))
+#define sk_SRP_gN_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_type(ptr), pnum)
+#define sk_SRP_gN_sort(sk) OPENSSL_sk_sort(ossl_check_SRP_gN_sk_type(sk))
+#define sk_SRP_gN_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SRP_gN_sk_type(sk))
+#define sk_SRP_gN_dup(sk) ((STACK_OF(SRP_gN) *)OPENSSL_sk_dup(ossl_check_const_SRP_gN_sk_type(sk)))
+#define sk_SRP_gN_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SRP_gN) *)OPENSSL_sk_deep_copy(ossl_check_const_SRP_gN_sk_type(sk), ossl_check_SRP_gN_copyfunc_type(copyfunc), ossl_check_SRP_gN_freefunc_type(freefunc)))
+#define sk_SRP_gN_set_cmp_func(sk, cmp) ((sk_SRP_gN_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SRP_gN_sk_type(sk), ossl_check_SRP_gN_compfunc_type(cmp)))
+
+
+
+OSSL_DEPRECATEDIN_3_0
+SRP_VBASE *SRP_VBASE_new(char *seed_key);
+OSSL_DEPRECATEDIN_3_0
+void SRP_VBASE_free(SRP_VBASE *vb);
+OSSL_DEPRECATEDIN_3_0
+int SRP_VBASE_init(SRP_VBASE *vb, char *verifier_file);
+
+OSSL_DEPRECATEDIN_3_0
+int SRP_VBASE_add0_user(SRP_VBASE *vb, SRP_user_pwd *user_pwd);
+
+/* NOTE: unlike in SRP_VBASE_get_by_user, caller owns the returned pointer.*/
+OSSL_DEPRECATEDIN_3_0
+SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username);
+
+OSSL_DEPRECATEDIN_3_0
+char *SRP_create_verifier_ex(const char *user, const char *pass, char **salt,
+ char **verifier, const char *N, const char *g,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+char *SRP_create_verifier(const char *user, const char *pass, char **salt,
+ char **verifier, const char *N, const char *g);
+OSSL_DEPRECATEDIN_3_0
+int SRP_create_verifier_BN_ex(const char *user, const char *pass, BIGNUM **salt,
+ BIGNUM **verifier, const BIGNUM *N,
+ const BIGNUM *g, OSSL_LIB_CTX *libctx,
+ const char *propq);
+OSSL_DEPRECATEDIN_3_0
+int SRP_create_verifier_BN(const char *user, const char *pass, BIGNUM **salt,
+ BIGNUM **verifier, const BIGNUM *N,
+ const BIGNUM *g);
+
+# define SRP_NO_ERROR 0
+# define SRP_ERR_VBASE_INCOMPLETE_FILE 1
+# define SRP_ERR_VBASE_BN_LIB 2
+# define SRP_ERR_OPEN_FILE 3
+# define SRP_ERR_MEMORY 4
+
+# define DB_srptype 0
+# define DB_srpverifier 1
+# define DB_srpsalt 2
+# define DB_srpid 3
+# define DB_srpgN 4
+# define DB_srpinfo 5
+# undef DB_NUMBER
+# define DB_NUMBER 6
+
+# define DB_SRP_INDEX 'I'
+# define DB_SRP_VALID 'V'
+# define DB_SRP_REVOKED 'R'
+# define DB_SRP_MODIF 'v'
+
+/* see srp.c */
+OSSL_DEPRECATEDIN_3_0
+char *SRP_check_known_gN_param(const BIGNUM *g, const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+SRP_gN *SRP_get_default_gN(const char *id);
+
+/* server side .... */
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_server_key(const BIGNUM *A, const BIGNUM *v, const BIGNUM *u,
+ const BIGNUM *b, const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_B_ex(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g,
+ const BIGNUM *v, OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_B(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g,
+ const BIGNUM *v);
+
+OSSL_DEPRECATEDIN_3_0
+int SRP_Verify_A_mod_N(const BIGNUM *A, const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_u_ex(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_u(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N);
+
+/* client side .... */
+
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_x_ex(const BIGNUM *s, const char *user, const char *pass,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_x(const BIGNUM *s, const char *user, const char *pass);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_A(const BIGNUM *a, const BIGNUM *N, const BIGNUM *g);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_client_key_ex(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g,
+ const BIGNUM *x, const BIGNUM *a, const BIGNUM *u,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_client_key(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g,
+ const BIGNUM *x, const BIGNUM *a, const BIGNUM *u);
+OSSL_DEPRECATEDIN_3_0
+int SRP_Verify_B_mod_N(const BIGNUM *B, const BIGNUM *N);
+
+# define SRP_MINIMAL_N 1024
+
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/* This method ignores the configured seed and fails for an unknown user. */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0
+SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/srp.h.in b/include/openssl/srp.h.in
new file mode 100644
index 00000000..dfbe845b
--- /dev/null
+++ b/include/openssl/srp.h.in
@@ -0,0 +1,214 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2004-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2004, EdelKey Project. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ *
+ * Originally written by Christophe Renou and Peter Sylvester,
+ * for the EdelKey project.
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_SRP_H
+# define OPENSSL_SRP_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SRP_H
+# endif
+
+#include <openssl/opensslconf.h>
+
+#ifndef OPENSSL_NO_SRP
+# include <stdio.h>
+# include <string.h>
+# include <openssl/safestack.h>
+# include <openssl/bn.h>
+# include <openssl/crypto.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+typedef struct SRP_gN_cache_st {
+ char *b64_bn;
+ BIGNUM *bn;
+} SRP_gN_cache;
+{-
+ generate_stack_macros("SRP_gN_cache");
+-}
+
+
+typedef struct SRP_user_pwd_st {
+ /* Owned by us. */
+ char *id;
+ BIGNUM *s;
+ BIGNUM *v;
+ /* Not owned by us. */
+ const BIGNUM *g;
+ const BIGNUM *N;
+ /* Owned by us. */
+ char *info;
+} SRP_user_pwd;
+{-
+ generate_stack_macros("SRP_user_pwd");
+-}
+
+OSSL_DEPRECATEDIN_3_0
+SRP_user_pwd *SRP_user_pwd_new(void);
+OSSL_DEPRECATEDIN_3_0
+void SRP_user_pwd_free(SRP_user_pwd *user_pwd);
+
+OSSL_DEPRECATEDIN_3_0
+void SRP_user_pwd_set_gN(SRP_user_pwd *user_pwd, const BIGNUM *g,
+ const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+int SRP_user_pwd_set1_ids(SRP_user_pwd *user_pwd, const char *id,
+ const char *info);
+OSSL_DEPRECATEDIN_3_0
+int SRP_user_pwd_set0_sv(SRP_user_pwd *user_pwd, BIGNUM *s, BIGNUM *v);
+
+typedef struct SRP_VBASE_st {
+ STACK_OF(SRP_user_pwd) *users_pwd;
+ STACK_OF(SRP_gN_cache) *gN_cache;
+/* to simulate a user */
+ char *seed_key;
+ const BIGNUM *default_g;
+ const BIGNUM *default_N;
+} SRP_VBASE;
+
+/*
+ * Internal structure storing N and g pair
+ */
+typedef struct SRP_gN_st {
+ char *id;
+ const BIGNUM *g;
+ const BIGNUM *N;
+} SRP_gN;
+{-
+ generate_stack_macros("SRP_gN");
+-}
+
+
+OSSL_DEPRECATEDIN_3_0
+SRP_VBASE *SRP_VBASE_new(char *seed_key);
+OSSL_DEPRECATEDIN_3_0
+void SRP_VBASE_free(SRP_VBASE *vb);
+OSSL_DEPRECATEDIN_3_0
+int SRP_VBASE_init(SRP_VBASE *vb, char *verifier_file);
+
+OSSL_DEPRECATEDIN_3_0
+int SRP_VBASE_add0_user(SRP_VBASE *vb, SRP_user_pwd *user_pwd);
+
+/* NOTE: unlike in SRP_VBASE_get_by_user, caller owns the returned pointer.*/
+OSSL_DEPRECATEDIN_3_0
+SRP_user_pwd *SRP_VBASE_get1_by_user(SRP_VBASE *vb, char *username);
+
+OSSL_DEPRECATEDIN_3_0
+char *SRP_create_verifier_ex(const char *user, const char *pass, char **salt,
+ char **verifier, const char *N, const char *g,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+char *SRP_create_verifier(const char *user, const char *pass, char **salt,
+ char **verifier, const char *N, const char *g);
+OSSL_DEPRECATEDIN_3_0
+int SRP_create_verifier_BN_ex(const char *user, const char *pass, BIGNUM **salt,
+ BIGNUM **verifier, const BIGNUM *N,
+ const BIGNUM *g, OSSL_LIB_CTX *libctx,
+ const char *propq);
+OSSL_DEPRECATEDIN_3_0
+int SRP_create_verifier_BN(const char *user, const char *pass, BIGNUM **salt,
+ BIGNUM **verifier, const BIGNUM *N,
+ const BIGNUM *g);
+
+# define SRP_NO_ERROR 0
+# define SRP_ERR_VBASE_INCOMPLETE_FILE 1
+# define SRP_ERR_VBASE_BN_LIB 2
+# define SRP_ERR_OPEN_FILE 3
+# define SRP_ERR_MEMORY 4
+
+# define DB_srptype 0
+# define DB_srpverifier 1
+# define DB_srpsalt 2
+# define DB_srpid 3
+# define DB_srpgN 4
+# define DB_srpinfo 5
+# undef DB_NUMBER
+# define DB_NUMBER 6
+
+# define DB_SRP_INDEX 'I'
+# define DB_SRP_VALID 'V'
+# define DB_SRP_REVOKED 'R'
+# define DB_SRP_MODIF 'v'
+
+/* see srp.c */
+OSSL_DEPRECATEDIN_3_0
+char *SRP_check_known_gN_param(const BIGNUM *g, const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+SRP_gN *SRP_get_default_gN(const char *id);
+
+/* server side .... */
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_server_key(const BIGNUM *A, const BIGNUM *v, const BIGNUM *u,
+ const BIGNUM *b, const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_B_ex(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g,
+ const BIGNUM *v, OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_B(const BIGNUM *b, const BIGNUM *N, const BIGNUM *g,
+ const BIGNUM *v);
+
+OSSL_DEPRECATEDIN_3_0
+int SRP_Verify_A_mod_N(const BIGNUM *A, const BIGNUM *N);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_u_ex(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_u(const BIGNUM *A, const BIGNUM *B, const BIGNUM *N);
+
+/* client side .... */
+
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_x_ex(const BIGNUM *s, const char *user, const char *pass,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_x(const BIGNUM *s, const char *user, const char *pass);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_A(const BIGNUM *a, const BIGNUM *N, const BIGNUM *g);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_client_key_ex(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g,
+ const BIGNUM *x, const BIGNUM *a, const BIGNUM *u,
+ OSSL_LIB_CTX *libctx, const char *propq);
+OSSL_DEPRECATEDIN_3_0
+BIGNUM *SRP_Calc_client_key(const BIGNUM *N, const BIGNUM *B, const BIGNUM *g,
+ const BIGNUM *x, const BIGNUM *a, const BIGNUM *u);
+OSSL_DEPRECATEDIN_3_0
+int SRP_Verify_B_mod_N(const BIGNUM *B, const BIGNUM *N);
+
+# define SRP_MINIMAL_N 1024
+
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+/* This method ignores the configured seed and fails for an unknown user. */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0
+SRP_user_pwd *SRP_VBASE_get_by_user(SRP_VBASE *vb, char *username);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/srtp.h b/include/openssl/srtp.h
new file mode 100644
index 00000000..d64606e5
--- /dev/null
+++ b/include/openssl/srtp.h
@@ -0,0 +1,56 @@
+/*
+ * Copyright 2011-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * DTLS code by Eric Rescorla <ekr@rtfm.com>
+ *
+ * Copyright (C) 2006, Network Resonance, Inc. Copyright (C) 2011, RTFM, Inc.
+ */
+
+#ifndef OPENSSL_SRTP_H
+# define OPENSSL_SRTP_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_D1_SRTP_H
+# endif
+
+# include <openssl/ssl.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define SRTP_AES128_CM_SHA1_80 0x0001
+# define SRTP_AES128_CM_SHA1_32 0x0002
+# define SRTP_AES128_F8_SHA1_80 0x0003
+# define SRTP_AES128_F8_SHA1_32 0x0004
+# define SRTP_NULL_SHA1_80 0x0005
+# define SRTP_NULL_SHA1_32 0x0006
+
+/* AEAD SRTP protection profiles from RFC 7714 */
+# define SRTP_AEAD_AES_128_GCM 0x0007
+# define SRTP_AEAD_AES_256_GCM 0x0008
+
+# ifndef OPENSSL_NO_SRTP
+
+__owur int SSL_CTX_set_tlsext_use_srtp(SSL_CTX *ctx, const char *profiles);
+__owur int SSL_set_tlsext_use_srtp(SSL *ssl, const char *profiles);
+
+__owur STACK_OF(SRTP_PROTECTION_PROFILE) *SSL_get_srtp_profiles(SSL *ssl);
+__owur SRTP_PROTECTION_PROFILE *SSL_get_selected_srtp_profile(SSL *s);
+
+# endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/ssl.h b/include/openssl/ssl.h
new file mode 100644
index 00000000..0763a33c
--- /dev/null
+++ b/include/openssl/ssl.h
@@ -0,0 +1,2585 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\ssl.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ * Copyright 2005 Nokia. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_SSL_H
+# define OPENSSL_SSL_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SSL_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/opensslconf.h>
+# include <openssl/comp.h>
+# include <openssl/bio.h>
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/x509.h>
+# include <openssl/crypto.h>
+# include <openssl/buffer.h>
+# endif
+# include <openssl/lhash.h>
+# include <openssl/pem.h>
+# include <openssl/hmac.h>
+# include <openssl/async.h>
+
+# include <openssl/safestack.h>
+# include <openssl/symhacks.h>
+# include <openssl/ct.h>
+# include <openssl/sslerr.h>
+# include <openssl/prov_ssl.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* OpenSSL version number for ASN.1 encoding of the session information */
+/*-
+ * Version 0 - initial version
+ * Version 1 - added the optional peer certificate
+ */
+# define SSL_SESSION_ASN1_VERSION 0x0001
+
+# define SSL_MAX_SSL_SESSION_ID_LENGTH 32
+# define SSL_MAX_SID_CTX_LENGTH 32
+
+# define SSL_MIN_RSA_MODULUS_LENGTH_IN_BYTES (512/8)
+# define SSL_MAX_KEY_ARG_LENGTH 8
+/* SSL_MAX_MASTER_KEY_LENGTH is defined in prov_ssl.h */
+
+/* The maximum number of encrypt/decrypt pipelines we can support */
+# define SSL_MAX_PIPELINES 32
+
+/* text strings for the ciphers */
+
+/* These are used to specify which ciphers to use and not to use */
+
+# define SSL_TXT_LOW "LOW"
+# define SSL_TXT_MEDIUM "MEDIUM"
+# define SSL_TXT_HIGH "HIGH"
+# define SSL_TXT_FIPS "FIPS"
+
+# define SSL_TXT_aNULL "aNULL"
+# define SSL_TXT_eNULL "eNULL"
+# define SSL_TXT_NULL "NULL"
+
+# define SSL_TXT_kRSA "kRSA"
+# define SSL_TXT_kDHr "kDHr"/* this cipher class has been removed */
+# define SSL_TXT_kDHd "kDHd"/* this cipher class has been removed */
+# define SSL_TXT_kDH "kDH"/* this cipher class has been removed */
+# define SSL_TXT_kEDH "kEDH"/* alias for kDHE */
+# define SSL_TXT_kDHE "kDHE"
+# define SSL_TXT_kECDHr "kECDHr"/* this cipher class has been removed */
+# define SSL_TXT_kECDHe "kECDHe"/* this cipher class has been removed */
+# define SSL_TXT_kECDH "kECDH"/* this cipher class has been removed */
+# define SSL_TXT_kEECDH "kEECDH"/* alias for kECDHE */
+# define SSL_TXT_kECDHE "kECDHE"
+# define SSL_TXT_kPSK "kPSK"
+# define SSL_TXT_kRSAPSK "kRSAPSK"
+# define SSL_TXT_kECDHEPSK "kECDHEPSK"
+# define SSL_TXT_kDHEPSK "kDHEPSK"
+# define SSL_TXT_kGOST "kGOST"
+# define SSL_TXT_kGOST18 "kGOST18"
+# define SSL_TXT_kSRP "kSRP"
+
+# define SSL_TXT_aRSA "aRSA"
+# define SSL_TXT_aDSS "aDSS"
+# define SSL_TXT_aDH "aDH"/* this cipher class has been removed */
+# define SSL_TXT_aECDH "aECDH"/* this cipher class has been removed */
+# define SSL_TXT_aECDSA "aECDSA"
+# define SSL_TXT_aPSK "aPSK"
+# define SSL_TXT_aGOST94 "aGOST94"
+# define SSL_TXT_aGOST01 "aGOST01"
+# define SSL_TXT_aGOST12 "aGOST12"
+# define SSL_TXT_aGOST "aGOST"
+# define SSL_TXT_aSRP "aSRP"
+
+# define SSL_TXT_DSS "DSS"
+# define SSL_TXT_DH "DH"
+# define SSL_TXT_DHE "DHE"/* same as "kDHE:-ADH" */
+# define SSL_TXT_EDH "EDH"/* alias for DHE */
+# define SSL_TXT_ADH "ADH"
+# define SSL_TXT_RSA "RSA"
+# define SSL_TXT_ECDH "ECDH"
+# define SSL_TXT_EECDH "EECDH"/* alias for ECDHE" */
+# define SSL_TXT_ECDHE "ECDHE"/* same as "kECDHE:-AECDH" */
+# define SSL_TXT_AECDH "AECDH"
+# define SSL_TXT_ECDSA "ECDSA"
+# define SSL_TXT_PSK "PSK"
+# define SSL_TXT_SRP "SRP"
+
+# define SSL_TXT_DES "DES"
+# define SSL_TXT_3DES "3DES"
+# define SSL_TXT_RC4 "RC4"
+# define SSL_TXT_RC2 "RC2"
+# define SSL_TXT_IDEA "IDEA"
+# define SSL_TXT_SEED "SEED"
+# define SSL_TXT_AES128 "AES128"
+# define SSL_TXT_AES256 "AES256"
+# define SSL_TXT_AES "AES"
+# define SSL_TXT_AES_GCM "AESGCM"
+# define SSL_TXT_AES_CCM "AESCCM"
+# define SSL_TXT_AES_CCM_8 "AESCCM8"
+# define SSL_TXT_CAMELLIA128 "CAMELLIA128"
+# define SSL_TXT_CAMELLIA256 "CAMELLIA256"
+# define SSL_TXT_CAMELLIA "CAMELLIA"
+# define SSL_TXT_CHACHA20 "CHACHA20"
+# define SSL_TXT_GOST "GOST89"
+# define SSL_TXT_ARIA "ARIA"
+# define SSL_TXT_ARIA_GCM "ARIAGCM"
+# define SSL_TXT_ARIA128 "ARIA128"
+# define SSL_TXT_ARIA256 "ARIA256"
+# define SSL_TXT_GOST2012_GOST8912_GOST8912 "GOST2012-GOST8912-GOST8912"
+# define SSL_TXT_CBC "CBC"
+
+# define SSL_TXT_MD5 "MD5"
+# define SSL_TXT_SHA1 "SHA1"
+# define SSL_TXT_SHA "SHA"/* same as "SHA1" */
+# define SSL_TXT_GOST94 "GOST94"
+# define SSL_TXT_GOST89MAC "GOST89MAC"
+# define SSL_TXT_GOST12 "GOST12"
+# define SSL_TXT_GOST89MAC12 "GOST89MAC12"
+# define SSL_TXT_SHA256 "SHA256"
+# define SSL_TXT_SHA384 "SHA384"
+
+# define SSL_TXT_SSLV3 "SSLv3"
+# define SSL_TXT_TLSV1 "TLSv1"
+# define SSL_TXT_TLSV1_1 "TLSv1.1"
+# define SSL_TXT_TLSV1_2 "TLSv1.2"
+
+# define SSL_TXT_ALL "ALL"
+
+/*-
+ * COMPLEMENTOF* definitions. These identifiers are used to (de-select)
+ * ciphers normally not being used.
+ * Example: "RC4" will activate all ciphers using RC4 including ciphers
+ * without authentication, which would normally disabled by DEFAULT (due
+ * the "!ADH" being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT"
+ * will make sure that it is also disabled in the specific selection.
+ * COMPLEMENTOF* identifiers are portable between version, as adjustments
+ * to the default cipher setup will also be included here.
+ *
+ * COMPLEMENTOFDEFAULT does not experience the same special treatment that
+ * DEFAULT gets, as only selection is being done and no sorting as needed
+ * for DEFAULT.
+ */
+# define SSL_TXT_CMPALL "COMPLEMENTOFALL"
+# define SSL_TXT_CMPDEF "COMPLEMENTOFDEFAULT"
+
+/*
+ * The following cipher list is used by default. It also is substituted when
+ * an application-defined cipher list string starts with 'DEFAULT'.
+ * This applies to ciphersuites for TLSv1.2 and below.
+ * DEPRECATED IN 3.0.0, in favor of OSSL_default_cipher_list()
+ * Update both macro and function simultaneously
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_DEFAULT_CIPHER_LIST "ALL:!COMPLEMENTOFDEFAULT:!eNULL"
+/*
+ * This is the default set of TLSv1.3 ciphersuites
+ * DEPRECATED IN 3.0.0, in favor of OSSL_default_ciphersuites()
+ * Update both macro and function simultaneously
+ */
+# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \
+ "TLS_CHACHA20_POLY1305_SHA256:" \
+ "TLS_AES_128_GCM_SHA256"
+# endif
+/*
+ * As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always
+ * starts with a reasonable order, and all we have to do for DEFAULT is
+ * throwing out anonymous and unencrypted ciphersuites! (The latter are not
+ * actually enabled by ALL, but "ALL:RSA" would enable some of them.)
+ */
+
+/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */
+# define SSL_SENT_SHUTDOWN 1
+# define SSL_RECEIVED_SHUTDOWN 2
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1
+# define SSL_FILETYPE_PEM X509_FILETYPE_PEM
+
+/*
+ * This is needed to stop compilers complaining about the 'struct ssl_st *'
+ * function parameters used to prototype callbacks in SSL_CTX.
+ */
+typedef struct ssl_st *ssl_crock_st;
+typedef struct tls_session_ticket_ext_st TLS_SESSION_TICKET_EXT;
+typedef struct ssl_method_st SSL_METHOD;
+typedef struct ssl_cipher_st SSL_CIPHER;
+typedef struct ssl_session_st SSL_SESSION;
+typedef struct tls_sigalgs_st TLS_SIGALGS;
+typedef struct ssl_conf_ctx_st SSL_CONF_CTX;
+typedef struct ssl_comp_st SSL_COMP;
+
+STACK_OF(SSL_CIPHER);
+STACK_OF(SSL_COMP);
+
+/* SRTP protection profiles for use with the use_srtp extension (RFC 5764)*/
+typedef struct srtp_protection_profile_st {
+ const char *name;
+ unsigned long id;
+} SRTP_PROTECTION_PROFILE;
+SKM_DEFINE_STACK_OF_INTERNAL(SRTP_PROTECTION_PROFILE, SRTP_PROTECTION_PROFILE, SRTP_PROTECTION_PROFILE)
+#define sk_SRTP_PROTECTION_PROFILE_num(sk) OPENSSL_sk_num(ossl_check_const_SRTP_PROTECTION_PROFILE_sk_type(sk))
+#define sk_SRTP_PROTECTION_PROFILE_value(sk, idx) ((SRTP_PROTECTION_PROFILE *)OPENSSL_sk_value(ossl_check_const_SRTP_PROTECTION_PROFILE_sk_type(sk), (idx)))
+#define sk_SRTP_PROTECTION_PROFILE_new(cmp) ((STACK_OF(SRTP_PROTECTION_PROFILE) *)OPENSSL_sk_new(ossl_check_SRTP_PROTECTION_PROFILE_compfunc_type(cmp)))
+#define sk_SRTP_PROTECTION_PROFILE_new_null() ((STACK_OF(SRTP_PROTECTION_PROFILE) *)OPENSSL_sk_new_null())
+#define sk_SRTP_PROTECTION_PROFILE_new_reserve(cmp, n) ((STACK_OF(SRTP_PROTECTION_PROFILE) *)OPENSSL_sk_new_reserve(ossl_check_SRTP_PROTECTION_PROFILE_compfunc_type(cmp), (n)))
+#define sk_SRTP_PROTECTION_PROFILE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), (n))
+#define sk_SRTP_PROTECTION_PROFILE_free(sk) OPENSSL_sk_free(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk))
+#define sk_SRTP_PROTECTION_PROFILE_zero(sk) OPENSSL_sk_zero(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk))
+#define sk_SRTP_PROTECTION_PROFILE_delete(sk, i) ((SRTP_PROTECTION_PROFILE *)OPENSSL_sk_delete(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), (i)))
+#define sk_SRTP_PROTECTION_PROFILE_delete_ptr(sk, ptr) ((SRTP_PROTECTION_PROFILE *)OPENSSL_sk_delete_ptr(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr)))
+#define sk_SRTP_PROTECTION_PROFILE_push(sk, ptr) OPENSSL_sk_push(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr))
+#define sk_SRTP_PROTECTION_PROFILE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr))
+#define sk_SRTP_PROTECTION_PROFILE_pop(sk) ((SRTP_PROTECTION_PROFILE *)OPENSSL_sk_pop(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk)))
+#define sk_SRTP_PROTECTION_PROFILE_shift(sk) ((SRTP_PROTECTION_PROFILE *)OPENSSL_sk_shift(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk)))
+#define sk_SRTP_PROTECTION_PROFILE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk),ossl_check_SRTP_PROTECTION_PROFILE_freefunc_type(freefunc))
+#define sk_SRTP_PROTECTION_PROFILE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr), (idx))
+#define sk_SRTP_PROTECTION_PROFILE_set(sk, idx, ptr) ((SRTP_PROTECTION_PROFILE *)OPENSSL_sk_set(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), (idx), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr)))
+#define sk_SRTP_PROTECTION_PROFILE_find(sk, ptr) OPENSSL_sk_find(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr))
+#define sk_SRTP_PROTECTION_PROFILE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr))
+#define sk_SRTP_PROTECTION_PROFILE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_type(ptr), pnum)
+#define sk_SRTP_PROTECTION_PROFILE_sort(sk) OPENSSL_sk_sort(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk))
+#define sk_SRTP_PROTECTION_PROFILE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SRTP_PROTECTION_PROFILE_sk_type(sk))
+#define sk_SRTP_PROTECTION_PROFILE_dup(sk) ((STACK_OF(SRTP_PROTECTION_PROFILE) *)OPENSSL_sk_dup(ossl_check_const_SRTP_PROTECTION_PROFILE_sk_type(sk)))
+#define sk_SRTP_PROTECTION_PROFILE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SRTP_PROTECTION_PROFILE) *)OPENSSL_sk_deep_copy(ossl_check_const_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_copyfunc_type(copyfunc), ossl_check_SRTP_PROTECTION_PROFILE_freefunc_type(freefunc)))
+#define sk_SRTP_PROTECTION_PROFILE_set_cmp_func(sk, cmp) ((sk_SRTP_PROTECTION_PROFILE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SRTP_PROTECTION_PROFILE_sk_type(sk), ossl_check_SRTP_PROTECTION_PROFILE_compfunc_type(cmp)))
+
+
+
+typedef int (*tls_session_ticket_ext_cb_fn)(SSL *s, const unsigned char *data,
+ int len, void *arg);
+typedef int (*tls_session_secret_cb_fn)(SSL *s, void *secret, int *secret_len,
+ STACK_OF(SSL_CIPHER) *peer_ciphers,
+ const SSL_CIPHER **cipher, void *arg);
+
+/* Extension context codes */
+/* This extension is only allowed in TLS */
+#define SSL_EXT_TLS_ONLY 0x0001
+/* This extension is only allowed in DTLS */
+#define SSL_EXT_DTLS_ONLY 0x0002
+/* Some extensions may be allowed in DTLS but we don't implement them for it */
+#define SSL_EXT_TLS_IMPLEMENTATION_ONLY 0x0004
+/* Most extensions are not defined for SSLv3 but EXT_TYPE_renegotiate is */
+#define SSL_EXT_SSL3_ALLOWED 0x0008
+/* Extension is only defined for TLS1.2 and below */
+#define SSL_EXT_TLS1_2_AND_BELOW_ONLY 0x0010
+/* Extension is only defined for TLS1.3 and above */
+#define SSL_EXT_TLS1_3_ONLY 0x0020
+/* Ignore this extension during parsing if we are resuming */
+#define SSL_EXT_IGNORE_ON_RESUMPTION 0x0040
+#define SSL_EXT_CLIENT_HELLO 0x0080
+/* Really means TLS1.2 or below */
+#define SSL_EXT_TLS1_2_SERVER_HELLO 0x0100
+#define SSL_EXT_TLS1_3_SERVER_HELLO 0x0200
+#define SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS 0x0400
+#define SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST 0x0800
+#define SSL_EXT_TLS1_3_CERTIFICATE 0x1000
+#define SSL_EXT_TLS1_3_NEW_SESSION_TICKET 0x2000
+#define SSL_EXT_TLS1_3_CERTIFICATE_REQUEST 0x4000
+
+/* Typedefs for handling custom extensions */
+
+typedef int (*custom_ext_add_cb)(SSL *s, unsigned int ext_type,
+ const unsigned char **out, size_t *outlen,
+ int *al, void *add_arg);
+
+typedef void (*custom_ext_free_cb)(SSL *s, unsigned int ext_type,
+ const unsigned char *out, void *add_arg);
+
+typedef int (*custom_ext_parse_cb)(SSL *s, unsigned int ext_type,
+ const unsigned char *in, size_t inlen,
+ int *al, void *parse_arg);
+
+
+typedef int (*SSL_custom_ext_add_cb_ex)(SSL *s, unsigned int ext_type,
+ unsigned int context,
+ const unsigned char **out,
+ size_t *outlen, X509 *x,
+ size_t chainidx,
+ int *al, void *add_arg);
+
+typedef void (*SSL_custom_ext_free_cb_ex)(SSL *s, unsigned int ext_type,
+ unsigned int context,
+ const unsigned char *out,
+ void *add_arg);
+
+typedef int (*SSL_custom_ext_parse_cb_ex)(SSL *s, unsigned int ext_type,
+ unsigned int context,
+ const unsigned char *in,
+ size_t inlen, X509 *x,
+ size_t chainidx,
+ int *al, void *parse_arg);
+
+/* Typedef for verification callback */
+typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx);
+
+/* Typedef for SSL async callback */
+typedef int (*SSL_async_callback_fn)(SSL *s, void *arg);
+
+#define SSL_OP_BIT(n) ((uint64_t)1 << (uint64_t)n)
+
+/*
+ * SSL/TLS connection options.
+ */
+ /* Disable Extended master secret */
+# define SSL_OP_NO_EXTENDED_MASTER_SECRET SSL_OP_BIT(0)
+ /* Cleanse plaintext copies of data delivered to the application */
+# define SSL_OP_CLEANSE_PLAINTEXT SSL_OP_BIT(1)
+ /* Allow initial connection to servers that don't support RI */
+# define SSL_OP_LEGACY_SERVER_CONNECT SSL_OP_BIT(2)
+ /* Enable support for Kernel TLS */
+# define SSL_OP_ENABLE_KTLS SSL_OP_BIT(3)
+# define SSL_OP_TLSEXT_PADDING SSL_OP_BIT(4)
+# define SSL_OP_SAFARI_ECDHE_ECDSA_BUG SSL_OP_BIT(6)
+# define SSL_OP_IGNORE_UNEXPECTED_EOF SSL_OP_BIT(7)
+# define SSL_OP_ALLOW_CLIENT_RENEGOTIATION SSL_OP_BIT(8)
+# define SSL_OP_DISABLE_TLSEXT_CA_NAMES SSL_OP_BIT(9)
+ /* In TLSv1.3 allow a non-(ec)dhe based kex_mode */
+# define SSL_OP_ALLOW_NO_DHE_KEX SSL_OP_BIT(10)
+ /*
+ * Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added
+ * in OpenSSL 0.9.6d. Usually (depending on the application protocol)
+ * the workaround is not needed. Unfortunately some broken SSL/TLS
+ * implementations cannot handle it at all, which is why we include it
+ * in SSL_OP_ALL. Added in 0.9.6e
+ */
+# define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS SSL_OP_BIT(11)
+ /* DTLS options */
+# define SSL_OP_NO_QUERY_MTU SSL_OP_BIT(12)
+ /* Turn on Cookie Exchange (on relevant for servers) */
+# define SSL_OP_COOKIE_EXCHANGE SSL_OP_BIT(13)
+ /* Don't use RFC4507 ticket extension */
+# define SSL_OP_NO_TICKET SSL_OP_BIT(14)
+# ifndef OPENSSL_NO_DTLS1_METHOD
+ /*
+ * Use Cisco's version identifier of DTLS_BAD_VER
+ * (only with deprecated DTLSv1_client_method())
+ */
+# define SSL_OP_CISCO_ANYCONNECT SSL_OP_BIT(15)
+# endif
+ /* As server, disallow session resumption on renegotiation */
+# define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION SSL_OP_BIT(16)
+ /* Don't use compression even if supported */
+# define SSL_OP_NO_COMPRESSION SSL_OP_BIT(17)
+ /* Permit unsafe legacy renegotiation */
+# define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION SSL_OP_BIT(18)
+ /* Disable encrypt-then-mac */
+# define SSL_OP_NO_ENCRYPT_THEN_MAC SSL_OP_BIT(19)
+ /*
+ * Enable TLSv1.3 Compatibility mode. This is on by default. A future
+ * version of OpenSSL may have this disabled by default.
+ */
+# define SSL_OP_ENABLE_MIDDLEBOX_COMPAT SSL_OP_BIT(20)
+ /*
+ * Prioritize Chacha20Poly1305 when client does.
+ * Modifies SSL_OP_CIPHER_SERVER_PREFERENCE
+ */
+# define SSL_OP_PRIORITIZE_CHACHA SSL_OP_BIT(21)
+ /*
+ * Set on servers to choose the cipher according to server's preferences.
+ */
+# define SSL_OP_CIPHER_SERVER_PREFERENCE SSL_OP_BIT(22)
+ /*
+ * If set, a server will allow a client to issue a SSLv3.0 version
+ * number as latest version supported in the premaster secret, even when
+ * TLSv1.0 (version 3.1) was announced in the client hello. Normally
+ * this is forbidden to prevent version rollback attacks.
+ */
+# define SSL_OP_TLS_ROLLBACK_BUG SSL_OP_BIT(23)
+ /*
+ * Switches off automatic TLSv1.3 anti-replay protection for early data.
+ * This is a server-side option only (no effect on the client).
+ */
+# define SSL_OP_NO_ANTI_REPLAY SSL_OP_BIT(24)
+# define SSL_OP_NO_SSLv3 SSL_OP_BIT(25)
+# define SSL_OP_NO_TLSv1 SSL_OP_BIT(26)
+# define SSL_OP_NO_TLSv1_2 SSL_OP_BIT(27)
+# define SSL_OP_NO_TLSv1_1 SSL_OP_BIT(28)
+# define SSL_OP_NO_TLSv1_3 SSL_OP_BIT(29)
+# define SSL_OP_NO_DTLSv1 SSL_OP_BIT(26)
+# define SSL_OP_NO_DTLSv1_2 SSL_OP_BIT(27)
+ /* Disallow all renegotiation */
+# define SSL_OP_NO_RENEGOTIATION SSL_OP_BIT(30)
+ /*
+ * Make server add server-hello extension from early version of
+ * cryptopro draft, when GOST ciphersuite is negotiated. Required for
+ * interoperability with CryptoPro CSP 3.x
+ */
+# define SSL_OP_CRYPTOPRO_TLSEXT_BUG SSL_OP_BIT(31)
+
+/*
+ * Option "collections."
+ */
+# define SSL_OP_NO_SSL_MASK \
+ ( SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 \
+ | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3 )
+# define SSL_OP_NO_DTLS_MASK \
+ ( SSL_OP_NO_DTLSv1 | SSL_OP_NO_DTLSv1_2 )
+
+/* Various bug workarounds that should be rather harmless. */
+# define SSL_OP_ALL \
+ ( SSL_OP_CRYPTOPRO_TLSEXT_BUG | SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS \
+ | SSL_OP_TLSEXT_PADDING | SSL_OP_SAFARI_ECDHE_ECDSA_BUG )
+
+/*
+ * OBSOLETE OPTIONS retained for compatibility
+ */
+
+# define SSL_OP_MICROSOFT_SESS_ID_BUG 0x0
+# define SSL_OP_NETSCAPE_CHALLENGE_BUG 0x0
+# define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0x0
+# define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG 0x0
+# define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER 0x0
+# define SSL_OP_MSIE_SSLV2_RSA_PADDING 0x0
+# define SSL_OP_SSLEAY_080_CLIENT_DH_BUG 0x0
+# define SSL_OP_TLS_D5_BUG 0x0
+# define SSL_OP_TLS_BLOCK_PADDING_BUG 0x0
+# define SSL_OP_SINGLE_ECDH_USE 0x0
+# define SSL_OP_SINGLE_DH_USE 0x0
+# define SSL_OP_EPHEMERAL_RSA 0x0
+# define SSL_OP_NO_SSLv2 0x0
+# define SSL_OP_PKCS1_CHECK_1 0x0
+# define SSL_OP_PKCS1_CHECK_2 0x0
+# define SSL_OP_NETSCAPE_CA_DN_BUG 0x0
+# define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG 0x0
+
+/*
+ * Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success
+ * when just a single record has been written):
+ */
+# define SSL_MODE_ENABLE_PARTIAL_WRITE 0x00000001U
+/*
+ * Make it possible to retry SSL_write() with changed buffer location (buffer
+ * contents must stay the same!); this is not the default to avoid the
+ * misconception that non-blocking SSL_write() behaves like non-blocking
+ * write():
+ */
+# define SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002U
+/*
+ * Never bother the application with retries if the transport is blocking:
+ */
+# define SSL_MODE_AUTO_RETRY 0x00000004U
+/* Don't attempt to automatically build certificate chain */
+# define SSL_MODE_NO_AUTO_CHAIN 0x00000008U
+/*
+ * Save RAM by releasing read and write buffers when they're empty. (SSL3 and
+ * TLS only.) Released buffers are freed.
+ */
+# define SSL_MODE_RELEASE_BUFFERS 0x00000010U
+/*
+ * Send the current time in the Random fields of the ClientHello and
+ * ServerHello records for compatibility with hypothetical implementations
+ * that require it.
+ */
+# define SSL_MODE_SEND_CLIENTHELLO_TIME 0x00000020U
+# define SSL_MODE_SEND_SERVERHELLO_TIME 0x00000040U
+/*
+ * Send TLS_FALLBACK_SCSV in the ClientHello. To be set only by applications
+ * that reconnect with a downgraded protocol version; see
+ * draft-ietf-tls-downgrade-scsv-00 for details. DO NOT ENABLE THIS if your
+ * application attempts a normal handshake. Only use this in explicit
+ * fallback retries, following the guidance in
+ * draft-ietf-tls-downgrade-scsv-00.
+ */
+# define SSL_MODE_SEND_FALLBACK_SCSV 0x00000080U
+/*
+ * Support Asynchronous operation
+ */
+# define SSL_MODE_ASYNC 0x00000100U
+
+/*
+ * When using DTLS/SCTP, include the terminating zero in the label
+ * used for computing the endpoint-pair shared secret. Required for
+ * interoperability with implementations having this bug like these
+ * older version of OpenSSL:
+ * - OpenSSL 1.0.0 series
+ * - OpenSSL 1.0.1 series
+ * - OpenSSL 1.0.2 series
+ * - OpenSSL 1.1.0 series
+ * - OpenSSL 1.1.1 and 1.1.1a
+ */
+# define SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG 0x00000400U
+
+/* Cert related flags */
+/*
+ * Many implementations ignore some aspects of the TLS standards such as
+ * enforcing certificate chain algorithms. When this is set we enforce them.
+ */
+# define SSL_CERT_FLAG_TLS_STRICT 0x00000001U
+
+/* Suite B modes, takes same values as certificate verify flags */
+# define SSL_CERT_FLAG_SUITEB_128_LOS_ONLY 0x10000
+/* Suite B 192 bit only mode */
+# define SSL_CERT_FLAG_SUITEB_192_LOS 0x20000
+/* Suite B 128 bit mode allowing 192 bit algorithms */
+# define SSL_CERT_FLAG_SUITEB_128_LOS 0x30000
+
+/* Perform all sorts of protocol violations for testing purposes */
+# define SSL_CERT_FLAG_BROKEN_PROTOCOL 0x10000000
+
+/* Flags for building certificate chains */
+/* Treat any existing certificates as untrusted CAs */
+# define SSL_BUILD_CHAIN_FLAG_UNTRUSTED 0x1
+/* Don't include root CA in chain */
+# define SSL_BUILD_CHAIN_FLAG_NO_ROOT 0x2
+/* Just check certificates already there */
+# define SSL_BUILD_CHAIN_FLAG_CHECK 0x4
+/* Ignore verification errors */
+# define SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR 0x8
+/* Clear verification errors from queue */
+# define SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR 0x10
+
+/* Flags returned by SSL_check_chain */
+/* Certificate can be used with this session */
+# define CERT_PKEY_VALID 0x1
+/* Certificate can also be used for signing */
+# define CERT_PKEY_SIGN 0x2
+/* EE certificate signing algorithm OK */
+# define CERT_PKEY_EE_SIGNATURE 0x10
+/* CA signature algorithms OK */
+# define CERT_PKEY_CA_SIGNATURE 0x20
+/* EE certificate parameters OK */
+# define CERT_PKEY_EE_PARAM 0x40
+/* CA certificate parameters OK */
+# define CERT_PKEY_CA_PARAM 0x80
+/* Signing explicitly allowed as opposed to SHA1 fallback */
+# define CERT_PKEY_EXPLICIT_SIGN 0x100
+/* Client CA issuer names match (always set for server cert) */
+# define CERT_PKEY_ISSUER_NAME 0x200
+/* Cert type matches client types (always set for server cert) */
+# define CERT_PKEY_CERT_TYPE 0x400
+/* Cert chain suitable to Suite B */
+# define CERT_PKEY_SUITEB 0x800
+
+# define SSL_CONF_FLAG_CMDLINE 0x1
+# define SSL_CONF_FLAG_FILE 0x2
+# define SSL_CONF_FLAG_CLIENT 0x4
+# define SSL_CONF_FLAG_SERVER 0x8
+# define SSL_CONF_FLAG_SHOW_ERRORS 0x10
+# define SSL_CONF_FLAG_CERTIFICATE 0x20
+# define SSL_CONF_FLAG_REQUIRE_PRIVATE 0x40
+/* Configuration value types */
+# define SSL_CONF_TYPE_UNKNOWN 0x0
+# define SSL_CONF_TYPE_STRING 0x1
+# define SSL_CONF_TYPE_FILE 0x2
+# define SSL_CONF_TYPE_DIR 0x3
+# define SSL_CONF_TYPE_NONE 0x4
+# define SSL_CONF_TYPE_STORE 0x5
+
+/* Maximum length of the application-controlled segment of a a TLSv1.3 cookie */
+# define SSL_COOKIE_LENGTH 4096
+
+/*
+ * Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, they
+ * cannot be used to clear bits.
+ */
+
+uint64_t SSL_CTX_get_options(const SSL_CTX *ctx);
+uint64_t SSL_get_options(const SSL *s);
+uint64_t SSL_CTX_clear_options(SSL_CTX *ctx, uint64_t op);
+uint64_t SSL_clear_options(SSL *s, uint64_t op);
+uint64_t SSL_CTX_set_options(SSL_CTX *ctx, uint64_t op);
+uint64_t SSL_set_options(SSL *s, uint64_t op);
+
+# define SSL_CTX_set_mode(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL)
+# define SSL_CTX_clear_mode(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL)
+# define SSL_CTX_get_mode(ctx) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,0,NULL)
+# define SSL_clear_mode(ssl,op) \
+ SSL_ctrl((ssl),SSL_CTRL_CLEAR_MODE,(op),NULL)
+# define SSL_set_mode(ssl,op) \
+ SSL_ctrl((ssl),SSL_CTRL_MODE,(op),NULL)
+# define SSL_get_mode(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_MODE,0,NULL)
+# define SSL_set_mtu(ssl, mtu) \
+ SSL_ctrl((ssl),SSL_CTRL_SET_MTU,(mtu),NULL)
+# define DTLS_set_link_mtu(ssl, mtu) \
+ SSL_ctrl((ssl),DTLS_CTRL_SET_LINK_MTU,(mtu),NULL)
+# define DTLS_get_link_min_mtu(ssl) \
+ SSL_ctrl((ssl),DTLS_CTRL_GET_LINK_MIN_MTU,0,NULL)
+
+# define SSL_get_secure_renegotiation_support(ssl) \
+ SSL_ctrl((ssl), SSL_CTRL_GET_RI_SUPPORT, 0, NULL)
+
+# define SSL_CTX_set_cert_flags(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_CERT_FLAGS,(op),NULL)
+# define SSL_set_cert_flags(s,op) \
+ SSL_ctrl((s),SSL_CTRL_CERT_FLAGS,(op),NULL)
+# define SSL_CTX_clear_cert_flags(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
+# define SSL_clear_cert_flags(s,op) \
+ SSL_ctrl((s),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
+
+void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
+ void (*cb) (int write_p, int version,
+ int content_type, const void *buf,
+ size_t len, SSL *ssl, void *arg));
+void SSL_set_msg_callback(SSL *ssl,
+ void (*cb) (int write_p, int version,
+ int content_type, const void *buf,
+ size_t len, SSL *ssl, void *arg));
+# define SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_CTX_ctrl((ctx), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
+# define SSL_set_msg_callback_arg(ssl, arg) SSL_ctrl((ssl), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
+
+# define SSL_get_extms_support(s) \
+ SSL_ctrl((s),SSL_CTRL_GET_EXTMS_SUPPORT,0,NULL)
+
+# ifndef OPENSSL_NO_SRP
+/* see tls_srp.c */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_SRP_CTX_init(SSL *s);
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_CTX_SRP_CTX_init(SSL_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 int SSL_SRP_CTX_free(SSL *ctx);
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_SRP_CTX_free(SSL_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_srp_server_param_with_username(SSL *s,
+ int *ad);
+OSSL_DEPRECATEDIN_3_0 __owur int SRP_Calc_A_param(SSL *s);
+# endif
+# endif
+
+/* 100k max cert list */
+# define SSL_MAX_CERT_LIST_DEFAULT (1024*100)
+
+# define SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (1024*20)
+
+/*
+ * This callback type is used inside SSL_CTX, SSL, and in the functions that
+ * set them. It is used to override the generation of SSL/TLS session IDs in
+ * a server. Return value should be zero on an error, non-zero to proceed.
+ * Also, callbacks should themselves check if the id they generate is unique
+ * otherwise the SSL handshake will fail with an error - callbacks can do
+ * this using the 'ssl' value they're passed by;
+ * SSL_has_matching_session_id(ssl, id, *id_len) The length value passed in
+ * is set at the maximum size the session ID can be. In SSLv3/TLSv1 it is 32
+ * bytes. The callback can alter this length to be less if desired. It is
+ * also an error for the callback to set the size to zero.
+ */
+typedef int (*GEN_SESSION_CB) (SSL *ssl, unsigned char *id,
+ unsigned int *id_len);
+
+# define SSL_SESS_CACHE_OFF 0x0000
+# define SSL_SESS_CACHE_CLIENT 0x0001
+# define SSL_SESS_CACHE_SERVER 0x0002
+# define SSL_SESS_CACHE_BOTH (SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_SERVER)
+# define SSL_SESS_CACHE_NO_AUTO_CLEAR 0x0080
+/* enough comments already ... see SSL_CTX_set_session_cache_mode(3) */
+# define SSL_SESS_CACHE_NO_INTERNAL_LOOKUP 0x0100
+# define SSL_SESS_CACHE_NO_INTERNAL_STORE 0x0200
+# define SSL_SESS_CACHE_NO_INTERNAL \
+ (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP|SSL_SESS_CACHE_NO_INTERNAL_STORE)
+# define SSL_SESS_CACHE_UPDATE_TIME 0x0400
+
+LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx);
+# define SSL_CTX_sess_number(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_NUMBER,0,NULL)
+# define SSL_CTX_sess_connect(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT,0,NULL)
+# define SSL_CTX_sess_connect_good(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_GOOD,0,NULL)
+# define SSL_CTX_sess_connect_renegotiate(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_RENEGOTIATE,0,NULL)
+# define SSL_CTX_sess_accept(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT,0,NULL)
+# define SSL_CTX_sess_accept_renegotiate(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_RENEGOTIATE,0,NULL)
+# define SSL_CTX_sess_accept_good(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_GOOD,0,NULL)
+# define SSL_CTX_sess_hits(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_HIT,0,NULL)
+# define SSL_CTX_sess_cb_hits(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CB_HIT,0,NULL)
+# define SSL_CTX_sess_misses(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_MISSES,0,NULL)
+# define SSL_CTX_sess_timeouts(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_TIMEOUTS,0,NULL)
+# define SSL_CTX_sess_cache_full(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CACHE_FULL,0,NULL)
+
+void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
+ int (*new_session_cb) (struct ssl_st *ssl,
+ SSL_SESSION *sess));
+int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
+ SSL_SESSION *sess);
+void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
+ void (*remove_session_cb) (struct ssl_ctx_st
+ *ctx,
+ SSL_SESSION *sess));
+void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (struct ssl_ctx_st *ctx,
+ SSL_SESSION *sess);
+void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
+ SSL_SESSION *(*get_session_cb) (struct ssl_st
+ *ssl,
+ const unsigned char
+ *data, int len,
+ int *copy));
+SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
+ const unsigned char *data,
+ int len, int *copy);
+void SSL_CTX_set_info_callback(SSL_CTX *ctx,
+ void (*cb) (const SSL *ssl, int type, int val));
+void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
+ int val);
+void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
+ int (*client_cert_cb) (SSL *ssl, X509 **x509,
+ EVP_PKEY **pkey));
+int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
+ EVP_PKEY **pkey);
+# ifndef OPENSSL_NO_ENGINE
+__owur int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e);
+# endif
+void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
+ int (*app_gen_cookie_cb) (SSL *ssl,
+ unsigned char
+ *cookie,
+ unsigned int
+ *cookie_len));
+void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
+ int (*app_verify_cookie_cb) (SSL *ssl,
+ const unsigned
+ char *cookie,
+ unsigned int
+ cookie_len));
+
+void SSL_CTX_set_stateless_cookie_generate_cb(
+ SSL_CTX *ctx,
+ int (*gen_stateless_cookie_cb) (SSL *ssl,
+ unsigned char *cookie,
+ size_t *cookie_len));
+void SSL_CTX_set_stateless_cookie_verify_cb(
+ SSL_CTX *ctx,
+ int (*verify_stateless_cookie_cb) (SSL *ssl,
+ const unsigned char *cookie,
+ size_t cookie_len));
+# ifndef OPENSSL_NO_NEXTPROTONEG
+
+typedef int (*SSL_CTX_npn_advertised_cb_func)(SSL *ssl,
+ const unsigned char **out,
+ unsigned int *outlen,
+ void *arg);
+void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s,
+ SSL_CTX_npn_advertised_cb_func cb,
+ void *arg);
+# define SSL_CTX_set_npn_advertised_cb SSL_CTX_set_next_protos_advertised_cb
+
+typedef int (*SSL_CTX_npn_select_cb_func)(SSL *s,
+ unsigned char **out,
+ unsigned char *outlen,
+ const unsigned char *in,
+ unsigned int inlen,
+ void *arg);
+void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s,
+ SSL_CTX_npn_select_cb_func cb,
+ void *arg);
+# define SSL_CTX_set_npn_select_cb SSL_CTX_set_next_proto_select_cb
+
+void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
+ unsigned *len);
+# define SSL_get0_npn_negotiated SSL_get0_next_proto_negotiated
+# endif
+
+__owur int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
+ const unsigned char *in, unsigned int inlen,
+ const unsigned char *client,
+ unsigned int client_len);
+
+# define OPENSSL_NPN_UNSUPPORTED 0
+# define OPENSSL_NPN_NEGOTIATED 1
+# define OPENSSL_NPN_NO_OVERLAP 2
+
+__owur int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
+ unsigned int protos_len);
+__owur int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
+ unsigned int protos_len);
+typedef int (*SSL_CTX_alpn_select_cb_func)(SSL *ssl,
+ const unsigned char **out,
+ unsigned char *outlen,
+ const unsigned char *in,
+ unsigned int inlen,
+ void *arg);
+void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
+ SSL_CTX_alpn_select_cb_func cb,
+ void *arg);
+void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
+ unsigned int *len);
+
+# ifndef OPENSSL_NO_PSK
+/*
+ * the maximum length of the buffer given to callbacks containing the
+ * resulting identity/psk
+ */
+# define PSK_MAX_IDENTITY_LEN 256
+# define PSK_MAX_PSK_LEN 512
+typedef unsigned int (*SSL_psk_client_cb_func)(SSL *ssl,
+ const char *hint,
+ char *identity,
+ unsigned int max_identity_len,
+ unsigned char *psk,
+ unsigned int max_psk_len);
+void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb);
+void SSL_set_psk_client_callback(SSL *ssl, SSL_psk_client_cb_func cb);
+
+typedef unsigned int (*SSL_psk_server_cb_func)(SSL *ssl,
+ const char *identity,
+ unsigned char *psk,
+ unsigned int max_psk_len);
+void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb);
+void SSL_set_psk_server_callback(SSL *ssl, SSL_psk_server_cb_func cb);
+
+__owur int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint);
+__owur int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint);
+const char *SSL_get_psk_identity_hint(const SSL *s);
+const char *SSL_get_psk_identity(const SSL *s);
+# endif
+
+typedef int (*SSL_psk_find_session_cb_func)(SSL *ssl,
+ const unsigned char *identity,
+ size_t identity_len,
+ SSL_SESSION **sess);
+typedef int (*SSL_psk_use_session_cb_func)(SSL *ssl, const EVP_MD *md,
+ const unsigned char **id,
+ size_t *idlen,
+ SSL_SESSION **sess);
+
+void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb);
+void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx,
+ SSL_psk_find_session_cb_func cb);
+void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb);
+void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx,
+ SSL_psk_use_session_cb_func cb);
+
+/* Register callbacks to handle custom TLS Extensions for client or server. */
+
+__owur int SSL_CTX_has_client_custom_ext(const SSL_CTX *ctx,
+ unsigned int ext_type);
+
+__owur int SSL_CTX_add_client_custom_ext(SSL_CTX *ctx,
+ unsigned int ext_type,
+ custom_ext_add_cb add_cb,
+ custom_ext_free_cb free_cb,
+ void *add_arg,
+ custom_ext_parse_cb parse_cb,
+ void *parse_arg);
+
+__owur int SSL_CTX_add_server_custom_ext(SSL_CTX *ctx,
+ unsigned int ext_type,
+ custom_ext_add_cb add_cb,
+ custom_ext_free_cb free_cb,
+ void *add_arg,
+ custom_ext_parse_cb parse_cb,
+ void *parse_arg);
+
+__owur int SSL_CTX_add_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
+ unsigned int context,
+ SSL_custom_ext_add_cb_ex add_cb,
+ SSL_custom_ext_free_cb_ex free_cb,
+ void *add_arg,
+ SSL_custom_ext_parse_cb_ex parse_cb,
+ void *parse_arg);
+
+__owur int SSL_extension_supported(unsigned int ext_type);
+
+# define SSL_NOTHING 1
+# define SSL_WRITING 2
+# define SSL_READING 3
+# define SSL_X509_LOOKUP 4
+# define SSL_ASYNC_PAUSED 5
+# define SSL_ASYNC_NO_JOBS 6
+# define SSL_CLIENT_HELLO_CB 7
+# define SSL_RETRY_VERIFY 8
+
+/* These will only be used when doing non-blocking IO */
+# define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING)
+# define SSL_want_read(s) (SSL_want(s) == SSL_READING)
+# define SSL_want_write(s) (SSL_want(s) == SSL_WRITING)
+# define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP)
+# define SSL_want_retry_verify(s) (SSL_want(s) == SSL_RETRY_VERIFY)
+# define SSL_want_async(s) (SSL_want(s) == SSL_ASYNC_PAUSED)
+# define SSL_want_async_job(s) (SSL_want(s) == SSL_ASYNC_NO_JOBS)
+# define SSL_want_client_hello_cb(s) (SSL_want(s) == SSL_CLIENT_HELLO_CB)
+
+# define SSL_MAC_FLAG_READ_MAC_STREAM 1
+# define SSL_MAC_FLAG_WRITE_MAC_STREAM 2
+# define SSL_MAC_FLAG_READ_MAC_TLSTREE 4
+# define SSL_MAC_FLAG_WRITE_MAC_TLSTREE 8
+
+/*
+ * A callback for logging out TLS key material. This callback should log out
+ * |line| followed by a newline.
+ */
+typedef void (*SSL_CTX_keylog_cb_func)(const SSL *ssl, const char *line);
+
+/*
+ * SSL_CTX_set_keylog_callback configures a callback to log key material. This
+ * is intended for debugging use with tools like Wireshark. The cb function
+ * should log line followed by a newline.
+ */
+void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb);
+
+/*
+ * SSL_CTX_get_keylog_callback returns the callback configured by
+ * SSL_CTX_set_keylog_callback.
+ */
+SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx);
+
+int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data);
+uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx);
+int SSL_set_max_early_data(SSL *s, uint32_t max_early_data);
+uint32_t SSL_get_max_early_data(const SSL *s);
+int SSL_CTX_set_recv_max_early_data(SSL_CTX *ctx, uint32_t recv_max_early_data);
+uint32_t SSL_CTX_get_recv_max_early_data(const SSL_CTX *ctx);
+int SSL_set_recv_max_early_data(SSL *s, uint32_t recv_max_early_data);
+uint32_t SSL_get_recv_max_early_data(const SSL *s);
+
+#ifdef __cplusplus
+}
+#endif
+
+# include <openssl/ssl2.h>
+# include <openssl/ssl3.h>
+# include <openssl/tls1.h> /* This is mostly sslv3 with a few tweaks */
+# include <openssl/dtls1.h> /* Datagram TLS */
+# include <openssl/srtp.h> /* Support for the use_srtp extension */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * These need to be after the above set of includes due to a compiler bug
+ * in VisualStudio 2015
+ */
+SKM_DEFINE_STACK_OF_INTERNAL(SSL_CIPHER, const SSL_CIPHER, SSL_CIPHER)
+#define sk_SSL_CIPHER_num(sk) OPENSSL_sk_num(ossl_check_const_SSL_CIPHER_sk_type(sk))
+#define sk_SSL_CIPHER_value(sk, idx) ((const SSL_CIPHER *)OPENSSL_sk_value(ossl_check_const_SSL_CIPHER_sk_type(sk), (idx)))
+#define sk_SSL_CIPHER_new(cmp) ((STACK_OF(SSL_CIPHER) *)OPENSSL_sk_new(ossl_check_SSL_CIPHER_compfunc_type(cmp)))
+#define sk_SSL_CIPHER_new_null() ((STACK_OF(SSL_CIPHER) *)OPENSSL_sk_new_null())
+#define sk_SSL_CIPHER_new_reserve(cmp, n) ((STACK_OF(SSL_CIPHER) *)OPENSSL_sk_new_reserve(ossl_check_SSL_CIPHER_compfunc_type(cmp), (n)))
+#define sk_SSL_CIPHER_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SSL_CIPHER_sk_type(sk), (n))
+#define sk_SSL_CIPHER_free(sk) OPENSSL_sk_free(ossl_check_SSL_CIPHER_sk_type(sk))
+#define sk_SSL_CIPHER_zero(sk) OPENSSL_sk_zero(ossl_check_SSL_CIPHER_sk_type(sk))
+#define sk_SSL_CIPHER_delete(sk, i) ((const SSL_CIPHER *)OPENSSL_sk_delete(ossl_check_SSL_CIPHER_sk_type(sk), (i)))
+#define sk_SSL_CIPHER_delete_ptr(sk, ptr) ((const SSL_CIPHER *)OPENSSL_sk_delete_ptr(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_type(ptr)))
+#define sk_SSL_CIPHER_push(sk, ptr) OPENSSL_sk_push(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_type(ptr))
+#define sk_SSL_CIPHER_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_type(ptr))
+#define sk_SSL_CIPHER_pop(sk) ((const SSL_CIPHER *)OPENSSL_sk_pop(ossl_check_SSL_CIPHER_sk_type(sk)))
+#define sk_SSL_CIPHER_shift(sk) ((const SSL_CIPHER *)OPENSSL_sk_shift(ossl_check_SSL_CIPHER_sk_type(sk)))
+#define sk_SSL_CIPHER_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SSL_CIPHER_sk_type(sk),ossl_check_SSL_CIPHER_freefunc_type(freefunc))
+#define sk_SSL_CIPHER_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_type(ptr), (idx))
+#define sk_SSL_CIPHER_set(sk, idx, ptr) ((const SSL_CIPHER *)OPENSSL_sk_set(ossl_check_SSL_CIPHER_sk_type(sk), (idx), ossl_check_SSL_CIPHER_type(ptr)))
+#define sk_SSL_CIPHER_find(sk, ptr) OPENSSL_sk_find(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_type(ptr))
+#define sk_SSL_CIPHER_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_type(ptr))
+#define sk_SSL_CIPHER_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_type(ptr), pnum)
+#define sk_SSL_CIPHER_sort(sk) OPENSSL_sk_sort(ossl_check_SSL_CIPHER_sk_type(sk))
+#define sk_SSL_CIPHER_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SSL_CIPHER_sk_type(sk))
+#define sk_SSL_CIPHER_dup(sk) ((STACK_OF(SSL_CIPHER) *)OPENSSL_sk_dup(ossl_check_const_SSL_CIPHER_sk_type(sk)))
+#define sk_SSL_CIPHER_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SSL_CIPHER) *)OPENSSL_sk_deep_copy(ossl_check_const_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_copyfunc_type(copyfunc), ossl_check_SSL_CIPHER_freefunc_type(freefunc)))
+#define sk_SSL_CIPHER_set_cmp_func(sk, cmp) ((sk_SSL_CIPHER_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SSL_CIPHER_sk_type(sk), ossl_check_SSL_CIPHER_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(SSL_COMP, SSL_COMP, SSL_COMP)
+#define sk_SSL_COMP_num(sk) OPENSSL_sk_num(ossl_check_const_SSL_COMP_sk_type(sk))
+#define sk_SSL_COMP_value(sk, idx) ((SSL_COMP *)OPENSSL_sk_value(ossl_check_const_SSL_COMP_sk_type(sk), (idx)))
+#define sk_SSL_COMP_new(cmp) ((STACK_OF(SSL_COMP) *)OPENSSL_sk_new(ossl_check_SSL_COMP_compfunc_type(cmp)))
+#define sk_SSL_COMP_new_null() ((STACK_OF(SSL_COMP) *)OPENSSL_sk_new_null())
+#define sk_SSL_COMP_new_reserve(cmp, n) ((STACK_OF(SSL_COMP) *)OPENSSL_sk_new_reserve(ossl_check_SSL_COMP_compfunc_type(cmp), (n)))
+#define sk_SSL_COMP_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SSL_COMP_sk_type(sk), (n))
+#define sk_SSL_COMP_free(sk) OPENSSL_sk_free(ossl_check_SSL_COMP_sk_type(sk))
+#define sk_SSL_COMP_zero(sk) OPENSSL_sk_zero(ossl_check_SSL_COMP_sk_type(sk))
+#define sk_SSL_COMP_delete(sk, i) ((SSL_COMP *)OPENSSL_sk_delete(ossl_check_SSL_COMP_sk_type(sk), (i)))
+#define sk_SSL_COMP_delete_ptr(sk, ptr) ((SSL_COMP *)OPENSSL_sk_delete_ptr(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_type(ptr)))
+#define sk_SSL_COMP_push(sk, ptr) OPENSSL_sk_push(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_type(ptr))
+#define sk_SSL_COMP_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_type(ptr))
+#define sk_SSL_COMP_pop(sk) ((SSL_COMP *)OPENSSL_sk_pop(ossl_check_SSL_COMP_sk_type(sk)))
+#define sk_SSL_COMP_shift(sk) ((SSL_COMP *)OPENSSL_sk_shift(ossl_check_SSL_COMP_sk_type(sk)))
+#define sk_SSL_COMP_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SSL_COMP_sk_type(sk),ossl_check_SSL_COMP_freefunc_type(freefunc))
+#define sk_SSL_COMP_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_type(ptr), (idx))
+#define sk_SSL_COMP_set(sk, idx, ptr) ((SSL_COMP *)OPENSSL_sk_set(ossl_check_SSL_COMP_sk_type(sk), (idx), ossl_check_SSL_COMP_type(ptr)))
+#define sk_SSL_COMP_find(sk, ptr) OPENSSL_sk_find(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_type(ptr))
+#define sk_SSL_COMP_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_type(ptr))
+#define sk_SSL_COMP_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_type(ptr), pnum)
+#define sk_SSL_COMP_sort(sk) OPENSSL_sk_sort(ossl_check_SSL_COMP_sk_type(sk))
+#define sk_SSL_COMP_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SSL_COMP_sk_type(sk))
+#define sk_SSL_COMP_dup(sk) ((STACK_OF(SSL_COMP) *)OPENSSL_sk_dup(ossl_check_const_SSL_COMP_sk_type(sk)))
+#define sk_SSL_COMP_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SSL_COMP) *)OPENSSL_sk_deep_copy(ossl_check_const_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_copyfunc_type(copyfunc), ossl_check_SSL_COMP_freefunc_type(freefunc)))
+#define sk_SSL_COMP_set_cmp_func(sk, cmp) ((sk_SSL_COMP_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SSL_COMP_sk_type(sk), ossl_check_SSL_COMP_compfunc_type(cmp)))
+
+
+/* compatibility */
+# define SSL_set_app_data(s,arg) (SSL_set_ex_data(s,0,(char *)(arg)))
+# define SSL_get_app_data(s) (SSL_get_ex_data(s,0))
+# define SSL_SESSION_set_app_data(s,a) (SSL_SESSION_set_ex_data(s,0, \
+ (char *)(a)))
+# define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s,0))
+# define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx,0))
+# define SSL_CTX_set_app_data(ctx,arg) (SSL_CTX_set_ex_data(ctx,0, \
+ (char *)(arg)))
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void SSL_set_debug(SSL *s, int debug);
+# endif
+
+/* TLSv1.3 KeyUpdate message types */
+/* -1 used so that this is an invalid value for the on-the-wire protocol */
+#define SSL_KEY_UPDATE_NONE -1
+/* Values as defined for the on-the-wire protocol */
+#define SSL_KEY_UPDATE_NOT_REQUESTED 0
+#define SSL_KEY_UPDATE_REQUESTED 1
+
+/*
+ * The valid handshake states (one for each type message sent and one for each
+ * type of message received). There are also two "special" states:
+ * TLS = TLS or DTLS state
+ * DTLS = DTLS specific state
+ * CR/SR = Client Read/Server Read
+ * CW/SW = Client Write/Server Write
+ *
+ * The "special" states are:
+ * TLS_ST_BEFORE = No handshake has been initiated yet
+ * TLS_ST_OK = A handshake has been successfully completed
+ */
+typedef enum {
+ TLS_ST_BEFORE,
+ TLS_ST_OK,
+ DTLS_ST_CR_HELLO_VERIFY_REQUEST,
+ TLS_ST_CR_SRVR_HELLO,
+ TLS_ST_CR_CERT,
+ TLS_ST_CR_CERT_STATUS,
+ TLS_ST_CR_KEY_EXCH,
+ TLS_ST_CR_CERT_REQ,
+ TLS_ST_CR_SRVR_DONE,
+ TLS_ST_CR_SESSION_TICKET,
+ TLS_ST_CR_CHANGE,
+ TLS_ST_CR_FINISHED,
+ TLS_ST_CW_CLNT_HELLO,
+ TLS_ST_CW_CERT,
+ TLS_ST_CW_KEY_EXCH,
+ TLS_ST_CW_CERT_VRFY,
+ TLS_ST_CW_CHANGE,
+ TLS_ST_CW_NEXT_PROTO,
+ TLS_ST_CW_FINISHED,
+ TLS_ST_SW_HELLO_REQ,
+ TLS_ST_SR_CLNT_HELLO,
+ DTLS_ST_SW_HELLO_VERIFY_REQUEST,
+ TLS_ST_SW_SRVR_HELLO,
+ TLS_ST_SW_CERT,
+ TLS_ST_SW_KEY_EXCH,
+ TLS_ST_SW_CERT_REQ,
+ TLS_ST_SW_SRVR_DONE,
+ TLS_ST_SR_CERT,
+ TLS_ST_SR_KEY_EXCH,
+ TLS_ST_SR_CERT_VRFY,
+ TLS_ST_SR_NEXT_PROTO,
+ TLS_ST_SR_CHANGE,
+ TLS_ST_SR_FINISHED,
+ TLS_ST_SW_SESSION_TICKET,
+ TLS_ST_SW_CERT_STATUS,
+ TLS_ST_SW_CHANGE,
+ TLS_ST_SW_FINISHED,
+ TLS_ST_SW_ENCRYPTED_EXTENSIONS,
+ TLS_ST_CR_ENCRYPTED_EXTENSIONS,
+ TLS_ST_CR_CERT_VRFY,
+ TLS_ST_SW_CERT_VRFY,
+ TLS_ST_CR_HELLO_REQ,
+ TLS_ST_SW_KEY_UPDATE,
+ TLS_ST_CW_KEY_UPDATE,
+ TLS_ST_SR_KEY_UPDATE,
+ TLS_ST_CR_KEY_UPDATE,
+ TLS_ST_EARLY_DATA,
+ TLS_ST_PENDING_EARLY_DATA_END,
+ TLS_ST_CW_END_OF_EARLY_DATA,
+ TLS_ST_SR_END_OF_EARLY_DATA
+} OSSL_HANDSHAKE_STATE;
+
+/*
+ * Most of the following state values are no longer used and are defined to be
+ * the closest equivalent value in the current state machine code. Not all
+ * defines have an equivalent and are set to a dummy value (-1). SSL_ST_CONNECT
+ * and SSL_ST_ACCEPT are still in use in the definition of SSL_CB_ACCEPT_LOOP,
+ * SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP and SSL_CB_CONNECT_EXIT.
+ */
+
+# define SSL_ST_CONNECT 0x1000
+# define SSL_ST_ACCEPT 0x2000
+
+# define SSL_ST_MASK 0x0FFF
+
+# define SSL_CB_LOOP 0x01
+# define SSL_CB_EXIT 0x02
+# define SSL_CB_READ 0x04
+# define SSL_CB_WRITE 0x08
+# define SSL_CB_ALERT 0x4000/* used in callback */
+# define SSL_CB_READ_ALERT (SSL_CB_ALERT|SSL_CB_READ)
+# define SSL_CB_WRITE_ALERT (SSL_CB_ALERT|SSL_CB_WRITE)
+# define SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT|SSL_CB_LOOP)
+# define SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT|SSL_CB_EXIT)
+# define SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT|SSL_CB_LOOP)
+# define SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT|SSL_CB_EXIT)
+# define SSL_CB_HANDSHAKE_START 0x10
+# define SSL_CB_HANDSHAKE_DONE 0x20
+
+/* Is the SSL_connection established? */
+# define SSL_in_connect_init(a) (SSL_in_init(a) && !SSL_is_server(a))
+# define SSL_in_accept_init(a) (SSL_in_init(a) && SSL_is_server(a))
+int SSL_in_init(const SSL *s);
+int SSL_in_before(const SSL *s);
+int SSL_is_init_finished(const SSL *s);
+
+/*
+ * The following 3 states are kept in ssl->rlayer.rstate when reads fail, you
+ * should not need these
+ */
+# define SSL_ST_READ_HEADER 0xF0
+# define SSL_ST_READ_BODY 0xF1
+# define SSL_ST_READ_DONE 0xF2
+
+/*-
+ * Obtain latest Finished message
+ * -- that we sent (SSL_get_finished)
+ * -- that we expected from peer (SSL_get_peer_finished).
+ * Returns length (0 == no Finished so far), copies up to 'count' bytes.
+ */
+size_t SSL_get_finished(const SSL *s, void *buf, size_t count);
+size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count);
+
+/*
+ * use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 3 options are
+ * 'ored' with SSL_VERIFY_PEER if they are desired
+ */
+# define SSL_VERIFY_NONE 0x00
+# define SSL_VERIFY_PEER 0x01
+# define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02
+# define SSL_VERIFY_CLIENT_ONCE 0x04
+# define SSL_VERIFY_POST_HANDSHAKE 0x08
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OpenSSL_add_ssl_algorithms() SSL_library_init()
+# define SSLeay_add_ssl_algorithms() SSL_library_init()
+# endif
+
+/* More backward compatibility */
+# define SSL_get_cipher(s) \
+ SSL_CIPHER_get_name(SSL_get_current_cipher(s))
+# define SSL_get_cipher_bits(s,np) \
+ SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np)
+# define SSL_get_cipher_version(s) \
+ SSL_CIPHER_get_version(SSL_get_current_cipher(s))
+# define SSL_get_cipher_name(s) \
+ SSL_CIPHER_get_name(SSL_get_current_cipher(s))
+# define SSL_get_time(a) SSL_SESSION_get_time(a)
+# define SSL_set_time(a,b) SSL_SESSION_set_time((a),(b))
+# define SSL_get_timeout(a) SSL_SESSION_get_timeout(a)
+# define SSL_set_timeout(a,b) SSL_SESSION_set_timeout((a),(b))
+
+# define d2i_SSL_SESSION_bio(bp,s_id) ASN1_d2i_bio_of(SSL_SESSION,SSL_SESSION_new,d2i_SSL_SESSION,bp,s_id)
+# define i2d_SSL_SESSION_bio(bp,s_id) ASN1_i2d_bio_of(SSL_SESSION,i2d_SSL_SESSION,bp,s_id)
+
+DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION)
+# define SSL_AD_REASON_OFFSET 1000/* offset to get SSL_R_... value
+ * from SSL_AD_... */
+/* These alert types are for SSLv3 and TLSv1 */
+# define SSL_AD_CLOSE_NOTIFY SSL3_AD_CLOSE_NOTIFY
+/* fatal */
+# define SSL_AD_UNEXPECTED_MESSAGE SSL3_AD_UNEXPECTED_MESSAGE
+/* fatal */
+# define SSL_AD_BAD_RECORD_MAC SSL3_AD_BAD_RECORD_MAC
+# define SSL_AD_DECRYPTION_FAILED TLS1_AD_DECRYPTION_FAILED
+# define SSL_AD_RECORD_OVERFLOW TLS1_AD_RECORD_OVERFLOW
+/* fatal */
+# define SSL_AD_DECOMPRESSION_FAILURE SSL3_AD_DECOMPRESSION_FAILURE
+/* fatal */
+# define SSL_AD_HANDSHAKE_FAILURE SSL3_AD_HANDSHAKE_FAILURE
+/* Not for TLS */
+# define SSL_AD_NO_CERTIFICATE SSL3_AD_NO_CERTIFICATE
+# define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE
+# define SSL_AD_UNSUPPORTED_CERTIFICATE SSL3_AD_UNSUPPORTED_CERTIFICATE
+# define SSL_AD_CERTIFICATE_REVOKED SSL3_AD_CERTIFICATE_REVOKED
+# define SSL_AD_CERTIFICATE_EXPIRED SSL3_AD_CERTIFICATE_EXPIRED
+# define SSL_AD_CERTIFICATE_UNKNOWN SSL3_AD_CERTIFICATE_UNKNOWN
+/* fatal */
+# define SSL_AD_ILLEGAL_PARAMETER SSL3_AD_ILLEGAL_PARAMETER
+/* fatal */
+# define SSL_AD_UNKNOWN_CA TLS1_AD_UNKNOWN_CA
+/* fatal */
+# define SSL_AD_ACCESS_DENIED TLS1_AD_ACCESS_DENIED
+/* fatal */
+# define SSL_AD_DECODE_ERROR TLS1_AD_DECODE_ERROR
+# define SSL_AD_DECRYPT_ERROR TLS1_AD_DECRYPT_ERROR
+/* fatal */
+# define SSL_AD_EXPORT_RESTRICTION TLS1_AD_EXPORT_RESTRICTION
+/* fatal */
+# define SSL_AD_PROTOCOL_VERSION TLS1_AD_PROTOCOL_VERSION
+/* fatal */
+# define SSL_AD_INSUFFICIENT_SECURITY TLS1_AD_INSUFFICIENT_SECURITY
+/* fatal */
+# define SSL_AD_INTERNAL_ERROR TLS1_AD_INTERNAL_ERROR
+# define SSL_AD_USER_CANCELLED TLS1_AD_USER_CANCELLED
+# define SSL_AD_NO_RENEGOTIATION TLS1_AD_NO_RENEGOTIATION
+# define SSL_AD_MISSING_EXTENSION TLS13_AD_MISSING_EXTENSION
+# define SSL_AD_CERTIFICATE_REQUIRED TLS13_AD_CERTIFICATE_REQUIRED
+# define SSL_AD_UNSUPPORTED_EXTENSION TLS1_AD_UNSUPPORTED_EXTENSION
+# define SSL_AD_CERTIFICATE_UNOBTAINABLE TLS1_AD_CERTIFICATE_UNOBTAINABLE
+# define SSL_AD_UNRECOGNIZED_NAME TLS1_AD_UNRECOGNIZED_NAME
+# define SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE
+# define SSL_AD_BAD_CERTIFICATE_HASH_VALUE TLS1_AD_BAD_CERTIFICATE_HASH_VALUE
+/* fatal */
+# define SSL_AD_UNKNOWN_PSK_IDENTITY TLS1_AD_UNKNOWN_PSK_IDENTITY
+/* fatal */
+# define SSL_AD_INAPPROPRIATE_FALLBACK TLS1_AD_INAPPROPRIATE_FALLBACK
+# define SSL_AD_NO_APPLICATION_PROTOCOL TLS1_AD_NO_APPLICATION_PROTOCOL
+# define SSL_ERROR_NONE 0
+# define SSL_ERROR_SSL 1
+# define SSL_ERROR_WANT_READ 2
+# define SSL_ERROR_WANT_WRITE 3
+# define SSL_ERROR_WANT_X509_LOOKUP 4
+# define SSL_ERROR_SYSCALL 5/* look at error stack/return
+ * value/errno */
+# define SSL_ERROR_ZERO_RETURN 6
+# define SSL_ERROR_WANT_CONNECT 7
+# define SSL_ERROR_WANT_ACCEPT 8
+# define SSL_ERROR_WANT_ASYNC 9
+# define SSL_ERROR_WANT_ASYNC_JOB 10
+# define SSL_ERROR_WANT_CLIENT_HELLO_CB 11
+# define SSL_ERROR_WANT_RETRY_VERIFY 12
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTRL_SET_TMP_DH 3
+# define SSL_CTRL_SET_TMP_ECDH 4
+# define SSL_CTRL_SET_TMP_DH_CB 6
+# endif
+
+# define SSL_CTRL_GET_CLIENT_CERT_REQUEST 9
+# define SSL_CTRL_GET_NUM_RENEGOTIATIONS 10
+# define SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS 11
+# define SSL_CTRL_GET_TOTAL_RENEGOTIATIONS 12
+# define SSL_CTRL_GET_FLAGS 13
+# define SSL_CTRL_EXTRA_CHAIN_CERT 14
+# define SSL_CTRL_SET_MSG_CALLBACK 15
+# define SSL_CTRL_SET_MSG_CALLBACK_ARG 16
+/* only applies to datagram connections */
+# define SSL_CTRL_SET_MTU 17
+/* Stats */
+# define SSL_CTRL_SESS_NUMBER 20
+# define SSL_CTRL_SESS_CONNECT 21
+# define SSL_CTRL_SESS_CONNECT_GOOD 22
+# define SSL_CTRL_SESS_CONNECT_RENEGOTIATE 23
+# define SSL_CTRL_SESS_ACCEPT 24
+# define SSL_CTRL_SESS_ACCEPT_GOOD 25
+# define SSL_CTRL_SESS_ACCEPT_RENEGOTIATE 26
+# define SSL_CTRL_SESS_HIT 27
+# define SSL_CTRL_SESS_CB_HIT 28
+# define SSL_CTRL_SESS_MISSES 29
+# define SSL_CTRL_SESS_TIMEOUTS 30
+# define SSL_CTRL_SESS_CACHE_FULL 31
+# define SSL_CTRL_MODE 33
+# define SSL_CTRL_GET_READ_AHEAD 40
+# define SSL_CTRL_SET_READ_AHEAD 41
+# define SSL_CTRL_SET_SESS_CACHE_SIZE 42
+# define SSL_CTRL_GET_SESS_CACHE_SIZE 43
+# define SSL_CTRL_SET_SESS_CACHE_MODE 44
+# define SSL_CTRL_GET_SESS_CACHE_MODE 45
+# define SSL_CTRL_GET_MAX_CERT_LIST 50
+# define SSL_CTRL_SET_MAX_CERT_LIST 51
+# define SSL_CTRL_SET_MAX_SEND_FRAGMENT 52
+/* see tls1.h for macros based on these */
+# define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
+# define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
+# define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
+# define SSL_CTRL_SET_TLSEXT_DEBUG_CB 56
+# define SSL_CTRL_SET_TLSEXT_DEBUG_ARG 57
+# define SSL_CTRL_GET_TLSEXT_TICKET_KEYS 58
+# define SSL_CTRL_SET_TLSEXT_TICKET_KEYS 59
+/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT 60 */
+/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB 61 */
+/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG 62 */
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB 63
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG 64
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE 65
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS 66
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS 67
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS 68
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS 69
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP 70
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP 71
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB 72
+# endif
+# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB 75
+# define SSL_CTRL_SET_SRP_VERIFY_PARAM_CB 76
+# define SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB 77
+# define SSL_CTRL_SET_SRP_ARG 78
+# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME 79
+# define SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH 80
+# define SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD 81
+# define DTLS_CTRL_GET_TIMEOUT 73
+# define DTLS_CTRL_HANDLE_TIMEOUT 74
+# define SSL_CTRL_GET_RI_SUPPORT 76
+# define SSL_CTRL_CLEAR_MODE 78
+# define SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB 79
+# define SSL_CTRL_GET_EXTRA_CHAIN_CERTS 82
+# define SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS 83
+# define SSL_CTRL_CHAIN 88
+# define SSL_CTRL_CHAIN_CERT 89
+# define SSL_CTRL_GET_GROUPS 90
+# define SSL_CTRL_SET_GROUPS 91
+# define SSL_CTRL_SET_GROUPS_LIST 92
+# define SSL_CTRL_GET_SHARED_GROUP 93
+# define SSL_CTRL_SET_SIGALGS 97
+# define SSL_CTRL_SET_SIGALGS_LIST 98
+# define SSL_CTRL_CERT_FLAGS 99
+# define SSL_CTRL_CLEAR_CERT_FLAGS 100
+# define SSL_CTRL_SET_CLIENT_SIGALGS 101
+# define SSL_CTRL_SET_CLIENT_SIGALGS_LIST 102
+# define SSL_CTRL_GET_CLIENT_CERT_TYPES 103
+# define SSL_CTRL_SET_CLIENT_CERT_TYPES 104
+# define SSL_CTRL_BUILD_CERT_CHAIN 105
+# define SSL_CTRL_SET_VERIFY_CERT_STORE 106
+# define SSL_CTRL_SET_CHAIN_CERT_STORE 107
+# define SSL_CTRL_GET_PEER_SIGNATURE_NID 108
+# define SSL_CTRL_GET_PEER_TMP_KEY 109
+# define SSL_CTRL_GET_RAW_CIPHERLIST 110
+# define SSL_CTRL_GET_EC_POINT_FORMATS 111
+# define SSL_CTRL_GET_CHAIN_CERTS 115
+# define SSL_CTRL_SELECT_CURRENT_CERT 116
+# define SSL_CTRL_SET_CURRENT_CERT 117
+# define SSL_CTRL_SET_DH_AUTO 118
+# define DTLS_CTRL_SET_LINK_MTU 120
+# define DTLS_CTRL_GET_LINK_MIN_MTU 121
+# define SSL_CTRL_GET_EXTMS_SUPPORT 122
+# define SSL_CTRL_SET_MIN_PROTO_VERSION 123
+# define SSL_CTRL_SET_MAX_PROTO_VERSION 124
+# define SSL_CTRL_SET_SPLIT_SEND_FRAGMENT 125
+# define SSL_CTRL_SET_MAX_PIPELINES 126
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE 127
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB 128
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG 129
+# define SSL_CTRL_GET_MIN_PROTO_VERSION 130
+# define SSL_CTRL_GET_MAX_PROTO_VERSION 131
+# define SSL_CTRL_GET_SIGNATURE_NID 132
+# define SSL_CTRL_GET_TMP_KEY 133
+# define SSL_CTRL_GET_NEGOTIATED_GROUP 134
+# define SSL_CERT_SET_FIRST 1
+# define SSL_CERT_SET_NEXT 2
+# define SSL_CERT_SET_SERVER 3
+# define DTLSv1_get_timeout(ssl, arg) \
+ SSL_ctrl(ssl,DTLS_CTRL_GET_TIMEOUT,0, (void *)(arg))
+# define DTLSv1_handle_timeout(ssl) \
+ SSL_ctrl(ssl,DTLS_CTRL_HANDLE_TIMEOUT,0, NULL)
+# define SSL_num_renegotiations(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_GET_NUM_RENEGOTIATIONS,0,NULL)
+# define SSL_clear_num_renegotiations(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS,0,NULL)
+# define SSL_total_renegotiations(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_GET_TOTAL_RENEGOTIATIONS,0,NULL)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTX_set_tmp_dh(ctx,dh) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH,0,(char *)(dh))
+# endif
+# define SSL_CTX_set_dh_auto(ctx, onoff) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_DH_AUTO,onoff,NULL)
+# define SSL_set_dh_auto(s, onoff) \
+ SSL_ctrl(s,SSL_CTRL_SET_DH_AUTO,onoff,NULL)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_set_tmp_dh(ssl,dh) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH,0,(char *)(dh))
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTX_set_tmp_ecdh(ctx,ecdh) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh))
+# define SSL_set_tmp_ecdh(ssl,ecdh) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh))
+# endif
+# define SSL_CTX_add_extra_chain_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_EXTRA_CHAIN_CERT,0,(char *)(x509))
+# define SSL_CTX_get_extra_chain_certs(ctx,px509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,0,px509)
+# define SSL_CTX_get_extra_chain_certs_only(ctx,px509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,1,px509)
+# define SSL_CTX_clear_extra_chain_certs(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS,0,NULL)
+# define SSL_CTX_set0_chain(ctx,sk) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)(sk))
+# define SSL_CTX_set1_chain(ctx,sk) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)(sk))
+# define SSL_CTX_add0_chain_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)(x509))
+# define SSL_CTX_add1_chain_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)(x509))
+# define SSL_CTX_get0_chain_certs(ctx,px509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
+# define SSL_CTX_clear_chain_certs(ctx) \
+ SSL_CTX_set0_chain(ctx,NULL)
+# define SSL_CTX_build_cert_chain(ctx, flags) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
+# define SSL_CTX_select_current_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509))
+# define SSL_CTX_set_current_cert(ctx, op) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
+# define SSL_CTX_set0_verify_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st))
+# define SSL_CTX_set1_verify_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st))
+# define SSL_CTX_set0_chain_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st))
+# define SSL_CTX_set1_chain_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st))
+# define SSL_set0_chain(s,sk) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN,0,(char *)(sk))
+# define SSL_set1_chain(s,sk) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN,1,(char *)(sk))
+# define SSL_add0_chain_cert(s,x509) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN_CERT,0,(char *)(x509))
+# define SSL_add1_chain_cert(s,x509) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN_CERT,1,(char *)(x509))
+# define SSL_get0_chain_certs(s,px509) \
+ SSL_ctrl(s,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
+# define SSL_clear_chain_certs(s) \
+ SSL_set0_chain(s,NULL)
+# define SSL_build_cert_chain(s, flags) \
+ SSL_ctrl(s,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
+# define SSL_select_current_cert(s,x509) \
+ SSL_ctrl(s,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509))
+# define SSL_set_current_cert(s,op) \
+ SSL_ctrl(s,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
+# define SSL_set0_verify_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st))
+# define SSL_set1_verify_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st))
+# define SSL_set0_chain_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st))
+# define SSL_set1_chain_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st))
+# define SSL_get1_groups(s, glist) \
+ SSL_ctrl(s,SSL_CTRL_GET_GROUPS,0,(int*)(glist))
+# define SSL_CTX_set1_groups(ctx, glist, glistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS,glistlen,(int *)(glist))
+# define SSL_CTX_set1_groups_list(ctx, s) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(s))
+# define SSL_set1_groups(s, glist, glistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_GROUPS,glistlen,(char *)(glist))
+# define SSL_set1_groups_list(s, str) \
+ SSL_ctrl(s,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(str))
+# define SSL_get_shared_group(s, n) \
+ SSL_ctrl(s,SSL_CTRL_GET_SHARED_GROUP,n,NULL)
+# define SSL_get_negotiated_group(s) \
+ SSL_ctrl(s,SSL_CTRL_GET_NEGOTIATED_GROUP,0,NULL)
+# define SSL_CTX_set1_sigalgs(ctx, slist, slistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)(slist))
+# define SSL_CTX_set1_sigalgs_list(ctx, s) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(s))
+# define SSL_set1_sigalgs(s, slist, slistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_SIGALGS,slistlen,(int *)(slist))
+# define SSL_set1_sigalgs_list(s, str) \
+ SSL_ctrl(s,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(str))
+# define SSL_CTX_set1_client_sigalgs(ctx, slist, slistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(int *)(slist))
+# define SSL_CTX_set1_client_sigalgs_list(ctx, s) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(s))
+# define SSL_set1_client_sigalgs(s, slist, slistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(int *)(slist))
+# define SSL_set1_client_sigalgs_list(s, str) \
+ SSL_ctrl(s,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(str))
+# define SSL_get0_certificate_types(s, clist) \
+ SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, (char *)(clist))
+# define SSL_CTX_set1_client_certificate_types(ctx, clist, clistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen, \
+ (char *)(clist))
+# define SSL_set1_client_certificate_types(s, clist, clistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)(clist))
+# define SSL_get_signature_nid(s, pn) \
+ SSL_ctrl(s,SSL_CTRL_GET_SIGNATURE_NID,0,pn)
+# define SSL_get_peer_signature_nid(s, pn) \
+ SSL_ctrl(s,SSL_CTRL_GET_PEER_SIGNATURE_NID,0,pn)
+# define SSL_get_peer_tmp_key(s, pk) \
+ SSL_ctrl(s,SSL_CTRL_GET_PEER_TMP_KEY,0,pk)
+# define SSL_get_tmp_key(s, pk) \
+ SSL_ctrl(s,SSL_CTRL_GET_TMP_KEY,0,pk)
+# define SSL_get0_raw_cipherlist(s, plst) \
+ SSL_ctrl(s,SSL_CTRL_GET_RAW_CIPHERLIST,0,plst)
+# define SSL_get0_ec_point_formats(s, plst) \
+ SSL_ctrl(s,SSL_CTRL_GET_EC_POINT_FORMATS,0,plst)
+# define SSL_CTX_set_min_proto_version(ctx, version) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL)
+# define SSL_CTX_set_max_proto_version(ctx, version) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL)
+# define SSL_CTX_get_min_proto_version(ctx) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL)
+# define SSL_CTX_get_max_proto_version(ctx) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL)
+# define SSL_set_min_proto_version(s, version) \
+ SSL_ctrl(s, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL)
+# define SSL_set_max_proto_version(s, version) \
+ SSL_ctrl(s, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL)
+# define SSL_get_min_proto_version(s) \
+ SSL_ctrl(s, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL)
+# define SSL_get_max_proto_version(s) \
+ SSL_ctrl(s, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL)
+
+const char *SSL_group_to_name(SSL *s, int id);
+
+/* Backwards compatibility, original 1.1.0 names */
+# define SSL_CTRL_GET_SERVER_TMP_KEY \
+ SSL_CTRL_GET_PEER_TMP_KEY
+# define SSL_get_server_tmp_key(s, pk) \
+ SSL_get_peer_tmp_key(s, pk)
+
+int SSL_set0_tmp_dh_pkey(SSL *s, EVP_PKEY *dhpkey);
+int SSL_CTX_set0_tmp_dh_pkey(SSL_CTX *ctx, EVP_PKEY *dhpkey);
+
+/*
+ * The following symbol names are old and obsolete. They are kept
+ * for compatibility reasons only and should not be used anymore.
+ */
+# define SSL_CTRL_GET_CURVES SSL_CTRL_GET_GROUPS
+# define SSL_CTRL_SET_CURVES SSL_CTRL_SET_GROUPS
+# define SSL_CTRL_SET_CURVES_LIST SSL_CTRL_SET_GROUPS_LIST
+# define SSL_CTRL_GET_SHARED_CURVE SSL_CTRL_GET_SHARED_GROUP
+
+# define SSL_get1_curves SSL_get1_groups
+# define SSL_CTX_set1_curves SSL_CTX_set1_groups
+# define SSL_CTX_set1_curves_list SSL_CTX_set1_groups_list
+# define SSL_set1_curves SSL_set1_groups
+# define SSL_set1_curves_list SSL_set1_groups_list
+# define SSL_get_shared_curve SSL_get_shared_group
+
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/* Provide some compatibility macros for removed functionality. */
+# define SSL_CTX_need_tmp_RSA(ctx) 0
+# define SSL_CTX_set_tmp_rsa(ctx,rsa) 1
+# define SSL_need_tmp_RSA(ssl) 0
+# define SSL_set_tmp_rsa(ssl,rsa) 1
+# define SSL_CTX_set_ecdh_auto(dummy, onoff) ((onoff) != 0)
+# define SSL_set_ecdh_auto(dummy, onoff) ((onoff) != 0)
+/*
+ * We "pretend" to call the callback to avoid warnings about unused static
+ * functions.
+ */
+# define SSL_CTX_set_tmp_rsa_callback(ctx, cb) while(0) (cb)(NULL, 0, 0)
+# define SSL_set_tmp_rsa_callback(ssl, cb) while(0) (cb)(NULL, 0, 0)
+# endif
+__owur const BIO_METHOD *BIO_f_ssl(void);
+__owur BIO *BIO_new_ssl(SSL_CTX *ctx, int client);
+__owur BIO *BIO_new_ssl_connect(SSL_CTX *ctx);
+__owur BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx);
+__owur int BIO_ssl_copy_session_id(BIO *to, BIO *from);
+void BIO_ssl_shutdown(BIO *ssl_bio);
+
+__owur int SSL_CTX_set_cipher_list(SSL_CTX *, const char *str);
+__owur SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth);
+__owur SSL_CTX *SSL_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq,
+ const SSL_METHOD *meth);
+int SSL_CTX_up_ref(SSL_CTX *ctx);
+void SSL_CTX_free(SSL_CTX *);
+__owur long SSL_CTX_set_timeout(SSL_CTX *ctx, long t);
+__owur long SSL_CTX_get_timeout(const SSL_CTX *ctx);
+__owur X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *);
+void SSL_CTX_set_cert_store(SSL_CTX *, X509_STORE *);
+void SSL_CTX_set1_cert_store(SSL_CTX *, X509_STORE *);
+__owur int SSL_want(const SSL *s);
+__owur int SSL_clear(SSL *s);
+
+void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm);
+
+__owur const SSL_CIPHER *SSL_get_current_cipher(const SSL *s);
+__owur const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s);
+__owur int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits);
+__owur const char *SSL_CIPHER_get_version(const SSL_CIPHER *c);
+__owur const char *SSL_CIPHER_get_name(const SSL_CIPHER *c);
+__owur const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c);
+__owur const char *OPENSSL_cipher_name(const char *rfc_name);
+__owur uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *c);
+__owur uint16_t SSL_CIPHER_get_protocol_id(const SSL_CIPHER *c);
+__owur int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c);
+__owur int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c);
+__owur const EVP_MD *SSL_CIPHER_get_handshake_digest(const SSL_CIPHER *c);
+__owur int SSL_CIPHER_is_aead(const SSL_CIPHER *c);
+
+__owur int SSL_get_fd(const SSL *s);
+__owur int SSL_get_rfd(const SSL *s);
+__owur int SSL_get_wfd(const SSL *s);
+__owur const char *SSL_get_cipher_list(const SSL *s, int n);
+__owur char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size);
+__owur int SSL_get_read_ahead(const SSL *s);
+__owur int SSL_pending(const SSL *s);
+__owur int SSL_has_pending(const SSL *s);
+# ifndef OPENSSL_NO_SOCK
+__owur int SSL_set_fd(SSL *s, int fd);
+__owur int SSL_set_rfd(SSL *s, int fd);
+__owur int SSL_set_wfd(SSL *s, int fd);
+# endif
+void SSL_set0_rbio(SSL *s, BIO *rbio);
+void SSL_set0_wbio(SSL *s, BIO *wbio);
+void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio);
+__owur BIO *SSL_get_rbio(const SSL *s);
+__owur BIO *SSL_get_wbio(const SSL *s);
+__owur int SSL_set_cipher_list(SSL *s, const char *str);
+__owur int SSL_CTX_set_ciphersuites(SSL_CTX *ctx, const char *str);
+__owur int SSL_set_ciphersuites(SSL *s, const char *str);
+void SSL_set_read_ahead(SSL *s, int yes);
+__owur int SSL_get_verify_mode(const SSL *s);
+__owur int SSL_get_verify_depth(const SSL *s);
+__owur SSL_verify_cb SSL_get_verify_callback(const SSL *s);
+void SSL_set_verify(SSL *s, int mode, SSL_verify_cb callback);
+void SSL_set_verify_depth(SSL *s, int depth);
+void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_use_RSAPrivateKey_ASN1(SSL *ssl,
+ const unsigned char *d, long len);
+# endif
+__owur int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey);
+__owur int SSL_use_PrivateKey_ASN1(int pk, SSL *ssl, const unsigned char *d,
+ long len);
+__owur int SSL_use_certificate(SSL *ssl, X509 *x);
+__owur int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len);
+__owur int SSL_use_cert_and_key(SSL *ssl, X509 *x509, EVP_PKEY *privatekey,
+ STACK_OF(X509) *chain, int override);
+
+
+/* serverinfo file format versions */
+# define SSL_SERVERINFOV1 1
+# define SSL_SERVERINFOV2 2
+
+/* Set serverinfo data for the current active cert. */
+__owur int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo,
+ size_t serverinfo_length);
+__owur int SSL_CTX_use_serverinfo_ex(SSL_CTX *ctx, unsigned int version,
+ const unsigned char *serverinfo,
+ size_t serverinfo_length);
+__owur int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file);
+
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type);
+#endif
+
+__owur int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type);
+__owur int SSL_use_certificate_file(SSL *ssl, const char *file, int type);
+
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file,
+ int type);
+#endif
+__owur int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file,
+ int type);
+__owur int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file,
+ int type);
+/* PEM type */
+__owur int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file);
+__owur int SSL_use_certificate_chain_file(SSL *ssl, const char *file);
+__owur STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file);
+__owur STACK_OF(X509_NAME)
+*SSL_load_client_CA_file_ex(const char *file, OSSL_LIB_CTX *libctx,
+ const char *propq);
+__owur int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
+ const char *file);
+int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
+ const char *dir);
+int SSL_add_store_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
+ const char *uri);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_load_error_strings() \
+ OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS \
+ | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL)
+# endif
+
+__owur const char *SSL_state_string(const SSL *s);
+__owur const char *SSL_rstate_string(const SSL *s);
+__owur const char *SSL_state_string_long(const SSL *s);
+__owur const char *SSL_rstate_string_long(const SSL *s);
+__owur long SSL_SESSION_get_time(const SSL_SESSION *s);
+__owur long SSL_SESSION_set_time(SSL_SESSION *s, long t);
+__owur long SSL_SESSION_get_timeout(const SSL_SESSION *s);
+__owur long SSL_SESSION_set_timeout(SSL_SESSION *s, long t);
+__owur int SSL_SESSION_get_protocol_version(const SSL_SESSION *s);
+__owur int SSL_SESSION_set_protocol_version(SSL_SESSION *s, int version);
+
+__owur const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s);
+__owur int SSL_SESSION_set1_hostname(SSL_SESSION *s, const char *hostname);
+void SSL_SESSION_get0_alpn_selected(const SSL_SESSION *s,
+ const unsigned char **alpn,
+ size_t *len);
+__owur int SSL_SESSION_set1_alpn_selected(SSL_SESSION *s,
+ const unsigned char *alpn,
+ size_t len);
+__owur const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s);
+__owur int SSL_SESSION_set_cipher(SSL_SESSION *s, const SSL_CIPHER *cipher);
+__owur int SSL_SESSION_has_ticket(const SSL_SESSION *s);
+__owur unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s);
+void SSL_SESSION_get0_ticket(const SSL_SESSION *s, const unsigned char **tick,
+ size_t *len);
+__owur uint32_t SSL_SESSION_get_max_early_data(const SSL_SESSION *s);
+__owur int SSL_SESSION_set_max_early_data(SSL_SESSION *s,
+ uint32_t max_early_data);
+__owur int SSL_copy_session_id(SSL *to, const SSL *from);
+__owur X509 *SSL_SESSION_get0_peer(SSL_SESSION *s);
+__owur int SSL_SESSION_set1_id_context(SSL_SESSION *s,
+ const unsigned char *sid_ctx,
+ unsigned int sid_ctx_len);
+__owur int SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
+ unsigned int sid_len);
+__owur int SSL_SESSION_is_resumable(const SSL_SESSION *s);
+
+__owur SSL_SESSION *SSL_SESSION_new(void);
+__owur SSL_SESSION *SSL_SESSION_dup(const SSL_SESSION *src);
+const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
+ unsigned int *len);
+const unsigned char *SSL_SESSION_get0_id_context(const SSL_SESSION *s,
+ unsigned int *len);
+__owur unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s);
+# ifndef OPENSSL_NO_STDIO
+int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *ses);
+# endif
+int SSL_SESSION_print(BIO *fp, const SSL_SESSION *ses);
+int SSL_SESSION_print_keylog(BIO *bp, const SSL_SESSION *x);
+int SSL_SESSION_up_ref(SSL_SESSION *ses);
+void SSL_SESSION_free(SSL_SESSION *ses);
+__owur int i2d_SSL_SESSION(const SSL_SESSION *in, unsigned char **pp);
+__owur int SSL_set_session(SSL *to, SSL_SESSION *session);
+int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *session);
+int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *session);
+__owur int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb);
+__owur int SSL_set_generate_session_id(SSL *s, GEN_SESSION_CB cb);
+__owur int SSL_has_matching_session_id(const SSL *s,
+ const unsigned char *id,
+ unsigned int id_len);
+SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp,
+ long length);
+
+# ifdef OPENSSL_X509_H
+__owur X509 *SSL_get0_peer_certificate(const SSL *s);
+__owur X509 *SSL_get1_peer_certificate(const SSL *s);
+/* Deprecated in 3.0.0 */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_get_peer_certificate SSL_get1_peer_certificate
+# endif
+# endif
+
+__owur STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s);
+
+__owur int SSL_CTX_get_verify_mode(const SSL_CTX *ctx);
+__owur int SSL_CTX_get_verify_depth(const SSL_CTX *ctx);
+__owur SSL_verify_cb SSL_CTX_get_verify_callback(const SSL_CTX *ctx);
+void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb callback);
+void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth);
+void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
+ int (*cb) (X509_STORE_CTX *, void *),
+ void *arg);
+void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg),
+ void *arg);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d,
+ long len);
+# endif
+__owur int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);
+__owur int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx,
+ const unsigned char *d, long len);
+__owur int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);
+__owur int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len,
+ const unsigned char *d);
+__owur int SSL_CTX_use_cert_and_key(SSL_CTX *ctx, X509 *x509, EVP_PKEY *privatekey,
+ STACK_OF(X509) *chain, int override);
+
+void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb);
+void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u);
+pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx);
+void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx);
+void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb);
+void SSL_set_default_passwd_cb_userdata(SSL *s, void *u);
+pem_password_cb *SSL_get_default_passwd_cb(SSL *s);
+void *SSL_get_default_passwd_cb_userdata(SSL *s);
+
+__owur int SSL_CTX_check_private_key(const SSL_CTX *ctx);
+__owur int SSL_check_private_key(const SSL *ctx);
+
+__owur int SSL_CTX_set_session_id_context(SSL_CTX *ctx,
+ const unsigned char *sid_ctx,
+ unsigned int sid_ctx_len);
+
+SSL *SSL_new(SSL_CTX *ctx);
+int SSL_up_ref(SSL *s);
+int SSL_is_dtls(const SSL *s);
+__owur int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
+ unsigned int sid_ctx_len);
+
+__owur int SSL_CTX_set_purpose(SSL_CTX *ctx, int purpose);
+__owur int SSL_set_purpose(SSL *ssl, int purpose);
+__owur int SSL_CTX_set_trust(SSL_CTX *ctx, int trust);
+__owur int SSL_set_trust(SSL *ssl, int trust);
+
+__owur int SSL_set1_host(SSL *s, const char *hostname);
+__owur int SSL_add1_host(SSL *s, const char *hostname);
+__owur const char *SSL_get0_peername(SSL *s);
+void SSL_set_hostflags(SSL *s, unsigned int flags);
+
+__owur int SSL_CTX_dane_enable(SSL_CTX *ctx);
+__owur int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md,
+ uint8_t mtype, uint8_t ord);
+__owur int SSL_dane_enable(SSL *s, const char *basedomain);
+__owur int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
+ uint8_t mtype, const unsigned char *data, size_t dlen);
+__owur int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki);
+__owur int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
+ uint8_t *mtype, const unsigned char **data,
+ size_t *dlen);
+/*
+ * Bridge opacity barrier between libcrypt and libssl, also needed to support
+ * offline testing in test/danetest.c
+ */
+SSL_DANE *SSL_get0_dane(SSL *ssl);
+/*
+ * DANE flags
+ */
+unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags);
+unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags);
+unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags);
+unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags);
+
+__owur int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm);
+__owur int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm);
+
+__owur X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx);
+__owur X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl);
+
+# ifndef OPENSSL_NO_SRP
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_username(SSL_CTX *ctx, char *name);
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_password(SSL_CTX *ctx, char *password);
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_strength(SSL_CTX *ctx, int strength);
+OSSL_DEPRECATEDIN_3_0
+int SSL_CTX_set_srp_client_pwd_callback(SSL_CTX *ctx,
+ char *(*cb) (SSL *, void *));
+OSSL_DEPRECATEDIN_3_0
+int SSL_CTX_set_srp_verify_param_callback(SSL_CTX *ctx,
+ int (*cb) (SSL *, void *));
+OSSL_DEPRECATEDIN_3_0
+int SSL_CTX_set_srp_username_callback(SSL_CTX *ctx,
+ int (*cb) (SSL *, int *, void *));
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_cb_arg(SSL_CTX *ctx, void *arg);
+
+OSSL_DEPRECATEDIN_3_0
+int SSL_set_srp_server_param(SSL *s, const BIGNUM *N, const BIGNUM *g,
+ BIGNUM *sa, BIGNUM *v, char *info);
+OSSL_DEPRECATEDIN_3_0
+int SSL_set_srp_server_param_pw(SSL *s, const char *user, const char *pass,
+ const char *grp);
+
+OSSL_DEPRECATEDIN_3_0 __owur BIGNUM *SSL_get_srp_g(SSL *s);
+OSSL_DEPRECATEDIN_3_0 __owur BIGNUM *SSL_get_srp_N(SSL *s);
+
+OSSL_DEPRECATEDIN_3_0 __owur char *SSL_get_srp_username(SSL *s);
+OSSL_DEPRECATEDIN_3_0 __owur char *SSL_get_srp_userinfo(SSL *s);
+# endif
+# endif
+
+/*
+ * ClientHello callback and helpers.
+ */
+
+# define SSL_CLIENT_HELLO_SUCCESS 1
+# define SSL_CLIENT_HELLO_ERROR 0
+# define SSL_CLIENT_HELLO_RETRY (-1)
+
+typedef int (*SSL_client_hello_cb_fn) (SSL *s, int *al, void *arg);
+void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn cb,
+ void *arg);
+int SSL_client_hello_isv2(SSL *s);
+unsigned int SSL_client_hello_get0_legacy_version(SSL *s);
+size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out);
+size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out);
+size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out);
+size_t SSL_client_hello_get0_compression_methods(SSL *s,
+ const unsigned char **out);
+int SSL_client_hello_get1_extensions_present(SSL *s, int **out, size_t *outlen);
+int SSL_client_hello_get0_ext(SSL *s, unsigned int type,
+ const unsigned char **out, size_t *outlen);
+
+void SSL_certs_clear(SSL *s);
+void SSL_free(SSL *ssl);
+# ifdef OSSL_ASYNC_FD
+/*
+ * Windows application developer has to include windows.h to use these.
+ */
+__owur int SSL_waiting_for_async(SSL *s);
+__owur int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds);
+__owur int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd,
+ size_t *numaddfds, OSSL_ASYNC_FD *delfd,
+ size_t *numdelfds);
+__owur int SSL_CTX_set_async_callback(SSL_CTX *ctx, SSL_async_callback_fn callback);
+__owur int SSL_CTX_set_async_callback_arg(SSL_CTX *ctx, void *arg);
+__owur int SSL_set_async_callback(SSL *s, SSL_async_callback_fn callback);
+__owur int SSL_set_async_callback_arg(SSL *s, void *arg);
+__owur int SSL_get_async_status(SSL *s, int *status);
+
+# endif
+__owur int SSL_accept(SSL *ssl);
+__owur int SSL_stateless(SSL *s);
+__owur int SSL_connect(SSL *ssl);
+__owur int SSL_read(SSL *ssl, void *buf, int num);
+__owur int SSL_read_ex(SSL *ssl, void *buf, size_t num, size_t *readbytes);
+
+# define SSL_READ_EARLY_DATA_ERROR 0
+# define SSL_READ_EARLY_DATA_SUCCESS 1
+# define SSL_READ_EARLY_DATA_FINISH 2
+
+__owur int SSL_read_early_data(SSL *s, void *buf, size_t num,
+ size_t *readbytes);
+__owur int SSL_peek(SSL *ssl, void *buf, int num);
+__owur int SSL_peek_ex(SSL *ssl, void *buf, size_t num, size_t *readbytes);
+__owur ossl_ssize_t SSL_sendfile(SSL *s, int fd, off_t offset, size_t size,
+ int flags);
+__owur int SSL_write(SSL *ssl, const void *buf, int num);
+__owur int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written);
+__owur int SSL_write_early_data(SSL *s, const void *buf, size_t num,
+ size_t *written);
+long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg);
+long SSL_callback_ctrl(SSL *, int, void (*)(void));
+long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg);
+long SSL_CTX_callback_ctrl(SSL_CTX *, int, void (*)(void));
+
+# define SSL_EARLY_DATA_NOT_SENT 0
+# define SSL_EARLY_DATA_REJECTED 1
+# define SSL_EARLY_DATA_ACCEPTED 2
+
+__owur int SSL_get_early_data_status(const SSL *s);
+
+__owur int SSL_get_error(const SSL *s, int ret_code);
+__owur const char *SSL_get_version(const SSL *s);
+
+/* This sets the 'default' SSL version that SSL_new() will create */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth);
+# endif
+
+# ifndef OPENSSL_NO_SSL3_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *SSLv3_method(void); /* SSLv3 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *SSLv3_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *SSLv3_client_method(void);
+# endif
+# endif
+
+#define SSLv23_method TLS_method
+#define SSLv23_server_method TLS_server_method
+#define SSLv23_client_method TLS_client_method
+
+/* Negotiate highest available SSL/TLS version */
+__owur const SSL_METHOD *TLS_method(void);
+__owur const SSL_METHOD *TLS_server_method(void);
+__owur const SSL_METHOD *TLS_client_method(void);
+
+# ifndef OPENSSL_NO_TLS1_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_method(void); /* TLSv1.0 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_TLS1_1_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_1_method(void); /* TLSv1.1 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_1_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_1_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_TLS1_2_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_2_method(void); /* TLSv1.2 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_2_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_2_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DTLS1_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_method(void); /* DTLSv1.0 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DTLS1_2_METHOD
+/* DTLSv1.2 */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_2_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_2_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_2_client_method(void);
+# endif
+# endif
+
+__owur const SSL_METHOD *DTLS_method(void); /* DTLS 1.0 and 1.2 */
+__owur const SSL_METHOD *DTLS_server_method(void); /* DTLS 1.0 and 1.2 */
+__owur const SSL_METHOD *DTLS_client_method(void); /* DTLS 1.0 and 1.2 */
+
+__owur size_t DTLS_get_data_mtu(const SSL *s);
+
+__owur STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s);
+__owur STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx);
+__owur STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s);
+__owur STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s);
+
+__owur int SSL_do_handshake(SSL *s);
+int SSL_key_update(SSL *s, int updatetype);
+int SSL_get_key_update_type(const SSL *s);
+int SSL_renegotiate(SSL *s);
+int SSL_renegotiate_abbreviated(SSL *s);
+__owur int SSL_renegotiate_pending(const SSL *s);
+int SSL_new_session_ticket(SSL *s);
+int SSL_shutdown(SSL *s);
+__owur int SSL_verify_client_post_handshake(SSL *s);
+void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val);
+void SSL_set_post_handshake_auth(SSL *s, int val);
+
+__owur const SSL_METHOD *SSL_CTX_get_ssl_method(const SSL_CTX *ctx);
+__owur const SSL_METHOD *SSL_get_ssl_method(const SSL *s);
+__owur int SSL_set_ssl_method(SSL *s, const SSL_METHOD *method);
+__owur const char *SSL_alert_type_string_long(int value);
+__owur const char *SSL_alert_type_string(int value);
+__owur const char *SSL_alert_desc_string_long(int value);
+__owur const char *SSL_alert_desc_string(int value);
+
+void SSL_set0_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list);
+void SSL_CTX_set0_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list);
+__owur const STACK_OF(X509_NAME) *SSL_get0_CA_list(const SSL *s);
+__owur const STACK_OF(X509_NAME) *SSL_CTX_get0_CA_list(const SSL_CTX *ctx);
+__owur int SSL_add1_to_CA_list(SSL *ssl, const X509 *x);
+__owur int SSL_CTX_add1_to_CA_list(SSL_CTX *ctx, const X509 *x);
+__owur const STACK_OF(X509_NAME) *SSL_get0_peer_CA_list(const SSL *s);
+
+void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list);
+void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list);
+__owur STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s);
+__owur STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *s);
+__owur int SSL_add_client_CA(SSL *ssl, X509 *x);
+__owur int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x);
+
+void SSL_set_connect_state(SSL *s);
+void SSL_set_accept_state(SSL *s);
+
+__owur long SSL_get_default_timeout(const SSL *s);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_library_init() OPENSSL_init_ssl(0, NULL)
+# endif
+
+__owur char *SSL_CIPHER_description(const SSL_CIPHER *, char *buf, int size);
+__owur STACK_OF(X509_NAME) *SSL_dup_CA_list(const STACK_OF(X509_NAME) *sk);
+
+__owur SSL *SSL_dup(SSL *ssl);
+
+__owur X509 *SSL_get_certificate(const SSL *ssl);
+/*
+ * EVP_PKEY
+ */
+struct evp_pkey_st *SSL_get_privatekey(const SSL *ssl);
+
+__owur X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx);
+__owur EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx);
+
+void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode);
+__owur int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx);
+void SSL_set_quiet_shutdown(SSL *ssl, int mode);
+__owur int SSL_get_quiet_shutdown(const SSL *ssl);
+void SSL_set_shutdown(SSL *ssl, int mode);
+__owur int SSL_get_shutdown(const SSL *ssl);
+__owur int SSL_version(const SSL *ssl);
+__owur int SSL_client_version(const SSL *s);
+__owur int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx);
+__owur int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx);
+__owur int SSL_CTX_set_default_verify_file(SSL_CTX *ctx);
+__owur int SSL_CTX_set_default_verify_store(SSL_CTX *ctx);
+__owur int SSL_CTX_load_verify_file(SSL_CTX *ctx, const char *CAfile);
+__owur int SSL_CTX_load_verify_dir(SSL_CTX *ctx, const char *CApath);
+__owur int SSL_CTX_load_verify_store(SSL_CTX *ctx, const char *CAstore);
+__owur int SSL_CTX_load_verify_locations(SSL_CTX *ctx,
+ const char *CAfile,
+ const char *CApath);
+# define SSL_get0_session SSL_get_session/* just peek at pointer */
+__owur SSL_SESSION *SSL_get_session(const SSL *ssl);
+__owur SSL_SESSION *SSL_get1_session(SSL *ssl); /* obtain a reference count */
+__owur SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl);
+SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx);
+void SSL_set_info_callback(SSL *ssl,
+ void (*cb) (const SSL *ssl, int type, int val));
+void (*SSL_get_info_callback(const SSL *ssl)) (const SSL *ssl, int type,
+ int val);
+__owur OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl);
+
+void SSL_set_verify_result(SSL *ssl, long v);
+__owur long SSL_get_verify_result(const SSL *ssl);
+__owur STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s);
+
+__owur size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
+ size_t outlen);
+__owur size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
+ size_t outlen);
+__owur size_t SSL_SESSION_get_master_key(const SSL_SESSION *sess,
+ unsigned char *out, size_t outlen);
+__owur int SSL_SESSION_set1_master_key(SSL_SESSION *sess,
+ const unsigned char *in, size_t len);
+uint8_t SSL_SESSION_get_max_fragment_length(const SSL_SESSION *sess);
+
+#define SSL_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, l, p, newf, dupf, freef)
+__owur int SSL_set_ex_data(SSL *ssl, int idx, void *data);
+void *SSL_get_ex_data(const SSL *ssl, int idx);
+#define SSL_SESSION_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION, l, p, newf, dupf, freef)
+__owur int SSL_SESSION_set_ex_data(SSL_SESSION *ss, int idx, void *data);
+void *SSL_SESSION_get_ex_data(const SSL_SESSION *ss, int idx);
+#define SSL_CTX_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, l, p, newf, dupf, freef)
+__owur int SSL_CTX_set_ex_data(SSL_CTX *ssl, int idx, void *data);
+void *SSL_CTX_get_ex_data(const SSL_CTX *ssl, int idx);
+
+__owur int SSL_get_ex_data_X509_STORE_CTX_idx(void);
+
+# define SSL_CTX_sess_set_cache_size(ctx,t) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_SIZE,t,NULL)
+# define SSL_CTX_sess_get_cache_size(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_SIZE,0,NULL)
+# define SSL_CTX_set_session_cache_mode(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_MODE,m,NULL)
+# define SSL_CTX_get_session_cache_mode(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_MODE,0,NULL)
+
+# define SSL_CTX_get_default_read_ahead(ctx) SSL_CTX_get_read_ahead(ctx)
+# define SSL_CTX_set_default_read_ahead(ctx,m) SSL_CTX_set_read_ahead(ctx,m)
+# define SSL_CTX_get_read_ahead(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_READ_AHEAD,0,NULL)
+# define SSL_CTX_set_read_ahead(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_READ_AHEAD,m,NULL)
+# define SSL_CTX_get_max_cert_list(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
+# define SSL_CTX_set_max_cert_list(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
+# define SSL_get_max_cert_list(ssl) \
+ SSL_ctrl(ssl,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
+# define SSL_set_max_cert_list(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
+
+# define SSL_CTX_set_max_send_fragment(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
+# define SSL_set_max_send_fragment(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
+# define SSL_CTX_set_split_send_fragment(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL)
+# define SSL_set_split_send_fragment(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL)
+# define SSL_CTX_set_max_pipelines(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_PIPELINES,m,NULL)
+# define SSL_set_max_pipelines(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_MAX_PIPELINES,m,NULL)
+
+void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len);
+void SSL_set_default_read_buffer_len(SSL *s, size_t len);
+
+# ifndef OPENSSL_NO_DH
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* NB: the |keylength| is only applicable when is_export is true */
+OSSL_DEPRECATEDIN_3_0
+void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
+ DH *(*dh) (SSL *ssl, int is_export,
+ int keylength));
+OSSL_DEPRECATEDIN_3_0
+void SSL_set_tmp_dh_callback(SSL *ssl,
+ DH *(*dh) (SSL *ssl, int is_export,
+ int keylength));
+# endif
+# endif
+
+__owur const COMP_METHOD *SSL_get_current_compression(const SSL *s);
+__owur const COMP_METHOD *SSL_get_current_expansion(const SSL *s);
+__owur const char *SSL_COMP_get_name(const COMP_METHOD *comp);
+__owur const char *SSL_COMP_get0_name(const SSL_COMP *comp);
+__owur int SSL_COMP_get_id(const SSL_COMP *comp);
+STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void);
+__owur STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP)
+ *meths);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_COMP_free_compression_methods() while(0) continue
+# endif
+__owur int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm);
+
+const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr);
+int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c);
+int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c);
+int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len,
+ int isv2format, STACK_OF(SSL_CIPHER) **sk,
+ STACK_OF(SSL_CIPHER) **scsvs);
+
+/* TLS extensions functions */
+__owur int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len);
+
+__owur int SSL_set_session_ticket_ext_cb(SSL *s,
+ tls_session_ticket_ext_cb_fn cb,
+ void *arg);
+
+/* Pre-shared secret session resumption functions */
+__owur int SSL_set_session_secret_cb(SSL *s,
+ tls_session_secret_cb_fn session_secret_cb,
+ void *arg);
+
+void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
+ int (*cb) (SSL *ssl,
+ int
+ is_forward_secure));
+
+void SSL_set_not_resumable_session_callback(SSL *ssl,
+ int (*cb) (SSL *ssl,
+ int is_forward_secure));
+
+void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
+ size_t (*cb) (SSL *ssl, int type,
+ size_t len, void *arg));
+void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg);
+void *SSL_CTX_get_record_padding_callback_arg(const SSL_CTX *ctx);
+int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size);
+
+int SSL_set_record_padding_callback(SSL *ssl,
+ size_t (*cb) (SSL *ssl, int type,
+ size_t len, void *arg));
+void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg);
+void *SSL_get_record_padding_callback_arg(const SSL *ssl);
+int SSL_set_block_padding(SSL *ssl, size_t block_size);
+
+int SSL_set_num_tickets(SSL *s, size_t num_tickets);
+size_t SSL_get_num_tickets(const SSL *s);
+int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets);
+size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_cache_hit(s) SSL_session_reused(s)
+# endif
+
+__owur int SSL_session_reused(const SSL *s);
+__owur int SSL_is_server(const SSL *s);
+
+__owur __owur SSL_CONF_CTX *SSL_CONF_CTX_new(void);
+int SSL_CONF_CTX_finish(SSL_CONF_CTX *cctx);
+void SSL_CONF_CTX_free(SSL_CONF_CTX *cctx);
+unsigned int SSL_CONF_CTX_set_flags(SSL_CONF_CTX *cctx, unsigned int flags);
+__owur unsigned int SSL_CONF_CTX_clear_flags(SSL_CONF_CTX *cctx,
+ unsigned int flags);
+__owur int SSL_CONF_CTX_set1_prefix(SSL_CONF_CTX *cctx, const char *pre);
+
+void SSL_CONF_CTX_set_ssl(SSL_CONF_CTX *cctx, SSL *ssl);
+void SSL_CONF_CTX_set_ssl_ctx(SSL_CONF_CTX *cctx, SSL_CTX *ctx);
+
+__owur int SSL_CONF_cmd(SSL_CONF_CTX *cctx, const char *cmd, const char *value);
+__owur int SSL_CONF_cmd_argv(SSL_CONF_CTX *cctx, int *pargc, char ***pargv);
+__owur int SSL_CONF_cmd_value_type(SSL_CONF_CTX *cctx, const char *cmd);
+
+void SSL_add_ssl_module(void);
+int SSL_config(SSL *s, const char *name);
+int SSL_CTX_config(SSL_CTX *ctx, const char *name);
+
+# ifndef OPENSSL_NO_SSL_TRACE
+void SSL_trace(int write_p, int version, int content_type,
+ const void *buf, size_t len, SSL *ssl, void *arg);
+# endif
+
+# ifndef OPENSSL_NO_SOCK
+int DTLSv1_listen(SSL *s, BIO_ADDR *client);
+# endif
+
+# ifndef OPENSSL_NO_CT
+
+/*
+ * A callback for verifying that the received SCTs are sufficient.
+ * Expected to return 1 if they are sufficient, otherwise 0.
+ * May return a negative integer if an error occurs.
+ * A connection should be aborted if the SCTs are deemed insufficient.
+ */
+typedef int (*ssl_ct_validation_cb)(const CT_POLICY_EVAL_CTX *ctx,
+ const STACK_OF(SCT) *scts, void *arg);
+
+/*
+ * Sets a |callback| that is invoked upon receipt of ServerHelloDone to validate
+ * the received SCTs.
+ * If the callback returns a non-positive result, the connection is terminated.
+ * Call this function before beginning a handshake.
+ * If a NULL |callback| is provided, SCT validation is disabled.
+ * |arg| is arbitrary userdata that will be passed to the callback whenever it
+ * is invoked. Ownership of |arg| remains with the caller.
+ *
+ * NOTE: A side-effect of setting a CT callback is that an OCSP stapled response
+ * will be requested.
+ */
+int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
+ void *arg);
+int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
+ ssl_ct_validation_cb callback,
+ void *arg);
+#define SSL_disable_ct(s) \
+ ((void) SSL_set_validation_callback((s), NULL, NULL))
+#define SSL_CTX_disable_ct(ctx) \
+ ((void) SSL_CTX_set_validation_callback((ctx), NULL, NULL))
+
+/*
+ * The validation type enumerates the available behaviours of the built-in SSL
+ * CT validation callback selected via SSL_enable_ct() and SSL_CTX_enable_ct().
+ * The underlying callback is a static function in libssl.
+ */
+enum {
+ SSL_CT_VALIDATION_PERMISSIVE = 0,
+ SSL_CT_VALIDATION_STRICT
+};
+
+/*
+ * Enable CT by setting up a callback that implements one of the built-in
+ * validation variants. The SSL_CT_VALIDATION_PERMISSIVE variant always
+ * continues the handshake, the application can make appropriate decisions at
+ * handshake completion. The SSL_CT_VALIDATION_STRICT variant requires at
+ * least one valid SCT, or else handshake termination will be requested. The
+ * handshake may continue anyway if SSL_VERIFY_NONE is in effect.
+ */
+int SSL_enable_ct(SSL *s, int validation_mode);
+int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode);
+
+/*
+ * Report whether a non-NULL callback is enabled.
+ */
+int SSL_ct_is_enabled(const SSL *s);
+int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx);
+
+/* Gets the SCTs received from a connection */
+const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s);
+
+/*
+ * Loads the CT log list from the default location.
+ * If a CTLOG_STORE has previously been set using SSL_CTX_set_ctlog_store,
+ * the log information loaded from this file will be appended to the
+ * CTLOG_STORE.
+ * Returns 1 on success, 0 otherwise.
+ */
+int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx);
+
+/*
+ * Loads the CT log list from the specified file path.
+ * If a CTLOG_STORE has previously been set using SSL_CTX_set_ctlog_store,
+ * the log information loaded from this file will be appended to the
+ * CTLOG_STORE.
+ * Returns 1 on success, 0 otherwise.
+ */
+int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path);
+
+/*
+ * Sets the CT log list used by all SSL connections created from this SSL_CTX.
+ * Ownership of the CTLOG_STORE is transferred to the SSL_CTX.
+ */
+void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE *logs);
+
+/*
+ * Gets the CT log list used by all SSL connections created from this SSL_CTX.
+ * This will be NULL unless one of the following functions has been called:
+ * - SSL_CTX_set_default_ctlog_list_file
+ * - SSL_CTX_set_ctlog_list_file
+ * - SSL_CTX_set_ctlog_store
+ */
+const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx);
+
+# endif /* OPENSSL_NO_CT */
+
+/* What the "other" parameter contains in security callback */
+/* Mask for type */
+# define SSL_SECOP_OTHER_TYPE 0xffff0000
+# define SSL_SECOP_OTHER_NONE 0
+# define SSL_SECOP_OTHER_CIPHER (1 << 16)
+# define SSL_SECOP_OTHER_CURVE (2 << 16)
+# define SSL_SECOP_OTHER_DH (3 << 16)
+# define SSL_SECOP_OTHER_PKEY (4 << 16)
+# define SSL_SECOP_OTHER_SIGALG (5 << 16)
+# define SSL_SECOP_OTHER_CERT (6 << 16)
+
+/* Indicated operation refers to peer key or certificate */
+# define SSL_SECOP_PEER 0x1000
+
+/* Values for "op" parameter in security callback */
+
+/* Called to filter ciphers */
+/* Ciphers client supports */
+# define SSL_SECOP_CIPHER_SUPPORTED (1 | SSL_SECOP_OTHER_CIPHER)
+/* Cipher shared by client/server */
+# define SSL_SECOP_CIPHER_SHARED (2 | SSL_SECOP_OTHER_CIPHER)
+/* Sanity check of cipher server selects */
+# define SSL_SECOP_CIPHER_CHECK (3 | SSL_SECOP_OTHER_CIPHER)
+/* Curves supported by client */
+# define SSL_SECOP_CURVE_SUPPORTED (4 | SSL_SECOP_OTHER_CURVE)
+/* Curves shared by client/server */
+# define SSL_SECOP_CURVE_SHARED (5 | SSL_SECOP_OTHER_CURVE)
+/* Sanity check of curve server selects */
+# define SSL_SECOP_CURVE_CHECK (6 | SSL_SECOP_OTHER_CURVE)
+/* Temporary DH key */
+# define SSL_SECOP_TMP_DH (7 | SSL_SECOP_OTHER_PKEY)
+/* SSL/TLS version */
+# define SSL_SECOP_VERSION (9 | SSL_SECOP_OTHER_NONE)
+/* Session tickets */
+# define SSL_SECOP_TICKET (10 | SSL_SECOP_OTHER_NONE)
+/* Supported signature algorithms sent to peer */
+# define SSL_SECOP_SIGALG_SUPPORTED (11 | SSL_SECOP_OTHER_SIGALG)
+/* Shared signature algorithm */
+# define SSL_SECOP_SIGALG_SHARED (12 | SSL_SECOP_OTHER_SIGALG)
+/* Sanity check signature algorithm allowed */
+# define SSL_SECOP_SIGALG_CHECK (13 | SSL_SECOP_OTHER_SIGALG)
+/* Used to get mask of supported public key signature algorithms */
+# define SSL_SECOP_SIGALG_MASK (14 | SSL_SECOP_OTHER_SIGALG)
+/* Use to see if compression is allowed */
+# define SSL_SECOP_COMPRESSION (15 | SSL_SECOP_OTHER_NONE)
+/* EE key in certificate */
+# define SSL_SECOP_EE_KEY (16 | SSL_SECOP_OTHER_CERT)
+/* CA key in certificate */
+# define SSL_SECOP_CA_KEY (17 | SSL_SECOP_OTHER_CERT)
+/* CA digest algorithm in certificate */
+# define SSL_SECOP_CA_MD (18 | SSL_SECOP_OTHER_CERT)
+/* Peer EE key in certificate */
+# define SSL_SECOP_PEER_EE_KEY (SSL_SECOP_EE_KEY | SSL_SECOP_PEER)
+/* Peer CA key in certificate */
+# define SSL_SECOP_PEER_CA_KEY (SSL_SECOP_CA_KEY | SSL_SECOP_PEER)
+/* Peer CA digest algorithm in certificate */
+# define SSL_SECOP_PEER_CA_MD (SSL_SECOP_CA_MD | SSL_SECOP_PEER)
+
+void SSL_set_security_level(SSL *s, int level);
+__owur int SSL_get_security_level(const SSL *s);
+void SSL_set_security_callback(SSL *s,
+ int (*cb) (const SSL *s, const SSL_CTX *ctx,
+ int op, int bits, int nid,
+ void *other, void *ex));
+int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
+ const SSL_CTX *ctx, int op,
+ int bits, int nid, void *other,
+ void *ex);
+void SSL_set0_security_ex_data(SSL *s, void *ex);
+__owur void *SSL_get0_security_ex_data(const SSL *s);
+
+void SSL_CTX_set_security_level(SSL_CTX *ctx, int level);
+__owur int SSL_CTX_get_security_level(const SSL_CTX *ctx);
+void SSL_CTX_set_security_callback(SSL_CTX *ctx,
+ int (*cb) (const SSL *s, const SSL_CTX *ctx,
+ int op, int bits, int nid,
+ void *other, void *ex));
+int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
+ const SSL_CTX *ctx,
+ int op, int bits,
+ int nid,
+ void *other,
+ void *ex);
+void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex);
+__owur void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx);
+
+/* OPENSSL_INIT flag 0x010000 reserved for internal use */
+# define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
+# define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
+
+# define OPENSSL_INIT_SSL_DEFAULT \
+ (OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS)
+
+int OPENSSL_init_ssl(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings);
+
+# ifndef OPENSSL_NO_UNIT_TEST
+__owur const struct openssl_ssl_test_functions *SSL_test_functions(void);
+# endif
+
+__owur int SSL_free_buffers(SSL *ssl);
+__owur int SSL_alloc_buffers(SSL *ssl);
+
+/* Status codes passed to the decrypt session ticket callback. Some of these
+ * are for internal use only and are never passed to the callback. */
+typedef int SSL_TICKET_STATUS;
+
+/* Support for ticket appdata */
+/* fatal error, malloc failure */
+# define SSL_TICKET_FATAL_ERR_MALLOC 0
+/* fatal error, either from parsing or decrypting the ticket */
+# define SSL_TICKET_FATAL_ERR_OTHER 1
+/* No ticket present */
+# define SSL_TICKET_NONE 2
+/* Empty ticket present */
+# define SSL_TICKET_EMPTY 3
+/* the ticket couldn't be decrypted */
+# define SSL_TICKET_NO_DECRYPT 4
+/* a ticket was successfully decrypted */
+# define SSL_TICKET_SUCCESS 5
+/* same as above but the ticket needs to be renewed */
+# define SSL_TICKET_SUCCESS_RENEW 6
+
+/* Return codes for the decrypt session ticket callback */
+typedef int SSL_TICKET_RETURN;
+
+/* An error occurred */
+#define SSL_TICKET_RETURN_ABORT 0
+/* Do not use the ticket, do not send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_IGNORE 1
+/* Do not use the ticket, send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_IGNORE_RENEW 2
+/* Use the ticket, do not send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_USE 3
+/* Use the ticket, send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_USE_RENEW 4
+
+typedef int (*SSL_CTX_generate_session_ticket_fn)(SSL *s, void *arg);
+typedef SSL_TICKET_RETURN (*SSL_CTX_decrypt_session_ticket_fn)(SSL *s, SSL_SESSION *ss,
+ const unsigned char *keyname,
+ size_t keyname_length,
+ SSL_TICKET_STATUS status,
+ void *arg);
+int SSL_CTX_set_session_ticket_cb(SSL_CTX *ctx,
+ SSL_CTX_generate_session_ticket_fn gen_cb,
+ SSL_CTX_decrypt_session_ticket_fn dec_cb,
+ void *arg);
+int SSL_SESSION_set1_ticket_appdata(SSL_SESSION *ss, const void *data, size_t len);
+int SSL_SESSION_get0_ticket_appdata(SSL_SESSION *ss, void **data, size_t *len);
+
+typedef unsigned int (*DTLS_timer_cb)(SSL *s, unsigned int timer_us);
+
+void DTLS_set_timer_cb(SSL *s, DTLS_timer_cb cb);
+
+
+typedef int (*SSL_allow_early_data_cb_fn)(SSL *s, void *arg);
+void SSL_CTX_set_allow_early_data_cb(SSL_CTX *ctx,
+ SSL_allow_early_data_cb_fn cb,
+ void *arg);
+void SSL_set_allow_early_data_cb(SSL *s,
+ SSL_allow_early_data_cb_fn cb,
+ void *arg);
+
+/* store the default cipher strings inside the library */
+const char *OSSL_default_cipher_list(void);
+const char *OSSL_default_ciphersuites(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/ssl.h.in b/include/openssl/ssl.h.in
new file mode 100644
index 00000000..9c00eb3d
--- /dev/null
+++ b/include/openssl/ssl.h.in
@@ -0,0 +1,2513 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ * Copyright 2005 Nokia. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros generate_const_stack_macros);
+-}
+
+#ifndef OPENSSL_SSL_H
+# define OPENSSL_SSL_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SSL_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/opensslconf.h>
+# include <openssl/comp.h>
+# include <openssl/bio.h>
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/x509.h>
+# include <openssl/crypto.h>
+# include <openssl/buffer.h>
+# endif
+# include <openssl/lhash.h>
+# include <openssl/pem.h>
+# include <openssl/hmac.h>
+# include <openssl/async.h>
+
+# include <openssl/safestack.h>
+# include <openssl/symhacks.h>
+# include <openssl/ct.h>
+# include <openssl/sslerr.h>
+# include <openssl/prov_ssl.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* OpenSSL version number for ASN.1 encoding of the session information */
+/*-
+ * Version 0 - initial version
+ * Version 1 - added the optional peer certificate
+ */
+# define SSL_SESSION_ASN1_VERSION 0x0001
+
+# define SSL_MAX_SSL_SESSION_ID_LENGTH 32
+# define SSL_MAX_SID_CTX_LENGTH 32
+
+# define SSL_MIN_RSA_MODULUS_LENGTH_IN_BYTES (512/8)
+# define SSL_MAX_KEY_ARG_LENGTH 8
+/* SSL_MAX_MASTER_KEY_LENGTH is defined in prov_ssl.h */
+
+/* The maximum number of encrypt/decrypt pipelines we can support */
+# define SSL_MAX_PIPELINES 32
+
+/* text strings for the ciphers */
+
+/* These are used to specify which ciphers to use and not to use */
+
+# define SSL_TXT_LOW "LOW"
+# define SSL_TXT_MEDIUM "MEDIUM"
+# define SSL_TXT_HIGH "HIGH"
+# define SSL_TXT_FIPS "FIPS"
+
+# define SSL_TXT_aNULL "aNULL"
+# define SSL_TXT_eNULL "eNULL"
+# define SSL_TXT_NULL "NULL"
+
+# define SSL_TXT_kRSA "kRSA"
+# define SSL_TXT_kDHr "kDHr"/* this cipher class has been removed */
+# define SSL_TXT_kDHd "kDHd"/* this cipher class has been removed */
+# define SSL_TXT_kDH "kDH"/* this cipher class has been removed */
+# define SSL_TXT_kEDH "kEDH"/* alias for kDHE */
+# define SSL_TXT_kDHE "kDHE"
+# define SSL_TXT_kECDHr "kECDHr"/* this cipher class has been removed */
+# define SSL_TXT_kECDHe "kECDHe"/* this cipher class has been removed */
+# define SSL_TXT_kECDH "kECDH"/* this cipher class has been removed */
+# define SSL_TXT_kEECDH "kEECDH"/* alias for kECDHE */
+# define SSL_TXT_kECDHE "kECDHE"
+# define SSL_TXT_kPSK "kPSK"
+# define SSL_TXT_kRSAPSK "kRSAPSK"
+# define SSL_TXT_kECDHEPSK "kECDHEPSK"
+# define SSL_TXT_kDHEPSK "kDHEPSK"
+# define SSL_TXT_kGOST "kGOST"
+# define SSL_TXT_kGOST18 "kGOST18"
+# define SSL_TXT_kSRP "kSRP"
+
+# define SSL_TXT_aRSA "aRSA"
+# define SSL_TXT_aDSS "aDSS"
+# define SSL_TXT_aDH "aDH"/* this cipher class has been removed */
+# define SSL_TXT_aECDH "aECDH"/* this cipher class has been removed */
+# define SSL_TXT_aECDSA "aECDSA"
+# define SSL_TXT_aPSK "aPSK"
+# define SSL_TXT_aGOST94 "aGOST94"
+# define SSL_TXT_aGOST01 "aGOST01"
+# define SSL_TXT_aGOST12 "aGOST12"
+# define SSL_TXT_aGOST "aGOST"
+# define SSL_TXT_aSRP "aSRP"
+
+# define SSL_TXT_DSS "DSS"
+# define SSL_TXT_DH "DH"
+# define SSL_TXT_DHE "DHE"/* same as "kDHE:-ADH" */
+# define SSL_TXT_EDH "EDH"/* alias for DHE */
+# define SSL_TXT_ADH "ADH"
+# define SSL_TXT_RSA "RSA"
+# define SSL_TXT_ECDH "ECDH"
+# define SSL_TXT_EECDH "EECDH"/* alias for ECDHE" */
+# define SSL_TXT_ECDHE "ECDHE"/* same as "kECDHE:-AECDH" */
+# define SSL_TXT_AECDH "AECDH"
+# define SSL_TXT_ECDSA "ECDSA"
+# define SSL_TXT_PSK "PSK"
+# define SSL_TXT_SRP "SRP"
+
+# define SSL_TXT_DES "DES"
+# define SSL_TXT_3DES "3DES"
+# define SSL_TXT_RC4 "RC4"
+# define SSL_TXT_RC2 "RC2"
+# define SSL_TXT_IDEA "IDEA"
+# define SSL_TXT_SEED "SEED"
+# define SSL_TXT_AES128 "AES128"
+# define SSL_TXT_AES256 "AES256"
+# define SSL_TXT_AES "AES"
+# define SSL_TXT_AES_GCM "AESGCM"
+# define SSL_TXT_AES_CCM "AESCCM"
+# define SSL_TXT_AES_CCM_8 "AESCCM8"
+# define SSL_TXT_CAMELLIA128 "CAMELLIA128"
+# define SSL_TXT_CAMELLIA256 "CAMELLIA256"
+# define SSL_TXT_CAMELLIA "CAMELLIA"
+# define SSL_TXT_CHACHA20 "CHACHA20"
+# define SSL_TXT_GOST "GOST89"
+# define SSL_TXT_ARIA "ARIA"
+# define SSL_TXT_ARIA_GCM "ARIAGCM"
+# define SSL_TXT_ARIA128 "ARIA128"
+# define SSL_TXT_ARIA256 "ARIA256"
+# define SSL_TXT_GOST2012_GOST8912_GOST8912 "GOST2012-GOST8912-GOST8912"
+# define SSL_TXT_CBC "CBC"
+
+# define SSL_TXT_MD5 "MD5"
+# define SSL_TXT_SHA1 "SHA1"
+# define SSL_TXT_SHA "SHA"/* same as "SHA1" */
+# define SSL_TXT_GOST94 "GOST94"
+# define SSL_TXT_GOST89MAC "GOST89MAC"
+# define SSL_TXT_GOST12 "GOST12"
+# define SSL_TXT_GOST89MAC12 "GOST89MAC12"
+# define SSL_TXT_SHA256 "SHA256"
+# define SSL_TXT_SHA384 "SHA384"
+
+# define SSL_TXT_SSLV3 "SSLv3"
+# define SSL_TXT_TLSV1 "TLSv1"
+# define SSL_TXT_TLSV1_1 "TLSv1.1"
+# define SSL_TXT_TLSV1_2 "TLSv1.2"
+
+# define SSL_TXT_ALL "ALL"
+
+/*-
+ * COMPLEMENTOF* definitions. These identifiers are used to (de-select)
+ * ciphers normally not being used.
+ * Example: "RC4" will activate all ciphers using RC4 including ciphers
+ * without authentication, which would normally disabled by DEFAULT (due
+ * the "!ADH" being part of default). Therefore "RC4:!COMPLEMENTOFDEFAULT"
+ * will make sure that it is also disabled in the specific selection.
+ * COMPLEMENTOF* identifiers are portable between version, as adjustments
+ * to the default cipher setup will also be included here.
+ *
+ * COMPLEMENTOFDEFAULT does not experience the same special treatment that
+ * DEFAULT gets, as only selection is being done and no sorting as needed
+ * for DEFAULT.
+ */
+# define SSL_TXT_CMPALL "COMPLEMENTOFALL"
+# define SSL_TXT_CMPDEF "COMPLEMENTOFDEFAULT"
+
+/*
+ * The following cipher list is used by default. It also is substituted when
+ * an application-defined cipher list string starts with 'DEFAULT'.
+ * This applies to ciphersuites for TLSv1.2 and below.
+ * DEPRECATED IN 3.0.0, in favor of OSSL_default_cipher_list()
+ * Update both macro and function simultaneously
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_DEFAULT_CIPHER_LIST "ALL:!COMPLEMENTOFDEFAULT:!eNULL"
+/*
+ * This is the default set of TLSv1.3 ciphersuites
+ * DEPRECATED IN 3.0.0, in favor of OSSL_default_ciphersuites()
+ * Update both macro and function simultaneously
+ */
+# define TLS_DEFAULT_CIPHERSUITES "TLS_AES_256_GCM_SHA384:" \
+ "TLS_CHACHA20_POLY1305_SHA256:" \
+ "TLS_AES_128_GCM_SHA256"
+# endif
+/*
+ * As of OpenSSL 1.0.0, ssl_create_cipher_list() in ssl/ssl_ciph.c always
+ * starts with a reasonable order, and all we have to do for DEFAULT is
+ * throwing out anonymous and unencrypted ciphersuites! (The latter are not
+ * actually enabled by ALL, but "ALL:RSA" would enable some of them.)
+ */
+
+/* Used in SSL_set_shutdown()/SSL_get_shutdown(); */
+# define SSL_SENT_SHUTDOWN 1
+# define SSL_RECEIVED_SHUTDOWN 2
+
+#ifdef __cplusplus
+}
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define SSL_FILETYPE_ASN1 X509_FILETYPE_ASN1
+# define SSL_FILETYPE_PEM X509_FILETYPE_PEM
+
+/*
+ * This is needed to stop compilers complaining about the 'struct ssl_st *'
+ * function parameters used to prototype callbacks in SSL_CTX.
+ */
+typedef struct ssl_st *ssl_crock_st;
+typedef struct tls_session_ticket_ext_st TLS_SESSION_TICKET_EXT;
+typedef struct ssl_method_st SSL_METHOD;
+typedef struct ssl_cipher_st SSL_CIPHER;
+typedef struct ssl_session_st SSL_SESSION;
+typedef struct tls_sigalgs_st TLS_SIGALGS;
+typedef struct ssl_conf_ctx_st SSL_CONF_CTX;
+typedef struct ssl_comp_st SSL_COMP;
+
+STACK_OF(SSL_CIPHER);
+STACK_OF(SSL_COMP);
+
+/* SRTP protection profiles for use with the use_srtp extension (RFC 5764)*/
+typedef struct srtp_protection_profile_st {
+ const char *name;
+ unsigned long id;
+} SRTP_PROTECTION_PROFILE;
+{-
+ generate_stack_macros("SRTP_PROTECTION_PROFILE");
+-}
+
+
+typedef int (*tls_session_ticket_ext_cb_fn)(SSL *s, const unsigned char *data,
+ int len, void *arg);
+typedef int (*tls_session_secret_cb_fn)(SSL *s, void *secret, int *secret_len,
+ STACK_OF(SSL_CIPHER) *peer_ciphers,
+ const SSL_CIPHER **cipher, void *arg);
+
+/* Extension context codes */
+/* This extension is only allowed in TLS */
+#define SSL_EXT_TLS_ONLY 0x0001
+/* This extension is only allowed in DTLS */
+#define SSL_EXT_DTLS_ONLY 0x0002
+/* Some extensions may be allowed in DTLS but we don't implement them for it */
+#define SSL_EXT_TLS_IMPLEMENTATION_ONLY 0x0004
+/* Most extensions are not defined for SSLv3 but EXT_TYPE_renegotiate is */
+#define SSL_EXT_SSL3_ALLOWED 0x0008
+/* Extension is only defined for TLS1.2 and below */
+#define SSL_EXT_TLS1_2_AND_BELOW_ONLY 0x0010
+/* Extension is only defined for TLS1.3 and above */
+#define SSL_EXT_TLS1_3_ONLY 0x0020
+/* Ignore this extension during parsing if we are resuming */
+#define SSL_EXT_IGNORE_ON_RESUMPTION 0x0040
+#define SSL_EXT_CLIENT_HELLO 0x0080
+/* Really means TLS1.2 or below */
+#define SSL_EXT_TLS1_2_SERVER_HELLO 0x0100
+#define SSL_EXT_TLS1_3_SERVER_HELLO 0x0200
+#define SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS 0x0400
+#define SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST 0x0800
+#define SSL_EXT_TLS1_3_CERTIFICATE 0x1000
+#define SSL_EXT_TLS1_3_NEW_SESSION_TICKET 0x2000
+#define SSL_EXT_TLS1_3_CERTIFICATE_REQUEST 0x4000
+
+/* Typedefs for handling custom extensions */
+
+typedef int (*custom_ext_add_cb)(SSL *s, unsigned int ext_type,
+ const unsigned char **out, size_t *outlen,
+ int *al, void *add_arg);
+
+typedef void (*custom_ext_free_cb)(SSL *s, unsigned int ext_type,
+ const unsigned char *out, void *add_arg);
+
+typedef int (*custom_ext_parse_cb)(SSL *s, unsigned int ext_type,
+ const unsigned char *in, size_t inlen,
+ int *al, void *parse_arg);
+
+
+typedef int (*SSL_custom_ext_add_cb_ex)(SSL *s, unsigned int ext_type,
+ unsigned int context,
+ const unsigned char **out,
+ size_t *outlen, X509 *x,
+ size_t chainidx,
+ int *al, void *add_arg);
+
+typedef void (*SSL_custom_ext_free_cb_ex)(SSL *s, unsigned int ext_type,
+ unsigned int context,
+ const unsigned char *out,
+ void *add_arg);
+
+typedef int (*SSL_custom_ext_parse_cb_ex)(SSL *s, unsigned int ext_type,
+ unsigned int context,
+ const unsigned char *in,
+ size_t inlen, X509 *x,
+ size_t chainidx,
+ int *al, void *parse_arg);
+
+/* Typedef for verification callback */
+typedef int (*SSL_verify_cb)(int preverify_ok, X509_STORE_CTX *x509_ctx);
+
+/* Typedef for SSL async callback */
+typedef int (*SSL_async_callback_fn)(SSL *s, void *arg);
+
+#define SSL_OP_BIT(n) ((uint64_t)1 << (uint64_t)n)
+
+/*
+ * SSL/TLS connection options.
+ */
+ /* Disable Extended master secret */
+# define SSL_OP_NO_EXTENDED_MASTER_SECRET SSL_OP_BIT(0)
+ /* Cleanse plaintext copies of data delivered to the application */
+# define SSL_OP_CLEANSE_PLAINTEXT SSL_OP_BIT(1)
+ /* Allow initial connection to servers that don't support RI */
+# define SSL_OP_LEGACY_SERVER_CONNECT SSL_OP_BIT(2)
+ /* Enable support for Kernel TLS */
+# define SSL_OP_ENABLE_KTLS SSL_OP_BIT(3)
+# define SSL_OP_TLSEXT_PADDING SSL_OP_BIT(4)
+# define SSL_OP_SAFARI_ECDHE_ECDSA_BUG SSL_OP_BIT(6)
+# define SSL_OP_IGNORE_UNEXPECTED_EOF SSL_OP_BIT(7)
+# define SSL_OP_ALLOW_CLIENT_RENEGOTIATION SSL_OP_BIT(8)
+# define SSL_OP_DISABLE_TLSEXT_CA_NAMES SSL_OP_BIT(9)
+ /* In TLSv1.3 allow a non-(ec)dhe based kex_mode */
+# define SSL_OP_ALLOW_NO_DHE_KEX SSL_OP_BIT(10)
+ /*
+ * Disable SSL 3.0/TLS 1.0 CBC vulnerability workaround that was added
+ * in OpenSSL 0.9.6d. Usually (depending on the application protocol)
+ * the workaround is not needed. Unfortunately some broken SSL/TLS
+ * implementations cannot handle it at all, which is why we include it
+ * in SSL_OP_ALL. Added in 0.9.6e
+ */
+# define SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS SSL_OP_BIT(11)
+ /* DTLS options */
+# define SSL_OP_NO_QUERY_MTU SSL_OP_BIT(12)
+ /* Turn on Cookie Exchange (on relevant for servers) */
+# define SSL_OP_COOKIE_EXCHANGE SSL_OP_BIT(13)
+ /* Don't use RFC4507 ticket extension */
+# define SSL_OP_NO_TICKET SSL_OP_BIT(14)
+# ifndef OPENSSL_NO_DTLS1_METHOD
+ /*
+ * Use Cisco's version identifier of DTLS_BAD_VER
+ * (only with deprecated DTLSv1_client_method())
+ */
+# define SSL_OP_CISCO_ANYCONNECT SSL_OP_BIT(15)
+# endif
+ /* As server, disallow session resumption on renegotiation */
+# define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION SSL_OP_BIT(16)
+ /* Don't use compression even if supported */
+# define SSL_OP_NO_COMPRESSION SSL_OP_BIT(17)
+ /* Permit unsafe legacy renegotiation */
+# define SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION SSL_OP_BIT(18)
+ /* Disable encrypt-then-mac */
+# define SSL_OP_NO_ENCRYPT_THEN_MAC SSL_OP_BIT(19)
+ /*
+ * Enable TLSv1.3 Compatibility mode. This is on by default. A future
+ * version of OpenSSL may have this disabled by default.
+ */
+# define SSL_OP_ENABLE_MIDDLEBOX_COMPAT SSL_OP_BIT(20)
+ /*
+ * Prioritize Chacha20Poly1305 when client does.
+ * Modifies SSL_OP_CIPHER_SERVER_PREFERENCE
+ */
+# define SSL_OP_PRIORITIZE_CHACHA SSL_OP_BIT(21)
+ /*
+ * Set on servers to choose the cipher according to server's preferences.
+ */
+# define SSL_OP_CIPHER_SERVER_PREFERENCE SSL_OP_BIT(22)
+ /*
+ * If set, a server will allow a client to issue a SSLv3.0 version
+ * number as latest version supported in the premaster secret, even when
+ * TLSv1.0 (version 3.1) was announced in the client hello. Normally
+ * this is forbidden to prevent version rollback attacks.
+ */
+# define SSL_OP_TLS_ROLLBACK_BUG SSL_OP_BIT(23)
+ /*
+ * Switches off automatic TLSv1.3 anti-replay protection for early data.
+ * This is a server-side option only (no effect on the client).
+ */
+# define SSL_OP_NO_ANTI_REPLAY SSL_OP_BIT(24)
+# define SSL_OP_NO_SSLv3 SSL_OP_BIT(25)
+# define SSL_OP_NO_TLSv1 SSL_OP_BIT(26)
+# define SSL_OP_NO_TLSv1_2 SSL_OP_BIT(27)
+# define SSL_OP_NO_TLSv1_1 SSL_OP_BIT(28)
+# define SSL_OP_NO_TLSv1_3 SSL_OP_BIT(29)
+# define SSL_OP_NO_DTLSv1 SSL_OP_BIT(26)
+# define SSL_OP_NO_DTLSv1_2 SSL_OP_BIT(27)
+ /* Disallow all renegotiation */
+# define SSL_OP_NO_RENEGOTIATION SSL_OP_BIT(30)
+ /*
+ * Make server add server-hello extension from early version of
+ * cryptopro draft, when GOST ciphersuite is negotiated. Required for
+ * interoperability with CryptoPro CSP 3.x
+ */
+# define SSL_OP_CRYPTOPRO_TLSEXT_BUG SSL_OP_BIT(31)
+
+/*
+ * Option "collections."
+ */
+# define SSL_OP_NO_SSL_MASK \
+ ( SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1 \
+ | SSL_OP_NO_TLSv1_2 | SSL_OP_NO_TLSv1_3 )
+# define SSL_OP_NO_DTLS_MASK \
+ ( SSL_OP_NO_DTLSv1 | SSL_OP_NO_DTLSv1_2 )
+
+/* Various bug workarounds that should be rather harmless. */
+# define SSL_OP_ALL \
+ ( SSL_OP_CRYPTOPRO_TLSEXT_BUG | SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS \
+ | SSL_OP_TLSEXT_PADDING | SSL_OP_SAFARI_ECDHE_ECDSA_BUG )
+
+/*
+ * OBSOLETE OPTIONS retained for compatibility
+ */
+
+# define SSL_OP_MICROSOFT_SESS_ID_BUG 0x0
+# define SSL_OP_NETSCAPE_CHALLENGE_BUG 0x0
+# define SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG 0x0
+# define SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG 0x0
+# define SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER 0x0
+# define SSL_OP_MSIE_SSLV2_RSA_PADDING 0x0
+# define SSL_OP_SSLEAY_080_CLIENT_DH_BUG 0x0
+# define SSL_OP_TLS_D5_BUG 0x0
+# define SSL_OP_TLS_BLOCK_PADDING_BUG 0x0
+# define SSL_OP_SINGLE_ECDH_USE 0x0
+# define SSL_OP_SINGLE_DH_USE 0x0
+# define SSL_OP_EPHEMERAL_RSA 0x0
+# define SSL_OP_NO_SSLv2 0x0
+# define SSL_OP_PKCS1_CHECK_1 0x0
+# define SSL_OP_PKCS1_CHECK_2 0x0
+# define SSL_OP_NETSCAPE_CA_DN_BUG 0x0
+# define SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG 0x0
+
+/*
+ * Allow SSL_write(..., n) to return r with 0 < r < n (i.e. report success
+ * when just a single record has been written):
+ */
+# define SSL_MODE_ENABLE_PARTIAL_WRITE 0x00000001U
+/*
+ * Make it possible to retry SSL_write() with changed buffer location (buffer
+ * contents must stay the same!); this is not the default to avoid the
+ * misconception that non-blocking SSL_write() behaves like non-blocking
+ * write():
+ */
+# define SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER 0x00000002U
+/*
+ * Never bother the application with retries if the transport is blocking:
+ */
+# define SSL_MODE_AUTO_RETRY 0x00000004U
+/* Don't attempt to automatically build certificate chain */
+# define SSL_MODE_NO_AUTO_CHAIN 0x00000008U
+/*
+ * Save RAM by releasing read and write buffers when they're empty. (SSL3 and
+ * TLS only.) Released buffers are freed.
+ */
+# define SSL_MODE_RELEASE_BUFFERS 0x00000010U
+/*
+ * Send the current time in the Random fields of the ClientHello and
+ * ServerHello records for compatibility with hypothetical implementations
+ * that require it.
+ */
+# define SSL_MODE_SEND_CLIENTHELLO_TIME 0x00000020U
+# define SSL_MODE_SEND_SERVERHELLO_TIME 0x00000040U
+/*
+ * Send TLS_FALLBACK_SCSV in the ClientHello. To be set only by applications
+ * that reconnect with a downgraded protocol version; see
+ * draft-ietf-tls-downgrade-scsv-00 for details. DO NOT ENABLE THIS if your
+ * application attempts a normal handshake. Only use this in explicit
+ * fallback retries, following the guidance in
+ * draft-ietf-tls-downgrade-scsv-00.
+ */
+# define SSL_MODE_SEND_FALLBACK_SCSV 0x00000080U
+/*
+ * Support Asynchronous operation
+ */
+# define SSL_MODE_ASYNC 0x00000100U
+
+/*
+ * When using DTLS/SCTP, include the terminating zero in the label
+ * used for computing the endpoint-pair shared secret. Required for
+ * interoperability with implementations having this bug like these
+ * older version of OpenSSL:
+ * - OpenSSL 1.0.0 series
+ * - OpenSSL 1.0.1 series
+ * - OpenSSL 1.0.2 series
+ * - OpenSSL 1.1.0 series
+ * - OpenSSL 1.1.1 and 1.1.1a
+ */
+# define SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG 0x00000400U
+
+/* Cert related flags */
+/*
+ * Many implementations ignore some aspects of the TLS standards such as
+ * enforcing certificate chain algorithms. When this is set we enforce them.
+ */
+# define SSL_CERT_FLAG_TLS_STRICT 0x00000001U
+
+/* Suite B modes, takes same values as certificate verify flags */
+# define SSL_CERT_FLAG_SUITEB_128_LOS_ONLY 0x10000
+/* Suite B 192 bit only mode */
+# define SSL_CERT_FLAG_SUITEB_192_LOS 0x20000
+/* Suite B 128 bit mode allowing 192 bit algorithms */
+# define SSL_CERT_FLAG_SUITEB_128_LOS 0x30000
+
+/* Perform all sorts of protocol violations for testing purposes */
+# define SSL_CERT_FLAG_BROKEN_PROTOCOL 0x10000000
+
+/* Flags for building certificate chains */
+/* Treat any existing certificates as untrusted CAs */
+# define SSL_BUILD_CHAIN_FLAG_UNTRUSTED 0x1
+/* Don't include root CA in chain */
+# define SSL_BUILD_CHAIN_FLAG_NO_ROOT 0x2
+/* Just check certificates already there */
+# define SSL_BUILD_CHAIN_FLAG_CHECK 0x4
+/* Ignore verification errors */
+# define SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR 0x8
+/* Clear verification errors from queue */
+# define SSL_BUILD_CHAIN_FLAG_CLEAR_ERROR 0x10
+
+/* Flags returned by SSL_check_chain */
+/* Certificate can be used with this session */
+# define CERT_PKEY_VALID 0x1
+/* Certificate can also be used for signing */
+# define CERT_PKEY_SIGN 0x2
+/* EE certificate signing algorithm OK */
+# define CERT_PKEY_EE_SIGNATURE 0x10
+/* CA signature algorithms OK */
+# define CERT_PKEY_CA_SIGNATURE 0x20
+/* EE certificate parameters OK */
+# define CERT_PKEY_EE_PARAM 0x40
+/* CA certificate parameters OK */
+# define CERT_PKEY_CA_PARAM 0x80
+/* Signing explicitly allowed as opposed to SHA1 fallback */
+# define CERT_PKEY_EXPLICIT_SIGN 0x100
+/* Client CA issuer names match (always set for server cert) */
+# define CERT_PKEY_ISSUER_NAME 0x200
+/* Cert type matches client types (always set for server cert) */
+# define CERT_PKEY_CERT_TYPE 0x400
+/* Cert chain suitable to Suite B */
+# define CERT_PKEY_SUITEB 0x800
+
+# define SSL_CONF_FLAG_CMDLINE 0x1
+# define SSL_CONF_FLAG_FILE 0x2
+# define SSL_CONF_FLAG_CLIENT 0x4
+# define SSL_CONF_FLAG_SERVER 0x8
+# define SSL_CONF_FLAG_SHOW_ERRORS 0x10
+# define SSL_CONF_FLAG_CERTIFICATE 0x20
+# define SSL_CONF_FLAG_REQUIRE_PRIVATE 0x40
+/* Configuration value types */
+# define SSL_CONF_TYPE_UNKNOWN 0x0
+# define SSL_CONF_TYPE_STRING 0x1
+# define SSL_CONF_TYPE_FILE 0x2
+# define SSL_CONF_TYPE_DIR 0x3
+# define SSL_CONF_TYPE_NONE 0x4
+# define SSL_CONF_TYPE_STORE 0x5
+
+/* Maximum length of the application-controlled segment of a a TLSv1.3 cookie */
+# define SSL_COOKIE_LENGTH 4096
+
+/*
+ * Note: SSL[_CTX]_set_{options,mode} use |= op on the previous value, they
+ * cannot be used to clear bits.
+ */
+
+uint64_t SSL_CTX_get_options(const SSL_CTX *ctx);
+uint64_t SSL_get_options(const SSL *s);
+uint64_t SSL_CTX_clear_options(SSL_CTX *ctx, uint64_t op);
+uint64_t SSL_clear_options(SSL *s, uint64_t op);
+uint64_t SSL_CTX_set_options(SSL_CTX *ctx, uint64_t op);
+uint64_t SSL_set_options(SSL *s, uint64_t op);
+
+# define SSL_CTX_set_mode(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,(op),NULL)
+# define SSL_CTX_clear_mode(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_MODE,(op),NULL)
+# define SSL_CTX_get_mode(ctx) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_MODE,0,NULL)
+# define SSL_clear_mode(ssl,op) \
+ SSL_ctrl((ssl),SSL_CTRL_CLEAR_MODE,(op),NULL)
+# define SSL_set_mode(ssl,op) \
+ SSL_ctrl((ssl),SSL_CTRL_MODE,(op),NULL)
+# define SSL_get_mode(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_MODE,0,NULL)
+# define SSL_set_mtu(ssl, mtu) \
+ SSL_ctrl((ssl),SSL_CTRL_SET_MTU,(mtu),NULL)
+# define DTLS_set_link_mtu(ssl, mtu) \
+ SSL_ctrl((ssl),DTLS_CTRL_SET_LINK_MTU,(mtu),NULL)
+# define DTLS_get_link_min_mtu(ssl) \
+ SSL_ctrl((ssl),DTLS_CTRL_GET_LINK_MIN_MTU,0,NULL)
+
+# define SSL_get_secure_renegotiation_support(ssl) \
+ SSL_ctrl((ssl), SSL_CTRL_GET_RI_SUPPORT, 0, NULL)
+
+# define SSL_CTX_set_cert_flags(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_CERT_FLAGS,(op),NULL)
+# define SSL_set_cert_flags(s,op) \
+ SSL_ctrl((s),SSL_CTRL_CERT_FLAGS,(op),NULL)
+# define SSL_CTX_clear_cert_flags(ctx,op) \
+ SSL_CTX_ctrl((ctx),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
+# define SSL_clear_cert_flags(s,op) \
+ SSL_ctrl((s),SSL_CTRL_CLEAR_CERT_FLAGS,(op),NULL)
+
+void SSL_CTX_set_msg_callback(SSL_CTX *ctx,
+ void (*cb) (int write_p, int version,
+ int content_type, const void *buf,
+ size_t len, SSL *ssl, void *arg));
+void SSL_set_msg_callback(SSL *ssl,
+ void (*cb) (int write_p, int version,
+ int content_type, const void *buf,
+ size_t len, SSL *ssl, void *arg));
+# define SSL_CTX_set_msg_callback_arg(ctx, arg) SSL_CTX_ctrl((ctx), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
+# define SSL_set_msg_callback_arg(ssl, arg) SSL_ctrl((ssl), SSL_CTRL_SET_MSG_CALLBACK_ARG, 0, (arg))
+
+# define SSL_get_extms_support(s) \
+ SSL_ctrl((s),SSL_CTRL_GET_EXTMS_SUPPORT,0,NULL)
+
+# ifndef OPENSSL_NO_SRP
+/* see tls_srp.c */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_SRP_CTX_init(SSL *s);
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_CTX_SRP_CTX_init(SSL_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 int SSL_SRP_CTX_free(SSL *ctx);
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_SRP_CTX_free(SSL_CTX *ctx);
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_srp_server_param_with_username(SSL *s,
+ int *ad);
+OSSL_DEPRECATEDIN_3_0 __owur int SRP_Calc_A_param(SSL *s);
+# endif
+# endif
+
+/* 100k max cert list */
+# define SSL_MAX_CERT_LIST_DEFAULT (1024*100)
+
+# define SSL_SESSION_CACHE_MAX_SIZE_DEFAULT (1024*20)
+
+/*
+ * This callback type is used inside SSL_CTX, SSL, and in the functions that
+ * set them. It is used to override the generation of SSL/TLS session IDs in
+ * a server. Return value should be zero on an error, non-zero to proceed.
+ * Also, callbacks should themselves check if the id they generate is unique
+ * otherwise the SSL handshake will fail with an error - callbacks can do
+ * this using the 'ssl' value they're passed by;
+ * SSL_has_matching_session_id(ssl, id, *id_len) The length value passed in
+ * is set at the maximum size the session ID can be. In SSLv3/TLSv1 it is 32
+ * bytes. The callback can alter this length to be less if desired. It is
+ * also an error for the callback to set the size to zero.
+ */
+typedef int (*GEN_SESSION_CB) (SSL *ssl, unsigned char *id,
+ unsigned int *id_len);
+
+# define SSL_SESS_CACHE_OFF 0x0000
+# define SSL_SESS_CACHE_CLIENT 0x0001
+# define SSL_SESS_CACHE_SERVER 0x0002
+# define SSL_SESS_CACHE_BOTH (SSL_SESS_CACHE_CLIENT|SSL_SESS_CACHE_SERVER)
+# define SSL_SESS_CACHE_NO_AUTO_CLEAR 0x0080
+/* enough comments already ... see SSL_CTX_set_session_cache_mode(3) */
+# define SSL_SESS_CACHE_NO_INTERNAL_LOOKUP 0x0100
+# define SSL_SESS_CACHE_NO_INTERNAL_STORE 0x0200
+# define SSL_SESS_CACHE_NO_INTERNAL \
+ (SSL_SESS_CACHE_NO_INTERNAL_LOOKUP|SSL_SESS_CACHE_NO_INTERNAL_STORE)
+# define SSL_SESS_CACHE_UPDATE_TIME 0x0400
+
+LHASH_OF(SSL_SESSION) *SSL_CTX_sessions(SSL_CTX *ctx);
+# define SSL_CTX_sess_number(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_NUMBER,0,NULL)
+# define SSL_CTX_sess_connect(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT,0,NULL)
+# define SSL_CTX_sess_connect_good(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_GOOD,0,NULL)
+# define SSL_CTX_sess_connect_renegotiate(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CONNECT_RENEGOTIATE,0,NULL)
+# define SSL_CTX_sess_accept(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT,0,NULL)
+# define SSL_CTX_sess_accept_renegotiate(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_RENEGOTIATE,0,NULL)
+# define SSL_CTX_sess_accept_good(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_ACCEPT_GOOD,0,NULL)
+# define SSL_CTX_sess_hits(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_HIT,0,NULL)
+# define SSL_CTX_sess_cb_hits(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CB_HIT,0,NULL)
+# define SSL_CTX_sess_misses(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_MISSES,0,NULL)
+# define SSL_CTX_sess_timeouts(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_TIMEOUTS,0,NULL)
+# define SSL_CTX_sess_cache_full(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SESS_CACHE_FULL,0,NULL)
+
+void SSL_CTX_sess_set_new_cb(SSL_CTX *ctx,
+ int (*new_session_cb) (struct ssl_st *ssl,
+ SSL_SESSION *sess));
+int (*SSL_CTX_sess_get_new_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
+ SSL_SESSION *sess);
+void SSL_CTX_sess_set_remove_cb(SSL_CTX *ctx,
+ void (*remove_session_cb) (struct ssl_ctx_st
+ *ctx,
+ SSL_SESSION *sess));
+void (*SSL_CTX_sess_get_remove_cb(SSL_CTX *ctx)) (struct ssl_ctx_st *ctx,
+ SSL_SESSION *sess);
+void SSL_CTX_sess_set_get_cb(SSL_CTX *ctx,
+ SSL_SESSION *(*get_session_cb) (struct ssl_st
+ *ssl,
+ const unsigned char
+ *data, int len,
+ int *copy));
+SSL_SESSION *(*SSL_CTX_sess_get_get_cb(SSL_CTX *ctx)) (struct ssl_st *ssl,
+ const unsigned char *data,
+ int len, int *copy);
+void SSL_CTX_set_info_callback(SSL_CTX *ctx,
+ void (*cb) (const SSL *ssl, int type, int val));
+void (*SSL_CTX_get_info_callback(SSL_CTX *ctx)) (const SSL *ssl, int type,
+ int val);
+void SSL_CTX_set_client_cert_cb(SSL_CTX *ctx,
+ int (*client_cert_cb) (SSL *ssl, X509 **x509,
+ EVP_PKEY **pkey));
+int (*SSL_CTX_get_client_cert_cb(SSL_CTX *ctx)) (SSL *ssl, X509 **x509,
+ EVP_PKEY **pkey);
+# ifndef OPENSSL_NO_ENGINE
+__owur int SSL_CTX_set_client_cert_engine(SSL_CTX *ctx, ENGINE *e);
+# endif
+void SSL_CTX_set_cookie_generate_cb(SSL_CTX *ctx,
+ int (*app_gen_cookie_cb) (SSL *ssl,
+ unsigned char
+ *cookie,
+ unsigned int
+ *cookie_len));
+void SSL_CTX_set_cookie_verify_cb(SSL_CTX *ctx,
+ int (*app_verify_cookie_cb) (SSL *ssl,
+ const unsigned
+ char *cookie,
+ unsigned int
+ cookie_len));
+
+void SSL_CTX_set_stateless_cookie_generate_cb(
+ SSL_CTX *ctx,
+ int (*gen_stateless_cookie_cb) (SSL *ssl,
+ unsigned char *cookie,
+ size_t *cookie_len));
+void SSL_CTX_set_stateless_cookie_verify_cb(
+ SSL_CTX *ctx,
+ int (*verify_stateless_cookie_cb) (SSL *ssl,
+ const unsigned char *cookie,
+ size_t cookie_len));
+# ifndef OPENSSL_NO_NEXTPROTONEG
+
+typedef int (*SSL_CTX_npn_advertised_cb_func)(SSL *ssl,
+ const unsigned char **out,
+ unsigned int *outlen,
+ void *arg);
+void SSL_CTX_set_next_protos_advertised_cb(SSL_CTX *s,
+ SSL_CTX_npn_advertised_cb_func cb,
+ void *arg);
+# define SSL_CTX_set_npn_advertised_cb SSL_CTX_set_next_protos_advertised_cb
+
+typedef int (*SSL_CTX_npn_select_cb_func)(SSL *s,
+ unsigned char **out,
+ unsigned char *outlen,
+ const unsigned char *in,
+ unsigned int inlen,
+ void *arg);
+void SSL_CTX_set_next_proto_select_cb(SSL_CTX *s,
+ SSL_CTX_npn_select_cb_func cb,
+ void *arg);
+# define SSL_CTX_set_npn_select_cb SSL_CTX_set_next_proto_select_cb
+
+void SSL_get0_next_proto_negotiated(const SSL *s, const unsigned char **data,
+ unsigned *len);
+# define SSL_get0_npn_negotiated SSL_get0_next_proto_negotiated
+# endif
+
+__owur int SSL_select_next_proto(unsigned char **out, unsigned char *outlen,
+ const unsigned char *in, unsigned int inlen,
+ const unsigned char *client,
+ unsigned int client_len);
+
+# define OPENSSL_NPN_UNSUPPORTED 0
+# define OPENSSL_NPN_NEGOTIATED 1
+# define OPENSSL_NPN_NO_OVERLAP 2
+
+__owur int SSL_CTX_set_alpn_protos(SSL_CTX *ctx, const unsigned char *protos,
+ unsigned int protos_len);
+__owur int SSL_set_alpn_protos(SSL *ssl, const unsigned char *protos,
+ unsigned int protos_len);
+typedef int (*SSL_CTX_alpn_select_cb_func)(SSL *ssl,
+ const unsigned char **out,
+ unsigned char *outlen,
+ const unsigned char *in,
+ unsigned int inlen,
+ void *arg);
+void SSL_CTX_set_alpn_select_cb(SSL_CTX *ctx,
+ SSL_CTX_alpn_select_cb_func cb,
+ void *arg);
+void SSL_get0_alpn_selected(const SSL *ssl, const unsigned char **data,
+ unsigned int *len);
+
+# ifndef OPENSSL_NO_PSK
+/*
+ * the maximum length of the buffer given to callbacks containing the
+ * resulting identity/psk
+ */
+# define PSK_MAX_IDENTITY_LEN 256
+# define PSK_MAX_PSK_LEN 512
+typedef unsigned int (*SSL_psk_client_cb_func)(SSL *ssl,
+ const char *hint,
+ char *identity,
+ unsigned int max_identity_len,
+ unsigned char *psk,
+ unsigned int max_psk_len);
+void SSL_CTX_set_psk_client_callback(SSL_CTX *ctx, SSL_psk_client_cb_func cb);
+void SSL_set_psk_client_callback(SSL *ssl, SSL_psk_client_cb_func cb);
+
+typedef unsigned int (*SSL_psk_server_cb_func)(SSL *ssl,
+ const char *identity,
+ unsigned char *psk,
+ unsigned int max_psk_len);
+void SSL_CTX_set_psk_server_callback(SSL_CTX *ctx, SSL_psk_server_cb_func cb);
+void SSL_set_psk_server_callback(SSL *ssl, SSL_psk_server_cb_func cb);
+
+__owur int SSL_CTX_use_psk_identity_hint(SSL_CTX *ctx, const char *identity_hint);
+__owur int SSL_use_psk_identity_hint(SSL *s, const char *identity_hint);
+const char *SSL_get_psk_identity_hint(const SSL *s);
+const char *SSL_get_psk_identity(const SSL *s);
+# endif
+
+typedef int (*SSL_psk_find_session_cb_func)(SSL *ssl,
+ const unsigned char *identity,
+ size_t identity_len,
+ SSL_SESSION **sess);
+typedef int (*SSL_psk_use_session_cb_func)(SSL *ssl, const EVP_MD *md,
+ const unsigned char **id,
+ size_t *idlen,
+ SSL_SESSION **sess);
+
+void SSL_set_psk_find_session_callback(SSL *s, SSL_psk_find_session_cb_func cb);
+void SSL_CTX_set_psk_find_session_callback(SSL_CTX *ctx,
+ SSL_psk_find_session_cb_func cb);
+void SSL_set_psk_use_session_callback(SSL *s, SSL_psk_use_session_cb_func cb);
+void SSL_CTX_set_psk_use_session_callback(SSL_CTX *ctx,
+ SSL_psk_use_session_cb_func cb);
+
+/* Register callbacks to handle custom TLS Extensions for client or server. */
+
+__owur int SSL_CTX_has_client_custom_ext(const SSL_CTX *ctx,
+ unsigned int ext_type);
+
+__owur int SSL_CTX_add_client_custom_ext(SSL_CTX *ctx,
+ unsigned int ext_type,
+ custom_ext_add_cb add_cb,
+ custom_ext_free_cb free_cb,
+ void *add_arg,
+ custom_ext_parse_cb parse_cb,
+ void *parse_arg);
+
+__owur int SSL_CTX_add_server_custom_ext(SSL_CTX *ctx,
+ unsigned int ext_type,
+ custom_ext_add_cb add_cb,
+ custom_ext_free_cb free_cb,
+ void *add_arg,
+ custom_ext_parse_cb parse_cb,
+ void *parse_arg);
+
+__owur int SSL_CTX_add_custom_ext(SSL_CTX *ctx, unsigned int ext_type,
+ unsigned int context,
+ SSL_custom_ext_add_cb_ex add_cb,
+ SSL_custom_ext_free_cb_ex free_cb,
+ void *add_arg,
+ SSL_custom_ext_parse_cb_ex parse_cb,
+ void *parse_arg);
+
+__owur int SSL_extension_supported(unsigned int ext_type);
+
+# define SSL_NOTHING 1
+# define SSL_WRITING 2
+# define SSL_READING 3
+# define SSL_X509_LOOKUP 4
+# define SSL_ASYNC_PAUSED 5
+# define SSL_ASYNC_NO_JOBS 6
+# define SSL_CLIENT_HELLO_CB 7
+# define SSL_RETRY_VERIFY 8
+
+/* These will only be used when doing non-blocking IO */
+# define SSL_want_nothing(s) (SSL_want(s) == SSL_NOTHING)
+# define SSL_want_read(s) (SSL_want(s) == SSL_READING)
+# define SSL_want_write(s) (SSL_want(s) == SSL_WRITING)
+# define SSL_want_x509_lookup(s) (SSL_want(s) == SSL_X509_LOOKUP)
+# define SSL_want_retry_verify(s) (SSL_want(s) == SSL_RETRY_VERIFY)
+# define SSL_want_async(s) (SSL_want(s) == SSL_ASYNC_PAUSED)
+# define SSL_want_async_job(s) (SSL_want(s) == SSL_ASYNC_NO_JOBS)
+# define SSL_want_client_hello_cb(s) (SSL_want(s) == SSL_CLIENT_HELLO_CB)
+
+# define SSL_MAC_FLAG_READ_MAC_STREAM 1
+# define SSL_MAC_FLAG_WRITE_MAC_STREAM 2
+# define SSL_MAC_FLAG_READ_MAC_TLSTREE 4
+# define SSL_MAC_FLAG_WRITE_MAC_TLSTREE 8
+
+/*
+ * A callback for logging out TLS key material. This callback should log out
+ * |line| followed by a newline.
+ */
+typedef void (*SSL_CTX_keylog_cb_func)(const SSL *ssl, const char *line);
+
+/*
+ * SSL_CTX_set_keylog_callback configures a callback to log key material. This
+ * is intended for debugging use with tools like Wireshark. The cb function
+ * should log line followed by a newline.
+ */
+void SSL_CTX_set_keylog_callback(SSL_CTX *ctx, SSL_CTX_keylog_cb_func cb);
+
+/*
+ * SSL_CTX_get_keylog_callback returns the callback configured by
+ * SSL_CTX_set_keylog_callback.
+ */
+SSL_CTX_keylog_cb_func SSL_CTX_get_keylog_callback(const SSL_CTX *ctx);
+
+int SSL_CTX_set_max_early_data(SSL_CTX *ctx, uint32_t max_early_data);
+uint32_t SSL_CTX_get_max_early_data(const SSL_CTX *ctx);
+int SSL_set_max_early_data(SSL *s, uint32_t max_early_data);
+uint32_t SSL_get_max_early_data(const SSL *s);
+int SSL_CTX_set_recv_max_early_data(SSL_CTX *ctx, uint32_t recv_max_early_data);
+uint32_t SSL_CTX_get_recv_max_early_data(const SSL_CTX *ctx);
+int SSL_set_recv_max_early_data(SSL *s, uint32_t recv_max_early_data);
+uint32_t SSL_get_recv_max_early_data(const SSL *s);
+
+#ifdef __cplusplus
+}
+#endif
+
+# include <openssl/ssl2.h>
+# include <openssl/ssl3.h>
+# include <openssl/tls1.h> /* This is mostly sslv3 with a few tweaks */
+# include <openssl/dtls1.h> /* Datagram TLS */
+# include <openssl/srtp.h> /* Support for the use_srtp extension */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * These need to be after the above set of includes due to a compiler bug
+ * in VisualStudio 2015
+ */
+{-
+ generate_const_stack_macros("SSL_CIPHER")
+ .generate_stack_macros("SSL_COMP");
+-}
+
+/* compatibility */
+# define SSL_set_app_data(s,arg) (SSL_set_ex_data(s,0,(char *)(arg)))
+# define SSL_get_app_data(s) (SSL_get_ex_data(s,0))
+# define SSL_SESSION_set_app_data(s,a) (SSL_SESSION_set_ex_data(s,0, \
+ (char *)(a)))
+# define SSL_SESSION_get_app_data(s) (SSL_SESSION_get_ex_data(s,0))
+# define SSL_CTX_get_app_data(ctx) (SSL_CTX_get_ex_data(ctx,0))
+# define SSL_CTX_set_app_data(ctx,arg) (SSL_CTX_set_ex_data(ctx,0, \
+ (char *)(arg)))
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 void SSL_set_debug(SSL *s, int debug);
+# endif
+
+/* TLSv1.3 KeyUpdate message types */
+/* -1 used so that this is an invalid value for the on-the-wire protocol */
+#define SSL_KEY_UPDATE_NONE -1
+/* Values as defined for the on-the-wire protocol */
+#define SSL_KEY_UPDATE_NOT_REQUESTED 0
+#define SSL_KEY_UPDATE_REQUESTED 1
+
+/*
+ * The valid handshake states (one for each type message sent and one for each
+ * type of message received). There are also two "special" states:
+ * TLS = TLS or DTLS state
+ * DTLS = DTLS specific state
+ * CR/SR = Client Read/Server Read
+ * CW/SW = Client Write/Server Write
+ *
+ * The "special" states are:
+ * TLS_ST_BEFORE = No handshake has been initiated yet
+ * TLS_ST_OK = A handshake has been successfully completed
+ */
+typedef enum {
+ TLS_ST_BEFORE,
+ TLS_ST_OK,
+ DTLS_ST_CR_HELLO_VERIFY_REQUEST,
+ TLS_ST_CR_SRVR_HELLO,
+ TLS_ST_CR_CERT,
+ TLS_ST_CR_CERT_STATUS,
+ TLS_ST_CR_KEY_EXCH,
+ TLS_ST_CR_CERT_REQ,
+ TLS_ST_CR_SRVR_DONE,
+ TLS_ST_CR_SESSION_TICKET,
+ TLS_ST_CR_CHANGE,
+ TLS_ST_CR_FINISHED,
+ TLS_ST_CW_CLNT_HELLO,
+ TLS_ST_CW_CERT,
+ TLS_ST_CW_KEY_EXCH,
+ TLS_ST_CW_CERT_VRFY,
+ TLS_ST_CW_CHANGE,
+ TLS_ST_CW_NEXT_PROTO,
+ TLS_ST_CW_FINISHED,
+ TLS_ST_SW_HELLO_REQ,
+ TLS_ST_SR_CLNT_HELLO,
+ DTLS_ST_SW_HELLO_VERIFY_REQUEST,
+ TLS_ST_SW_SRVR_HELLO,
+ TLS_ST_SW_CERT,
+ TLS_ST_SW_KEY_EXCH,
+ TLS_ST_SW_CERT_REQ,
+ TLS_ST_SW_SRVR_DONE,
+ TLS_ST_SR_CERT,
+ TLS_ST_SR_KEY_EXCH,
+ TLS_ST_SR_CERT_VRFY,
+ TLS_ST_SR_NEXT_PROTO,
+ TLS_ST_SR_CHANGE,
+ TLS_ST_SR_FINISHED,
+ TLS_ST_SW_SESSION_TICKET,
+ TLS_ST_SW_CERT_STATUS,
+ TLS_ST_SW_CHANGE,
+ TLS_ST_SW_FINISHED,
+ TLS_ST_SW_ENCRYPTED_EXTENSIONS,
+ TLS_ST_CR_ENCRYPTED_EXTENSIONS,
+ TLS_ST_CR_CERT_VRFY,
+ TLS_ST_SW_CERT_VRFY,
+ TLS_ST_CR_HELLO_REQ,
+ TLS_ST_SW_KEY_UPDATE,
+ TLS_ST_CW_KEY_UPDATE,
+ TLS_ST_SR_KEY_UPDATE,
+ TLS_ST_CR_KEY_UPDATE,
+ TLS_ST_EARLY_DATA,
+ TLS_ST_PENDING_EARLY_DATA_END,
+ TLS_ST_CW_END_OF_EARLY_DATA,
+ TLS_ST_SR_END_OF_EARLY_DATA
+} OSSL_HANDSHAKE_STATE;
+
+/*
+ * Most of the following state values are no longer used and are defined to be
+ * the closest equivalent value in the current state machine code. Not all
+ * defines have an equivalent and are set to a dummy value (-1). SSL_ST_CONNECT
+ * and SSL_ST_ACCEPT are still in use in the definition of SSL_CB_ACCEPT_LOOP,
+ * SSL_CB_ACCEPT_EXIT, SSL_CB_CONNECT_LOOP and SSL_CB_CONNECT_EXIT.
+ */
+
+# define SSL_ST_CONNECT 0x1000
+# define SSL_ST_ACCEPT 0x2000
+
+# define SSL_ST_MASK 0x0FFF
+
+# define SSL_CB_LOOP 0x01
+# define SSL_CB_EXIT 0x02
+# define SSL_CB_READ 0x04
+# define SSL_CB_WRITE 0x08
+# define SSL_CB_ALERT 0x4000/* used in callback */
+# define SSL_CB_READ_ALERT (SSL_CB_ALERT|SSL_CB_READ)
+# define SSL_CB_WRITE_ALERT (SSL_CB_ALERT|SSL_CB_WRITE)
+# define SSL_CB_ACCEPT_LOOP (SSL_ST_ACCEPT|SSL_CB_LOOP)
+# define SSL_CB_ACCEPT_EXIT (SSL_ST_ACCEPT|SSL_CB_EXIT)
+# define SSL_CB_CONNECT_LOOP (SSL_ST_CONNECT|SSL_CB_LOOP)
+# define SSL_CB_CONNECT_EXIT (SSL_ST_CONNECT|SSL_CB_EXIT)
+# define SSL_CB_HANDSHAKE_START 0x10
+# define SSL_CB_HANDSHAKE_DONE 0x20
+
+/* Is the SSL_connection established? */
+# define SSL_in_connect_init(a) (SSL_in_init(a) && !SSL_is_server(a))
+# define SSL_in_accept_init(a) (SSL_in_init(a) && SSL_is_server(a))
+int SSL_in_init(const SSL *s);
+int SSL_in_before(const SSL *s);
+int SSL_is_init_finished(const SSL *s);
+
+/*
+ * The following 3 states are kept in ssl->rlayer.rstate when reads fail, you
+ * should not need these
+ */
+# define SSL_ST_READ_HEADER 0xF0
+# define SSL_ST_READ_BODY 0xF1
+# define SSL_ST_READ_DONE 0xF2
+
+/*-
+ * Obtain latest Finished message
+ * -- that we sent (SSL_get_finished)
+ * -- that we expected from peer (SSL_get_peer_finished).
+ * Returns length (0 == no Finished so far), copies up to 'count' bytes.
+ */
+size_t SSL_get_finished(const SSL *s, void *buf, size_t count);
+size_t SSL_get_peer_finished(const SSL *s, void *buf, size_t count);
+
+/*
+ * use either SSL_VERIFY_NONE or SSL_VERIFY_PEER, the last 3 options are
+ * 'ored' with SSL_VERIFY_PEER if they are desired
+ */
+# define SSL_VERIFY_NONE 0x00
+# define SSL_VERIFY_PEER 0x01
+# define SSL_VERIFY_FAIL_IF_NO_PEER_CERT 0x02
+# define SSL_VERIFY_CLIENT_ONCE 0x04
+# define SSL_VERIFY_POST_HANDSHAKE 0x08
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define OpenSSL_add_ssl_algorithms() SSL_library_init()
+# define SSLeay_add_ssl_algorithms() SSL_library_init()
+# endif
+
+/* More backward compatibility */
+# define SSL_get_cipher(s) \
+ SSL_CIPHER_get_name(SSL_get_current_cipher(s))
+# define SSL_get_cipher_bits(s,np) \
+ SSL_CIPHER_get_bits(SSL_get_current_cipher(s),np)
+# define SSL_get_cipher_version(s) \
+ SSL_CIPHER_get_version(SSL_get_current_cipher(s))
+# define SSL_get_cipher_name(s) \
+ SSL_CIPHER_get_name(SSL_get_current_cipher(s))
+# define SSL_get_time(a) SSL_SESSION_get_time(a)
+# define SSL_set_time(a,b) SSL_SESSION_set_time((a),(b))
+# define SSL_get_timeout(a) SSL_SESSION_get_timeout(a)
+# define SSL_set_timeout(a,b) SSL_SESSION_set_timeout((a),(b))
+
+# define d2i_SSL_SESSION_bio(bp,s_id) ASN1_d2i_bio_of(SSL_SESSION,SSL_SESSION_new,d2i_SSL_SESSION,bp,s_id)
+# define i2d_SSL_SESSION_bio(bp,s_id) ASN1_i2d_bio_of(SSL_SESSION,i2d_SSL_SESSION,bp,s_id)
+
+DECLARE_PEM_rw(SSL_SESSION, SSL_SESSION)
+# define SSL_AD_REASON_OFFSET 1000/* offset to get SSL_R_... value
+ * from SSL_AD_... */
+/* These alert types are for SSLv3 and TLSv1 */
+# define SSL_AD_CLOSE_NOTIFY SSL3_AD_CLOSE_NOTIFY
+/* fatal */
+# define SSL_AD_UNEXPECTED_MESSAGE SSL3_AD_UNEXPECTED_MESSAGE
+/* fatal */
+# define SSL_AD_BAD_RECORD_MAC SSL3_AD_BAD_RECORD_MAC
+# define SSL_AD_DECRYPTION_FAILED TLS1_AD_DECRYPTION_FAILED
+# define SSL_AD_RECORD_OVERFLOW TLS1_AD_RECORD_OVERFLOW
+/* fatal */
+# define SSL_AD_DECOMPRESSION_FAILURE SSL3_AD_DECOMPRESSION_FAILURE
+/* fatal */
+# define SSL_AD_HANDSHAKE_FAILURE SSL3_AD_HANDSHAKE_FAILURE
+/* Not for TLS */
+# define SSL_AD_NO_CERTIFICATE SSL3_AD_NO_CERTIFICATE
+# define SSL_AD_BAD_CERTIFICATE SSL3_AD_BAD_CERTIFICATE
+# define SSL_AD_UNSUPPORTED_CERTIFICATE SSL3_AD_UNSUPPORTED_CERTIFICATE
+# define SSL_AD_CERTIFICATE_REVOKED SSL3_AD_CERTIFICATE_REVOKED
+# define SSL_AD_CERTIFICATE_EXPIRED SSL3_AD_CERTIFICATE_EXPIRED
+# define SSL_AD_CERTIFICATE_UNKNOWN SSL3_AD_CERTIFICATE_UNKNOWN
+/* fatal */
+# define SSL_AD_ILLEGAL_PARAMETER SSL3_AD_ILLEGAL_PARAMETER
+/* fatal */
+# define SSL_AD_UNKNOWN_CA TLS1_AD_UNKNOWN_CA
+/* fatal */
+# define SSL_AD_ACCESS_DENIED TLS1_AD_ACCESS_DENIED
+/* fatal */
+# define SSL_AD_DECODE_ERROR TLS1_AD_DECODE_ERROR
+# define SSL_AD_DECRYPT_ERROR TLS1_AD_DECRYPT_ERROR
+/* fatal */
+# define SSL_AD_EXPORT_RESTRICTION TLS1_AD_EXPORT_RESTRICTION
+/* fatal */
+# define SSL_AD_PROTOCOL_VERSION TLS1_AD_PROTOCOL_VERSION
+/* fatal */
+# define SSL_AD_INSUFFICIENT_SECURITY TLS1_AD_INSUFFICIENT_SECURITY
+/* fatal */
+# define SSL_AD_INTERNAL_ERROR TLS1_AD_INTERNAL_ERROR
+# define SSL_AD_USER_CANCELLED TLS1_AD_USER_CANCELLED
+# define SSL_AD_NO_RENEGOTIATION TLS1_AD_NO_RENEGOTIATION
+# define SSL_AD_MISSING_EXTENSION TLS13_AD_MISSING_EXTENSION
+# define SSL_AD_CERTIFICATE_REQUIRED TLS13_AD_CERTIFICATE_REQUIRED
+# define SSL_AD_UNSUPPORTED_EXTENSION TLS1_AD_UNSUPPORTED_EXTENSION
+# define SSL_AD_CERTIFICATE_UNOBTAINABLE TLS1_AD_CERTIFICATE_UNOBTAINABLE
+# define SSL_AD_UNRECOGNIZED_NAME TLS1_AD_UNRECOGNIZED_NAME
+# define SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE
+# define SSL_AD_BAD_CERTIFICATE_HASH_VALUE TLS1_AD_BAD_CERTIFICATE_HASH_VALUE
+/* fatal */
+# define SSL_AD_UNKNOWN_PSK_IDENTITY TLS1_AD_UNKNOWN_PSK_IDENTITY
+/* fatal */
+# define SSL_AD_INAPPROPRIATE_FALLBACK TLS1_AD_INAPPROPRIATE_FALLBACK
+# define SSL_AD_NO_APPLICATION_PROTOCOL TLS1_AD_NO_APPLICATION_PROTOCOL
+# define SSL_ERROR_NONE 0
+# define SSL_ERROR_SSL 1
+# define SSL_ERROR_WANT_READ 2
+# define SSL_ERROR_WANT_WRITE 3
+# define SSL_ERROR_WANT_X509_LOOKUP 4
+# define SSL_ERROR_SYSCALL 5/* look at error stack/return
+ * value/errno */
+# define SSL_ERROR_ZERO_RETURN 6
+# define SSL_ERROR_WANT_CONNECT 7
+# define SSL_ERROR_WANT_ACCEPT 8
+# define SSL_ERROR_WANT_ASYNC 9
+# define SSL_ERROR_WANT_ASYNC_JOB 10
+# define SSL_ERROR_WANT_CLIENT_HELLO_CB 11
+# define SSL_ERROR_WANT_RETRY_VERIFY 12
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTRL_SET_TMP_DH 3
+# define SSL_CTRL_SET_TMP_ECDH 4
+# define SSL_CTRL_SET_TMP_DH_CB 6
+# endif
+
+# define SSL_CTRL_GET_CLIENT_CERT_REQUEST 9
+# define SSL_CTRL_GET_NUM_RENEGOTIATIONS 10
+# define SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS 11
+# define SSL_CTRL_GET_TOTAL_RENEGOTIATIONS 12
+# define SSL_CTRL_GET_FLAGS 13
+# define SSL_CTRL_EXTRA_CHAIN_CERT 14
+# define SSL_CTRL_SET_MSG_CALLBACK 15
+# define SSL_CTRL_SET_MSG_CALLBACK_ARG 16
+/* only applies to datagram connections */
+# define SSL_CTRL_SET_MTU 17
+/* Stats */
+# define SSL_CTRL_SESS_NUMBER 20
+# define SSL_CTRL_SESS_CONNECT 21
+# define SSL_CTRL_SESS_CONNECT_GOOD 22
+# define SSL_CTRL_SESS_CONNECT_RENEGOTIATE 23
+# define SSL_CTRL_SESS_ACCEPT 24
+# define SSL_CTRL_SESS_ACCEPT_GOOD 25
+# define SSL_CTRL_SESS_ACCEPT_RENEGOTIATE 26
+# define SSL_CTRL_SESS_HIT 27
+# define SSL_CTRL_SESS_CB_HIT 28
+# define SSL_CTRL_SESS_MISSES 29
+# define SSL_CTRL_SESS_TIMEOUTS 30
+# define SSL_CTRL_SESS_CACHE_FULL 31
+# define SSL_CTRL_MODE 33
+# define SSL_CTRL_GET_READ_AHEAD 40
+# define SSL_CTRL_SET_READ_AHEAD 41
+# define SSL_CTRL_SET_SESS_CACHE_SIZE 42
+# define SSL_CTRL_GET_SESS_CACHE_SIZE 43
+# define SSL_CTRL_SET_SESS_CACHE_MODE 44
+# define SSL_CTRL_GET_SESS_CACHE_MODE 45
+# define SSL_CTRL_GET_MAX_CERT_LIST 50
+# define SSL_CTRL_SET_MAX_CERT_LIST 51
+# define SSL_CTRL_SET_MAX_SEND_FRAGMENT 52
+/* see tls1.h for macros based on these */
+# define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53
+# define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54
+# define SSL_CTRL_SET_TLSEXT_HOSTNAME 55
+# define SSL_CTRL_SET_TLSEXT_DEBUG_CB 56
+# define SSL_CTRL_SET_TLSEXT_DEBUG_ARG 57
+# define SSL_CTRL_GET_TLSEXT_TICKET_KEYS 58
+# define SSL_CTRL_SET_TLSEXT_TICKET_KEYS 59
+/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT 60 */
+/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB 61 */
+/*# define SSL_CTRL_SET_TLSEXT_OPAQUE_PRF_INPUT_CB_ARG 62 */
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB 63
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG 64
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE 65
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS 66
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS 67
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS 68
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS 69
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP 70
+# define SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP 71
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB 72
+# endif
+# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME_CB 75
+# define SSL_CTRL_SET_SRP_VERIFY_PARAM_CB 76
+# define SSL_CTRL_SET_SRP_GIVE_CLIENT_PWD_CB 77
+# define SSL_CTRL_SET_SRP_ARG 78
+# define SSL_CTRL_SET_TLS_EXT_SRP_USERNAME 79
+# define SSL_CTRL_SET_TLS_EXT_SRP_STRENGTH 80
+# define SSL_CTRL_SET_TLS_EXT_SRP_PASSWORD 81
+# define DTLS_CTRL_GET_TIMEOUT 73
+# define DTLS_CTRL_HANDLE_TIMEOUT 74
+# define SSL_CTRL_GET_RI_SUPPORT 76
+# define SSL_CTRL_CLEAR_MODE 78
+# define SSL_CTRL_SET_NOT_RESUMABLE_SESS_CB 79
+# define SSL_CTRL_GET_EXTRA_CHAIN_CERTS 82
+# define SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS 83
+# define SSL_CTRL_CHAIN 88
+# define SSL_CTRL_CHAIN_CERT 89
+# define SSL_CTRL_GET_GROUPS 90
+# define SSL_CTRL_SET_GROUPS 91
+# define SSL_CTRL_SET_GROUPS_LIST 92
+# define SSL_CTRL_GET_SHARED_GROUP 93
+# define SSL_CTRL_SET_SIGALGS 97
+# define SSL_CTRL_SET_SIGALGS_LIST 98
+# define SSL_CTRL_CERT_FLAGS 99
+# define SSL_CTRL_CLEAR_CERT_FLAGS 100
+# define SSL_CTRL_SET_CLIENT_SIGALGS 101
+# define SSL_CTRL_SET_CLIENT_SIGALGS_LIST 102
+# define SSL_CTRL_GET_CLIENT_CERT_TYPES 103
+# define SSL_CTRL_SET_CLIENT_CERT_TYPES 104
+# define SSL_CTRL_BUILD_CERT_CHAIN 105
+# define SSL_CTRL_SET_VERIFY_CERT_STORE 106
+# define SSL_CTRL_SET_CHAIN_CERT_STORE 107
+# define SSL_CTRL_GET_PEER_SIGNATURE_NID 108
+# define SSL_CTRL_GET_PEER_TMP_KEY 109
+# define SSL_CTRL_GET_RAW_CIPHERLIST 110
+# define SSL_CTRL_GET_EC_POINT_FORMATS 111
+# define SSL_CTRL_GET_CHAIN_CERTS 115
+# define SSL_CTRL_SELECT_CURRENT_CERT 116
+# define SSL_CTRL_SET_CURRENT_CERT 117
+# define SSL_CTRL_SET_DH_AUTO 118
+# define DTLS_CTRL_SET_LINK_MTU 120
+# define DTLS_CTRL_GET_LINK_MIN_MTU 121
+# define SSL_CTRL_GET_EXTMS_SUPPORT 122
+# define SSL_CTRL_SET_MIN_PROTO_VERSION 123
+# define SSL_CTRL_SET_MAX_PROTO_VERSION 124
+# define SSL_CTRL_SET_SPLIT_SEND_FRAGMENT 125
+# define SSL_CTRL_SET_MAX_PIPELINES 126
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE 127
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB 128
+# define SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG 129
+# define SSL_CTRL_GET_MIN_PROTO_VERSION 130
+# define SSL_CTRL_GET_MAX_PROTO_VERSION 131
+# define SSL_CTRL_GET_SIGNATURE_NID 132
+# define SSL_CTRL_GET_TMP_KEY 133
+# define SSL_CTRL_GET_NEGOTIATED_GROUP 134
+# define SSL_CERT_SET_FIRST 1
+# define SSL_CERT_SET_NEXT 2
+# define SSL_CERT_SET_SERVER 3
+# define DTLSv1_get_timeout(ssl, arg) \
+ SSL_ctrl(ssl,DTLS_CTRL_GET_TIMEOUT,0, (void *)(arg))
+# define DTLSv1_handle_timeout(ssl) \
+ SSL_ctrl(ssl,DTLS_CTRL_HANDLE_TIMEOUT,0, NULL)
+# define SSL_num_renegotiations(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_GET_NUM_RENEGOTIATIONS,0,NULL)
+# define SSL_clear_num_renegotiations(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_CLEAR_NUM_RENEGOTIATIONS,0,NULL)
+# define SSL_total_renegotiations(ssl) \
+ SSL_ctrl((ssl),SSL_CTRL_GET_TOTAL_RENEGOTIATIONS,0,NULL)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTX_set_tmp_dh(ctx,dh) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_DH,0,(char *)(dh))
+# endif
+# define SSL_CTX_set_dh_auto(ctx, onoff) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_DH_AUTO,onoff,NULL)
+# define SSL_set_dh_auto(s, onoff) \
+ SSL_ctrl(s,SSL_CTRL_SET_DH_AUTO,onoff,NULL)
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_set_tmp_dh(ssl,dh) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TMP_DH,0,(char *)(dh))
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTX_set_tmp_ecdh(ctx,ecdh) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh))
+# define SSL_set_tmp_ecdh(ssl,ecdh) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TMP_ECDH,0,(char *)(ecdh))
+# endif
+# define SSL_CTX_add_extra_chain_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_EXTRA_CHAIN_CERT,0,(char *)(x509))
+# define SSL_CTX_get_extra_chain_certs(ctx,px509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,0,px509)
+# define SSL_CTX_get_extra_chain_certs_only(ctx,px509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_EXTRA_CHAIN_CERTS,1,px509)
+# define SSL_CTX_clear_extra_chain_certs(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CLEAR_EXTRA_CHAIN_CERTS,0,NULL)
+# define SSL_CTX_set0_chain(ctx,sk) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,0,(char *)(sk))
+# define SSL_CTX_set1_chain(ctx,sk) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN,1,(char *)(sk))
+# define SSL_CTX_add0_chain_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,0,(char *)(x509))
+# define SSL_CTX_add1_chain_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_CHAIN_CERT,1,(char *)(x509))
+# define SSL_CTX_get0_chain_certs(ctx,px509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
+# define SSL_CTX_clear_chain_certs(ctx) \
+ SSL_CTX_set0_chain(ctx,NULL)
+# define SSL_CTX_build_cert_chain(ctx, flags) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
+# define SSL_CTX_select_current_cert(ctx,x509) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509))
+# define SSL_CTX_set_current_cert(ctx, op) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
+# define SSL_CTX_set0_verify_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st))
+# define SSL_CTX_set1_verify_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st))
+# define SSL_CTX_set0_chain_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st))
+# define SSL_CTX_set1_chain_cert_store(ctx,st) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st))
+# define SSL_set0_chain(s,sk) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN,0,(char *)(sk))
+# define SSL_set1_chain(s,sk) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN,1,(char *)(sk))
+# define SSL_add0_chain_cert(s,x509) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN_CERT,0,(char *)(x509))
+# define SSL_add1_chain_cert(s,x509) \
+ SSL_ctrl(s,SSL_CTRL_CHAIN_CERT,1,(char *)(x509))
+# define SSL_get0_chain_certs(s,px509) \
+ SSL_ctrl(s,SSL_CTRL_GET_CHAIN_CERTS,0,px509)
+# define SSL_clear_chain_certs(s) \
+ SSL_set0_chain(s,NULL)
+# define SSL_build_cert_chain(s, flags) \
+ SSL_ctrl(s,SSL_CTRL_BUILD_CERT_CHAIN, flags, NULL)
+# define SSL_select_current_cert(s,x509) \
+ SSL_ctrl(s,SSL_CTRL_SELECT_CURRENT_CERT,0,(char *)(x509))
+# define SSL_set_current_cert(s,op) \
+ SSL_ctrl(s,SSL_CTRL_SET_CURRENT_CERT, op, NULL)
+# define SSL_set0_verify_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,0,(char *)(st))
+# define SSL_set1_verify_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_VERIFY_CERT_STORE,1,(char *)(st))
+# define SSL_set0_chain_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,0,(char *)(st))
+# define SSL_set1_chain_cert_store(s,st) \
+ SSL_ctrl(s,SSL_CTRL_SET_CHAIN_CERT_STORE,1,(char *)(st))
+# define SSL_get1_groups(s, glist) \
+ SSL_ctrl(s,SSL_CTRL_GET_GROUPS,0,(int*)(glist))
+# define SSL_CTX_set1_groups(ctx, glist, glistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS,glistlen,(int *)(glist))
+# define SSL_CTX_set1_groups_list(ctx, s) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(s))
+# define SSL_set1_groups(s, glist, glistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_GROUPS,glistlen,(char *)(glist))
+# define SSL_set1_groups_list(s, str) \
+ SSL_ctrl(s,SSL_CTRL_SET_GROUPS_LIST,0,(char *)(str))
+# define SSL_get_shared_group(s, n) \
+ SSL_ctrl(s,SSL_CTRL_GET_SHARED_GROUP,n,NULL)
+# define SSL_get_negotiated_group(s) \
+ SSL_ctrl(s,SSL_CTRL_GET_NEGOTIATED_GROUP,0,NULL)
+# define SSL_CTX_set1_sigalgs(ctx, slist, slistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS,slistlen,(int *)(slist))
+# define SSL_CTX_set1_sigalgs_list(ctx, s) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(s))
+# define SSL_set1_sigalgs(s, slist, slistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_SIGALGS,slistlen,(int *)(slist))
+# define SSL_set1_sigalgs_list(s, str) \
+ SSL_ctrl(s,SSL_CTRL_SET_SIGALGS_LIST,0,(char *)(str))
+# define SSL_CTX_set1_client_sigalgs(ctx, slist, slistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(int *)(slist))
+# define SSL_CTX_set1_client_sigalgs_list(ctx, s) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(s))
+# define SSL_set1_client_sigalgs(s, slist, slistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_CLIENT_SIGALGS,slistlen,(int *)(slist))
+# define SSL_set1_client_sigalgs_list(s, str) \
+ SSL_ctrl(s,SSL_CTRL_SET_CLIENT_SIGALGS_LIST,0,(char *)(str))
+# define SSL_get0_certificate_types(s, clist) \
+ SSL_ctrl(s, SSL_CTRL_GET_CLIENT_CERT_TYPES, 0, (char *)(clist))
+# define SSL_CTX_set1_client_certificate_types(ctx, clist, clistlen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen, \
+ (char *)(clist))
+# define SSL_set1_client_certificate_types(s, clist, clistlen) \
+ SSL_ctrl(s,SSL_CTRL_SET_CLIENT_CERT_TYPES,clistlen,(char *)(clist))
+# define SSL_get_signature_nid(s, pn) \
+ SSL_ctrl(s,SSL_CTRL_GET_SIGNATURE_NID,0,pn)
+# define SSL_get_peer_signature_nid(s, pn) \
+ SSL_ctrl(s,SSL_CTRL_GET_PEER_SIGNATURE_NID,0,pn)
+# define SSL_get_peer_tmp_key(s, pk) \
+ SSL_ctrl(s,SSL_CTRL_GET_PEER_TMP_KEY,0,pk)
+# define SSL_get_tmp_key(s, pk) \
+ SSL_ctrl(s,SSL_CTRL_GET_TMP_KEY,0,pk)
+# define SSL_get0_raw_cipherlist(s, plst) \
+ SSL_ctrl(s,SSL_CTRL_GET_RAW_CIPHERLIST,0,plst)
+# define SSL_get0_ec_point_formats(s, plst) \
+ SSL_ctrl(s,SSL_CTRL_GET_EC_POINT_FORMATS,0,plst)
+# define SSL_CTX_set_min_proto_version(ctx, version) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL)
+# define SSL_CTX_set_max_proto_version(ctx, version) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL)
+# define SSL_CTX_get_min_proto_version(ctx) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL)
+# define SSL_CTX_get_max_proto_version(ctx) \
+ SSL_CTX_ctrl(ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL)
+# define SSL_set_min_proto_version(s, version) \
+ SSL_ctrl(s, SSL_CTRL_SET_MIN_PROTO_VERSION, version, NULL)
+# define SSL_set_max_proto_version(s, version) \
+ SSL_ctrl(s, SSL_CTRL_SET_MAX_PROTO_VERSION, version, NULL)
+# define SSL_get_min_proto_version(s) \
+ SSL_ctrl(s, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL)
+# define SSL_get_max_proto_version(s) \
+ SSL_ctrl(s, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL)
+
+const char *SSL_group_to_name(SSL *s, int id);
+
+/* Backwards compatibility, original 1.1.0 names */
+# define SSL_CTRL_GET_SERVER_TMP_KEY \
+ SSL_CTRL_GET_PEER_TMP_KEY
+# define SSL_get_server_tmp_key(s, pk) \
+ SSL_get_peer_tmp_key(s, pk)
+
+int SSL_set0_tmp_dh_pkey(SSL *s, EVP_PKEY *dhpkey);
+int SSL_CTX_set0_tmp_dh_pkey(SSL_CTX *ctx, EVP_PKEY *dhpkey);
+
+/*
+ * The following symbol names are old and obsolete. They are kept
+ * for compatibility reasons only and should not be used anymore.
+ */
+# define SSL_CTRL_GET_CURVES SSL_CTRL_GET_GROUPS
+# define SSL_CTRL_SET_CURVES SSL_CTRL_SET_GROUPS
+# define SSL_CTRL_SET_CURVES_LIST SSL_CTRL_SET_GROUPS_LIST
+# define SSL_CTRL_GET_SHARED_CURVE SSL_CTRL_GET_SHARED_GROUP
+
+# define SSL_get1_curves SSL_get1_groups
+# define SSL_CTX_set1_curves SSL_CTX_set1_groups
+# define SSL_CTX_set1_curves_list SSL_CTX_set1_groups_list
+# define SSL_set1_curves SSL_set1_groups
+# define SSL_set1_curves_list SSL_set1_groups_list
+# define SSL_get_shared_curve SSL_get_shared_group
+
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/* Provide some compatibility macros for removed functionality. */
+# define SSL_CTX_need_tmp_RSA(ctx) 0
+# define SSL_CTX_set_tmp_rsa(ctx,rsa) 1
+# define SSL_need_tmp_RSA(ssl) 0
+# define SSL_set_tmp_rsa(ssl,rsa) 1
+# define SSL_CTX_set_ecdh_auto(dummy, onoff) ((onoff) != 0)
+# define SSL_set_ecdh_auto(dummy, onoff) ((onoff) != 0)
+/*
+ * We "pretend" to call the callback to avoid warnings about unused static
+ * functions.
+ */
+# define SSL_CTX_set_tmp_rsa_callback(ctx, cb) while(0) (cb)(NULL, 0, 0)
+# define SSL_set_tmp_rsa_callback(ssl, cb) while(0) (cb)(NULL, 0, 0)
+# endif
+__owur const BIO_METHOD *BIO_f_ssl(void);
+__owur BIO *BIO_new_ssl(SSL_CTX *ctx, int client);
+__owur BIO *BIO_new_ssl_connect(SSL_CTX *ctx);
+__owur BIO *BIO_new_buffer_ssl_connect(SSL_CTX *ctx);
+__owur int BIO_ssl_copy_session_id(BIO *to, BIO *from);
+void BIO_ssl_shutdown(BIO *ssl_bio);
+
+__owur int SSL_CTX_set_cipher_list(SSL_CTX *, const char *str);
+__owur SSL_CTX *SSL_CTX_new(const SSL_METHOD *meth);
+__owur SSL_CTX *SSL_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq,
+ const SSL_METHOD *meth);
+int SSL_CTX_up_ref(SSL_CTX *ctx);
+void SSL_CTX_free(SSL_CTX *);
+__owur long SSL_CTX_set_timeout(SSL_CTX *ctx, long t);
+__owur long SSL_CTX_get_timeout(const SSL_CTX *ctx);
+__owur X509_STORE *SSL_CTX_get_cert_store(const SSL_CTX *);
+void SSL_CTX_set_cert_store(SSL_CTX *, X509_STORE *);
+void SSL_CTX_set1_cert_store(SSL_CTX *, X509_STORE *);
+__owur int SSL_want(const SSL *s);
+__owur int SSL_clear(SSL *s);
+
+void SSL_CTX_flush_sessions(SSL_CTX *ctx, long tm);
+
+__owur const SSL_CIPHER *SSL_get_current_cipher(const SSL *s);
+__owur const SSL_CIPHER *SSL_get_pending_cipher(const SSL *s);
+__owur int SSL_CIPHER_get_bits(const SSL_CIPHER *c, int *alg_bits);
+__owur const char *SSL_CIPHER_get_version(const SSL_CIPHER *c);
+__owur const char *SSL_CIPHER_get_name(const SSL_CIPHER *c);
+__owur const char *SSL_CIPHER_standard_name(const SSL_CIPHER *c);
+__owur const char *OPENSSL_cipher_name(const char *rfc_name);
+__owur uint32_t SSL_CIPHER_get_id(const SSL_CIPHER *c);
+__owur uint16_t SSL_CIPHER_get_protocol_id(const SSL_CIPHER *c);
+__owur int SSL_CIPHER_get_kx_nid(const SSL_CIPHER *c);
+__owur int SSL_CIPHER_get_auth_nid(const SSL_CIPHER *c);
+__owur const EVP_MD *SSL_CIPHER_get_handshake_digest(const SSL_CIPHER *c);
+__owur int SSL_CIPHER_is_aead(const SSL_CIPHER *c);
+
+__owur int SSL_get_fd(const SSL *s);
+__owur int SSL_get_rfd(const SSL *s);
+__owur int SSL_get_wfd(const SSL *s);
+__owur const char *SSL_get_cipher_list(const SSL *s, int n);
+__owur char *SSL_get_shared_ciphers(const SSL *s, char *buf, int size);
+__owur int SSL_get_read_ahead(const SSL *s);
+__owur int SSL_pending(const SSL *s);
+__owur int SSL_has_pending(const SSL *s);
+# ifndef OPENSSL_NO_SOCK
+__owur int SSL_set_fd(SSL *s, int fd);
+__owur int SSL_set_rfd(SSL *s, int fd);
+__owur int SSL_set_wfd(SSL *s, int fd);
+# endif
+void SSL_set0_rbio(SSL *s, BIO *rbio);
+void SSL_set0_wbio(SSL *s, BIO *wbio);
+void SSL_set_bio(SSL *s, BIO *rbio, BIO *wbio);
+__owur BIO *SSL_get_rbio(const SSL *s);
+__owur BIO *SSL_get_wbio(const SSL *s);
+__owur int SSL_set_cipher_list(SSL *s, const char *str);
+__owur int SSL_CTX_set_ciphersuites(SSL_CTX *ctx, const char *str);
+__owur int SSL_set_ciphersuites(SSL *s, const char *str);
+void SSL_set_read_ahead(SSL *s, int yes);
+__owur int SSL_get_verify_mode(const SSL *s);
+__owur int SSL_get_verify_depth(const SSL *s);
+__owur SSL_verify_cb SSL_get_verify_callback(const SSL *s);
+void SSL_set_verify(SSL *s, int mode, SSL_verify_cb callback);
+void SSL_set_verify_depth(SSL *s, int depth);
+void SSL_set_cert_cb(SSL *s, int (*cb) (SSL *ssl, void *arg), void *arg);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 __owur int SSL_use_RSAPrivateKey(SSL *ssl, RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_use_RSAPrivateKey_ASN1(SSL *ssl,
+ const unsigned char *d, long len);
+# endif
+__owur int SSL_use_PrivateKey(SSL *ssl, EVP_PKEY *pkey);
+__owur int SSL_use_PrivateKey_ASN1(int pk, SSL *ssl, const unsigned char *d,
+ long len);
+__owur int SSL_use_certificate(SSL *ssl, X509 *x);
+__owur int SSL_use_certificate_ASN1(SSL *ssl, const unsigned char *d, int len);
+__owur int SSL_use_cert_and_key(SSL *ssl, X509 *x509, EVP_PKEY *privatekey,
+ STACK_OF(X509) *chain, int override);
+
+
+/* serverinfo file format versions */
+# define SSL_SERVERINFOV1 1
+# define SSL_SERVERINFOV2 2
+
+/* Set serverinfo data for the current active cert. */
+__owur int SSL_CTX_use_serverinfo(SSL_CTX *ctx, const unsigned char *serverinfo,
+ size_t serverinfo_length);
+__owur int SSL_CTX_use_serverinfo_ex(SSL_CTX *ctx, unsigned int version,
+ const unsigned char *serverinfo,
+ size_t serverinfo_length);
+__owur int SSL_CTX_use_serverinfo_file(SSL_CTX *ctx, const char *file);
+
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_use_RSAPrivateKey_file(SSL *ssl, const char *file, int type);
+#endif
+
+__owur int SSL_use_PrivateKey_file(SSL *ssl, const char *file, int type);
+__owur int SSL_use_certificate_file(SSL *ssl, const char *file, int type);
+
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_use_RSAPrivateKey_file(SSL_CTX *ctx, const char *file,
+ int type);
+#endif
+__owur int SSL_CTX_use_PrivateKey_file(SSL_CTX *ctx, const char *file,
+ int type);
+__owur int SSL_CTX_use_certificate_file(SSL_CTX *ctx, const char *file,
+ int type);
+/* PEM type */
+__owur int SSL_CTX_use_certificate_chain_file(SSL_CTX *ctx, const char *file);
+__owur int SSL_use_certificate_chain_file(SSL *ssl, const char *file);
+__owur STACK_OF(X509_NAME) *SSL_load_client_CA_file(const char *file);
+__owur STACK_OF(X509_NAME)
+*SSL_load_client_CA_file_ex(const char *file, OSSL_LIB_CTX *libctx,
+ const char *propq);
+__owur int SSL_add_file_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
+ const char *file);
+int SSL_add_dir_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
+ const char *dir);
+int SSL_add_store_cert_subjects_to_stack(STACK_OF(X509_NAME) *stackCAs,
+ const char *uri);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_load_error_strings() \
+ OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS \
+ | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL)
+# endif
+
+__owur const char *SSL_state_string(const SSL *s);
+__owur const char *SSL_rstate_string(const SSL *s);
+__owur const char *SSL_state_string_long(const SSL *s);
+__owur const char *SSL_rstate_string_long(const SSL *s);
+__owur long SSL_SESSION_get_time(const SSL_SESSION *s);
+__owur long SSL_SESSION_set_time(SSL_SESSION *s, long t);
+__owur long SSL_SESSION_get_timeout(const SSL_SESSION *s);
+__owur long SSL_SESSION_set_timeout(SSL_SESSION *s, long t);
+__owur int SSL_SESSION_get_protocol_version(const SSL_SESSION *s);
+__owur int SSL_SESSION_set_protocol_version(SSL_SESSION *s, int version);
+
+__owur const char *SSL_SESSION_get0_hostname(const SSL_SESSION *s);
+__owur int SSL_SESSION_set1_hostname(SSL_SESSION *s, const char *hostname);
+void SSL_SESSION_get0_alpn_selected(const SSL_SESSION *s,
+ const unsigned char **alpn,
+ size_t *len);
+__owur int SSL_SESSION_set1_alpn_selected(SSL_SESSION *s,
+ const unsigned char *alpn,
+ size_t len);
+__owur const SSL_CIPHER *SSL_SESSION_get0_cipher(const SSL_SESSION *s);
+__owur int SSL_SESSION_set_cipher(SSL_SESSION *s, const SSL_CIPHER *cipher);
+__owur int SSL_SESSION_has_ticket(const SSL_SESSION *s);
+__owur unsigned long SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s);
+void SSL_SESSION_get0_ticket(const SSL_SESSION *s, const unsigned char **tick,
+ size_t *len);
+__owur uint32_t SSL_SESSION_get_max_early_data(const SSL_SESSION *s);
+__owur int SSL_SESSION_set_max_early_data(SSL_SESSION *s,
+ uint32_t max_early_data);
+__owur int SSL_copy_session_id(SSL *to, const SSL *from);
+__owur X509 *SSL_SESSION_get0_peer(SSL_SESSION *s);
+__owur int SSL_SESSION_set1_id_context(SSL_SESSION *s,
+ const unsigned char *sid_ctx,
+ unsigned int sid_ctx_len);
+__owur int SSL_SESSION_set1_id(SSL_SESSION *s, const unsigned char *sid,
+ unsigned int sid_len);
+__owur int SSL_SESSION_is_resumable(const SSL_SESSION *s);
+
+__owur SSL_SESSION *SSL_SESSION_new(void);
+__owur SSL_SESSION *SSL_SESSION_dup(const SSL_SESSION *src);
+const unsigned char *SSL_SESSION_get_id(const SSL_SESSION *s,
+ unsigned int *len);
+const unsigned char *SSL_SESSION_get0_id_context(const SSL_SESSION *s,
+ unsigned int *len);
+__owur unsigned int SSL_SESSION_get_compress_id(const SSL_SESSION *s);
+# ifndef OPENSSL_NO_STDIO
+int SSL_SESSION_print_fp(FILE *fp, const SSL_SESSION *ses);
+# endif
+int SSL_SESSION_print(BIO *fp, const SSL_SESSION *ses);
+int SSL_SESSION_print_keylog(BIO *bp, const SSL_SESSION *x);
+int SSL_SESSION_up_ref(SSL_SESSION *ses);
+void SSL_SESSION_free(SSL_SESSION *ses);
+__owur int i2d_SSL_SESSION(const SSL_SESSION *in, unsigned char **pp);
+__owur int SSL_set_session(SSL *to, SSL_SESSION *session);
+int SSL_CTX_add_session(SSL_CTX *ctx, SSL_SESSION *session);
+int SSL_CTX_remove_session(SSL_CTX *ctx, SSL_SESSION *session);
+__owur int SSL_CTX_set_generate_session_id(SSL_CTX *ctx, GEN_SESSION_CB cb);
+__owur int SSL_set_generate_session_id(SSL *s, GEN_SESSION_CB cb);
+__owur int SSL_has_matching_session_id(const SSL *s,
+ const unsigned char *id,
+ unsigned int id_len);
+SSL_SESSION *d2i_SSL_SESSION(SSL_SESSION **a, const unsigned char **pp,
+ long length);
+
+# ifdef OPENSSL_X509_H
+__owur X509 *SSL_get0_peer_certificate(const SSL *s);
+__owur X509 *SSL_get1_peer_certificate(const SSL *s);
+/* Deprecated in 3.0.0 */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_get_peer_certificate SSL_get1_peer_certificate
+# endif
+# endif
+
+__owur STACK_OF(X509) *SSL_get_peer_cert_chain(const SSL *s);
+
+__owur int SSL_CTX_get_verify_mode(const SSL_CTX *ctx);
+__owur int SSL_CTX_get_verify_depth(const SSL_CTX *ctx);
+__owur SSL_verify_cb SSL_CTX_get_verify_callback(const SSL_CTX *ctx);
+void SSL_CTX_set_verify(SSL_CTX *ctx, int mode, SSL_verify_cb callback);
+void SSL_CTX_set_verify_depth(SSL_CTX *ctx, int depth);
+void SSL_CTX_set_cert_verify_callback(SSL_CTX *ctx,
+ int (*cb) (X509_STORE_CTX *, void *),
+ void *arg);
+void SSL_CTX_set_cert_cb(SSL_CTX *c, int (*cb) (SSL *ssl, void *arg),
+ void *arg);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_use_RSAPrivateKey(SSL_CTX *ctx, RSA *rsa);
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_use_RSAPrivateKey_ASN1(SSL_CTX *ctx, const unsigned char *d,
+ long len);
+# endif
+__owur int SSL_CTX_use_PrivateKey(SSL_CTX *ctx, EVP_PKEY *pkey);
+__owur int SSL_CTX_use_PrivateKey_ASN1(int pk, SSL_CTX *ctx,
+ const unsigned char *d, long len);
+__owur int SSL_CTX_use_certificate(SSL_CTX *ctx, X509 *x);
+__owur int SSL_CTX_use_certificate_ASN1(SSL_CTX *ctx, int len,
+ const unsigned char *d);
+__owur int SSL_CTX_use_cert_and_key(SSL_CTX *ctx, X509 *x509, EVP_PKEY *privatekey,
+ STACK_OF(X509) *chain, int override);
+
+void SSL_CTX_set_default_passwd_cb(SSL_CTX *ctx, pem_password_cb *cb);
+void SSL_CTX_set_default_passwd_cb_userdata(SSL_CTX *ctx, void *u);
+pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx);
+void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx);
+void SSL_set_default_passwd_cb(SSL *s, pem_password_cb *cb);
+void SSL_set_default_passwd_cb_userdata(SSL *s, void *u);
+pem_password_cb *SSL_get_default_passwd_cb(SSL *s);
+void *SSL_get_default_passwd_cb_userdata(SSL *s);
+
+__owur int SSL_CTX_check_private_key(const SSL_CTX *ctx);
+__owur int SSL_check_private_key(const SSL *ctx);
+
+__owur int SSL_CTX_set_session_id_context(SSL_CTX *ctx,
+ const unsigned char *sid_ctx,
+ unsigned int sid_ctx_len);
+
+SSL *SSL_new(SSL_CTX *ctx);
+int SSL_up_ref(SSL *s);
+int SSL_is_dtls(const SSL *s);
+__owur int SSL_set_session_id_context(SSL *ssl, const unsigned char *sid_ctx,
+ unsigned int sid_ctx_len);
+
+__owur int SSL_CTX_set_purpose(SSL_CTX *ctx, int purpose);
+__owur int SSL_set_purpose(SSL *ssl, int purpose);
+__owur int SSL_CTX_set_trust(SSL_CTX *ctx, int trust);
+__owur int SSL_set_trust(SSL *ssl, int trust);
+
+__owur int SSL_set1_host(SSL *s, const char *hostname);
+__owur int SSL_add1_host(SSL *s, const char *hostname);
+__owur const char *SSL_get0_peername(SSL *s);
+void SSL_set_hostflags(SSL *s, unsigned int flags);
+
+__owur int SSL_CTX_dane_enable(SSL_CTX *ctx);
+__owur int SSL_CTX_dane_mtype_set(SSL_CTX *ctx, const EVP_MD *md,
+ uint8_t mtype, uint8_t ord);
+__owur int SSL_dane_enable(SSL *s, const char *basedomain);
+__owur int SSL_dane_tlsa_add(SSL *s, uint8_t usage, uint8_t selector,
+ uint8_t mtype, const unsigned char *data, size_t dlen);
+__owur int SSL_get0_dane_authority(SSL *s, X509 **mcert, EVP_PKEY **mspki);
+__owur int SSL_get0_dane_tlsa(SSL *s, uint8_t *usage, uint8_t *selector,
+ uint8_t *mtype, const unsigned char **data,
+ size_t *dlen);
+/*
+ * Bridge opacity barrier between libcrypt and libssl, also needed to support
+ * offline testing in test/danetest.c
+ */
+SSL_DANE *SSL_get0_dane(SSL *ssl);
+/*
+ * DANE flags
+ */
+unsigned long SSL_CTX_dane_set_flags(SSL_CTX *ctx, unsigned long flags);
+unsigned long SSL_CTX_dane_clear_flags(SSL_CTX *ctx, unsigned long flags);
+unsigned long SSL_dane_set_flags(SSL *ssl, unsigned long flags);
+unsigned long SSL_dane_clear_flags(SSL *ssl, unsigned long flags);
+
+__owur int SSL_CTX_set1_param(SSL_CTX *ctx, X509_VERIFY_PARAM *vpm);
+__owur int SSL_set1_param(SSL *ssl, X509_VERIFY_PARAM *vpm);
+
+__owur X509_VERIFY_PARAM *SSL_CTX_get0_param(SSL_CTX *ctx);
+__owur X509_VERIFY_PARAM *SSL_get0_param(SSL *ssl);
+
+# ifndef OPENSSL_NO_SRP
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_username(SSL_CTX *ctx, char *name);
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_password(SSL_CTX *ctx, char *password);
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_strength(SSL_CTX *ctx, int strength);
+OSSL_DEPRECATEDIN_3_0
+int SSL_CTX_set_srp_client_pwd_callback(SSL_CTX *ctx,
+ char *(*cb) (SSL *, void *));
+OSSL_DEPRECATEDIN_3_0
+int SSL_CTX_set_srp_verify_param_callback(SSL_CTX *ctx,
+ int (*cb) (SSL *, void *));
+OSSL_DEPRECATEDIN_3_0
+int SSL_CTX_set_srp_username_callback(SSL_CTX *ctx,
+ int (*cb) (SSL *, int *, void *));
+OSSL_DEPRECATEDIN_3_0 int SSL_CTX_set_srp_cb_arg(SSL_CTX *ctx, void *arg);
+
+OSSL_DEPRECATEDIN_3_0
+int SSL_set_srp_server_param(SSL *s, const BIGNUM *N, const BIGNUM *g,
+ BIGNUM *sa, BIGNUM *v, char *info);
+OSSL_DEPRECATEDIN_3_0
+int SSL_set_srp_server_param_pw(SSL *s, const char *user, const char *pass,
+ const char *grp);
+
+OSSL_DEPRECATEDIN_3_0 __owur BIGNUM *SSL_get_srp_g(SSL *s);
+OSSL_DEPRECATEDIN_3_0 __owur BIGNUM *SSL_get_srp_N(SSL *s);
+
+OSSL_DEPRECATEDIN_3_0 __owur char *SSL_get_srp_username(SSL *s);
+OSSL_DEPRECATEDIN_3_0 __owur char *SSL_get_srp_userinfo(SSL *s);
+# endif
+# endif
+
+/*
+ * ClientHello callback and helpers.
+ */
+
+# define SSL_CLIENT_HELLO_SUCCESS 1
+# define SSL_CLIENT_HELLO_ERROR 0
+# define SSL_CLIENT_HELLO_RETRY (-1)
+
+typedef int (*SSL_client_hello_cb_fn) (SSL *s, int *al, void *arg);
+void SSL_CTX_set_client_hello_cb(SSL_CTX *c, SSL_client_hello_cb_fn cb,
+ void *arg);
+int SSL_client_hello_isv2(SSL *s);
+unsigned int SSL_client_hello_get0_legacy_version(SSL *s);
+size_t SSL_client_hello_get0_random(SSL *s, const unsigned char **out);
+size_t SSL_client_hello_get0_session_id(SSL *s, const unsigned char **out);
+size_t SSL_client_hello_get0_ciphers(SSL *s, const unsigned char **out);
+size_t SSL_client_hello_get0_compression_methods(SSL *s,
+ const unsigned char **out);
+int SSL_client_hello_get1_extensions_present(SSL *s, int **out, size_t *outlen);
+int SSL_client_hello_get0_ext(SSL *s, unsigned int type,
+ const unsigned char **out, size_t *outlen);
+
+void SSL_certs_clear(SSL *s);
+void SSL_free(SSL *ssl);
+# ifdef OSSL_ASYNC_FD
+/*
+ * Windows application developer has to include windows.h to use these.
+ */
+__owur int SSL_waiting_for_async(SSL *s);
+__owur int SSL_get_all_async_fds(SSL *s, OSSL_ASYNC_FD *fds, size_t *numfds);
+__owur int SSL_get_changed_async_fds(SSL *s, OSSL_ASYNC_FD *addfd,
+ size_t *numaddfds, OSSL_ASYNC_FD *delfd,
+ size_t *numdelfds);
+__owur int SSL_CTX_set_async_callback(SSL_CTX *ctx, SSL_async_callback_fn callback);
+__owur int SSL_CTX_set_async_callback_arg(SSL_CTX *ctx, void *arg);
+__owur int SSL_set_async_callback(SSL *s, SSL_async_callback_fn callback);
+__owur int SSL_set_async_callback_arg(SSL *s, void *arg);
+__owur int SSL_get_async_status(SSL *s, int *status);
+
+# endif
+__owur int SSL_accept(SSL *ssl);
+__owur int SSL_stateless(SSL *s);
+__owur int SSL_connect(SSL *ssl);
+__owur int SSL_read(SSL *ssl, void *buf, int num);
+__owur int SSL_read_ex(SSL *ssl, void *buf, size_t num, size_t *readbytes);
+
+# define SSL_READ_EARLY_DATA_ERROR 0
+# define SSL_READ_EARLY_DATA_SUCCESS 1
+# define SSL_READ_EARLY_DATA_FINISH 2
+
+__owur int SSL_read_early_data(SSL *s, void *buf, size_t num,
+ size_t *readbytes);
+__owur int SSL_peek(SSL *ssl, void *buf, int num);
+__owur int SSL_peek_ex(SSL *ssl, void *buf, size_t num, size_t *readbytes);
+__owur ossl_ssize_t SSL_sendfile(SSL *s, int fd, off_t offset, size_t size,
+ int flags);
+__owur int SSL_write(SSL *ssl, const void *buf, int num);
+__owur int SSL_write_ex(SSL *s, const void *buf, size_t num, size_t *written);
+__owur int SSL_write_early_data(SSL *s, const void *buf, size_t num,
+ size_t *written);
+long SSL_ctrl(SSL *ssl, int cmd, long larg, void *parg);
+long SSL_callback_ctrl(SSL *, int, void (*)(void));
+long SSL_CTX_ctrl(SSL_CTX *ctx, int cmd, long larg, void *parg);
+long SSL_CTX_callback_ctrl(SSL_CTX *, int, void (*)(void));
+
+# define SSL_EARLY_DATA_NOT_SENT 0
+# define SSL_EARLY_DATA_REJECTED 1
+# define SSL_EARLY_DATA_ACCEPTED 2
+
+__owur int SSL_get_early_data_status(const SSL *s);
+
+__owur int SSL_get_error(const SSL *s, int ret_code);
+__owur const char *SSL_get_version(const SSL *s);
+
+/* This sets the 'default' SSL version that SSL_new() will create */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+__owur int SSL_CTX_set_ssl_version(SSL_CTX *ctx, const SSL_METHOD *meth);
+# endif
+
+# ifndef OPENSSL_NO_SSL3_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *SSLv3_method(void); /* SSLv3 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *SSLv3_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *SSLv3_client_method(void);
+# endif
+# endif
+
+#define SSLv23_method TLS_method
+#define SSLv23_server_method TLS_server_method
+#define SSLv23_client_method TLS_client_method
+
+/* Negotiate highest available SSL/TLS version */
+__owur const SSL_METHOD *TLS_method(void);
+__owur const SSL_METHOD *TLS_server_method(void);
+__owur const SSL_METHOD *TLS_client_method(void);
+
+# ifndef OPENSSL_NO_TLS1_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_method(void); /* TLSv1.0 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_TLS1_1_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_1_method(void); /* TLSv1.1 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_1_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_1_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_TLS1_2_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_2_method(void); /* TLSv1.2 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_2_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *TLSv1_2_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DTLS1_METHOD
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_method(void); /* DTLSv1.0 */
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_client_method(void);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DTLS1_2_METHOD
+/* DTLSv1.2 */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_2_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_2_server_method(void);
+OSSL_DEPRECATEDIN_1_1_0 __owur const SSL_METHOD *DTLSv1_2_client_method(void);
+# endif
+# endif
+
+__owur const SSL_METHOD *DTLS_method(void); /* DTLS 1.0 and 1.2 */
+__owur const SSL_METHOD *DTLS_server_method(void); /* DTLS 1.0 and 1.2 */
+__owur const SSL_METHOD *DTLS_client_method(void); /* DTLS 1.0 and 1.2 */
+
+__owur size_t DTLS_get_data_mtu(const SSL *s);
+
+__owur STACK_OF(SSL_CIPHER) *SSL_get_ciphers(const SSL *s);
+__owur STACK_OF(SSL_CIPHER) *SSL_CTX_get_ciphers(const SSL_CTX *ctx);
+__owur STACK_OF(SSL_CIPHER) *SSL_get_client_ciphers(const SSL *s);
+__owur STACK_OF(SSL_CIPHER) *SSL_get1_supported_ciphers(SSL *s);
+
+__owur int SSL_do_handshake(SSL *s);
+int SSL_key_update(SSL *s, int updatetype);
+int SSL_get_key_update_type(const SSL *s);
+int SSL_renegotiate(SSL *s);
+int SSL_renegotiate_abbreviated(SSL *s);
+__owur int SSL_renegotiate_pending(const SSL *s);
+int SSL_new_session_ticket(SSL *s);
+int SSL_shutdown(SSL *s);
+__owur int SSL_verify_client_post_handshake(SSL *s);
+void SSL_CTX_set_post_handshake_auth(SSL_CTX *ctx, int val);
+void SSL_set_post_handshake_auth(SSL *s, int val);
+
+__owur const SSL_METHOD *SSL_CTX_get_ssl_method(const SSL_CTX *ctx);
+__owur const SSL_METHOD *SSL_get_ssl_method(const SSL *s);
+__owur int SSL_set_ssl_method(SSL *s, const SSL_METHOD *method);
+__owur const char *SSL_alert_type_string_long(int value);
+__owur const char *SSL_alert_type_string(int value);
+__owur const char *SSL_alert_desc_string_long(int value);
+__owur const char *SSL_alert_desc_string(int value);
+
+void SSL_set0_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list);
+void SSL_CTX_set0_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list);
+__owur const STACK_OF(X509_NAME) *SSL_get0_CA_list(const SSL *s);
+__owur const STACK_OF(X509_NAME) *SSL_CTX_get0_CA_list(const SSL_CTX *ctx);
+__owur int SSL_add1_to_CA_list(SSL *ssl, const X509 *x);
+__owur int SSL_CTX_add1_to_CA_list(SSL_CTX *ctx, const X509 *x);
+__owur const STACK_OF(X509_NAME) *SSL_get0_peer_CA_list(const SSL *s);
+
+void SSL_set_client_CA_list(SSL *s, STACK_OF(X509_NAME) *name_list);
+void SSL_CTX_set_client_CA_list(SSL_CTX *ctx, STACK_OF(X509_NAME) *name_list);
+__owur STACK_OF(X509_NAME) *SSL_get_client_CA_list(const SSL *s);
+__owur STACK_OF(X509_NAME) *SSL_CTX_get_client_CA_list(const SSL_CTX *s);
+__owur int SSL_add_client_CA(SSL *ssl, X509 *x);
+__owur int SSL_CTX_add_client_CA(SSL_CTX *ctx, X509 *x);
+
+void SSL_set_connect_state(SSL *s);
+void SSL_set_accept_state(SSL *s);
+
+__owur long SSL_get_default_timeout(const SSL *s);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_library_init() OPENSSL_init_ssl(0, NULL)
+# endif
+
+__owur char *SSL_CIPHER_description(const SSL_CIPHER *, char *buf, int size);
+__owur STACK_OF(X509_NAME) *SSL_dup_CA_list(const STACK_OF(X509_NAME) *sk);
+
+__owur SSL *SSL_dup(SSL *ssl);
+
+__owur X509 *SSL_get_certificate(const SSL *ssl);
+/*
+ * EVP_PKEY
+ */
+struct evp_pkey_st *SSL_get_privatekey(const SSL *ssl);
+
+__owur X509 *SSL_CTX_get0_certificate(const SSL_CTX *ctx);
+__owur EVP_PKEY *SSL_CTX_get0_privatekey(const SSL_CTX *ctx);
+
+void SSL_CTX_set_quiet_shutdown(SSL_CTX *ctx, int mode);
+__owur int SSL_CTX_get_quiet_shutdown(const SSL_CTX *ctx);
+void SSL_set_quiet_shutdown(SSL *ssl, int mode);
+__owur int SSL_get_quiet_shutdown(const SSL *ssl);
+void SSL_set_shutdown(SSL *ssl, int mode);
+__owur int SSL_get_shutdown(const SSL *ssl);
+__owur int SSL_version(const SSL *ssl);
+__owur int SSL_client_version(const SSL *s);
+__owur int SSL_CTX_set_default_verify_paths(SSL_CTX *ctx);
+__owur int SSL_CTX_set_default_verify_dir(SSL_CTX *ctx);
+__owur int SSL_CTX_set_default_verify_file(SSL_CTX *ctx);
+__owur int SSL_CTX_set_default_verify_store(SSL_CTX *ctx);
+__owur int SSL_CTX_load_verify_file(SSL_CTX *ctx, const char *CAfile);
+__owur int SSL_CTX_load_verify_dir(SSL_CTX *ctx, const char *CApath);
+__owur int SSL_CTX_load_verify_store(SSL_CTX *ctx, const char *CAstore);
+__owur int SSL_CTX_load_verify_locations(SSL_CTX *ctx,
+ const char *CAfile,
+ const char *CApath);
+# define SSL_get0_session SSL_get_session/* just peek at pointer */
+__owur SSL_SESSION *SSL_get_session(const SSL *ssl);
+__owur SSL_SESSION *SSL_get1_session(SSL *ssl); /* obtain a reference count */
+__owur SSL_CTX *SSL_get_SSL_CTX(const SSL *ssl);
+SSL_CTX *SSL_set_SSL_CTX(SSL *ssl, SSL_CTX *ctx);
+void SSL_set_info_callback(SSL *ssl,
+ void (*cb) (const SSL *ssl, int type, int val));
+void (*SSL_get_info_callback(const SSL *ssl)) (const SSL *ssl, int type,
+ int val);
+__owur OSSL_HANDSHAKE_STATE SSL_get_state(const SSL *ssl);
+
+void SSL_set_verify_result(SSL *ssl, long v);
+__owur long SSL_get_verify_result(const SSL *ssl);
+__owur STACK_OF(X509) *SSL_get0_verified_chain(const SSL *s);
+
+__owur size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
+ size_t outlen);
+__owur size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
+ size_t outlen);
+__owur size_t SSL_SESSION_get_master_key(const SSL_SESSION *sess,
+ unsigned char *out, size_t outlen);
+__owur int SSL_SESSION_set1_master_key(SSL_SESSION *sess,
+ const unsigned char *in, size_t len);
+uint8_t SSL_SESSION_get_max_fragment_length(const SSL_SESSION *sess);
+
+#define SSL_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL, l, p, newf, dupf, freef)
+__owur int SSL_set_ex_data(SSL *ssl, int idx, void *data);
+void *SSL_get_ex_data(const SSL *ssl, int idx);
+#define SSL_SESSION_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_SESSION, l, p, newf, dupf, freef)
+__owur int SSL_SESSION_set_ex_data(SSL_SESSION *ss, int idx, void *data);
+void *SSL_SESSION_get_ex_data(const SSL_SESSION *ss, int idx);
+#define SSL_CTX_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_SSL_CTX, l, p, newf, dupf, freef)
+__owur int SSL_CTX_set_ex_data(SSL_CTX *ssl, int idx, void *data);
+void *SSL_CTX_get_ex_data(const SSL_CTX *ssl, int idx);
+
+__owur int SSL_get_ex_data_X509_STORE_CTX_idx(void);
+
+# define SSL_CTX_sess_set_cache_size(ctx,t) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_SIZE,t,NULL)
+# define SSL_CTX_sess_get_cache_size(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_SIZE,0,NULL)
+# define SSL_CTX_set_session_cache_mode(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SESS_CACHE_MODE,m,NULL)
+# define SSL_CTX_get_session_cache_mode(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_SESS_CACHE_MODE,0,NULL)
+
+# define SSL_CTX_get_default_read_ahead(ctx) SSL_CTX_get_read_ahead(ctx)
+# define SSL_CTX_set_default_read_ahead(ctx,m) SSL_CTX_set_read_ahead(ctx,m)
+# define SSL_CTX_get_read_ahead(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_READ_AHEAD,0,NULL)
+# define SSL_CTX_set_read_ahead(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_READ_AHEAD,m,NULL)
+# define SSL_CTX_get_max_cert_list(ctx) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
+# define SSL_CTX_set_max_cert_list(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
+# define SSL_get_max_cert_list(ssl) \
+ SSL_ctrl(ssl,SSL_CTRL_GET_MAX_CERT_LIST,0,NULL)
+# define SSL_set_max_cert_list(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_MAX_CERT_LIST,m,NULL)
+
+# define SSL_CTX_set_max_send_fragment(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
+# define SSL_set_max_send_fragment(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_MAX_SEND_FRAGMENT,m,NULL)
+# define SSL_CTX_set_split_send_fragment(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL)
+# define SSL_set_split_send_fragment(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_SPLIT_SEND_FRAGMENT,m,NULL)
+# define SSL_CTX_set_max_pipelines(ctx,m) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_MAX_PIPELINES,m,NULL)
+# define SSL_set_max_pipelines(ssl,m) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_MAX_PIPELINES,m,NULL)
+
+void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len);
+void SSL_set_default_read_buffer_len(SSL *s, size_t len);
+
+# ifndef OPENSSL_NO_DH
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+/* NB: the |keylength| is only applicable when is_export is true */
+OSSL_DEPRECATEDIN_3_0
+void SSL_CTX_set_tmp_dh_callback(SSL_CTX *ctx,
+ DH *(*dh) (SSL *ssl, int is_export,
+ int keylength));
+OSSL_DEPRECATEDIN_3_0
+void SSL_set_tmp_dh_callback(SSL *ssl,
+ DH *(*dh) (SSL *ssl, int is_export,
+ int keylength));
+# endif
+# endif
+
+__owur const COMP_METHOD *SSL_get_current_compression(const SSL *s);
+__owur const COMP_METHOD *SSL_get_current_expansion(const SSL *s);
+__owur const char *SSL_COMP_get_name(const COMP_METHOD *comp);
+__owur const char *SSL_COMP_get0_name(const SSL_COMP *comp);
+__owur int SSL_COMP_get_id(const SSL_COMP *comp);
+STACK_OF(SSL_COMP) *SSL_COMP_get_compression_methods(void);
+__owur STACK_OF(SSL_COMP) *SSL_COMP_set0_compression_methods(STACK_OF(SSL_COMP)
+ *meths);
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_COMP_free_compression_methods() while(0) continue
+# endif
+__owur int SSL_COMP_add_compression_method(int id, COMP_METHOD *cm);
+
+const SSL_CIPHER *SSL_CIPHER_find(SSL *ssl, const unsigned char *ptr);
+int SSL_CIPHER_get_cipher_nid(const SSL_CIPHER *c);
+int SSL_CIPHER_get_digest_nid(const SSL_CIPHER *c);
+int SSL_bytes_to_cipher_list(SSL *s, const unsigned char *bytes, size_t len,
+ int isv2format, STACK_OF(SSL_CIPHER) **sk,
+ STACK_OF(SSL_CIPHER) **scsvs);
+
+/* TLS extensions functions */
+__owur int SSL_set_session_ticket_ext(SSL *s, void *ext_data, int ext_len);
+
+__owur int SSL_set_session_ticket_ext_cb(SSL *s,
+ tls_session_ticket_ext_cb_fn cb,
+ void *arg);
+
+/* Pre-shared secret session resumption functions */
+__owur int SSL_set_session_secret_cb(SSL *s,
+ tls_session_secret_cb_fn session_secret_cb,
+ void *arg);
+
+void SSL_CTX_set_not_resumable_session_callback(SSL_CTX *ctx,
+ int (*cb) (SSL *ssl,
+ int
+ is_forward_secure));
+
+void SSL_set_not_resumable_session_callback(SSL *ssl,
+ int (*cb) (SSL *ssl,
+ int is_forward_secure));
+
+void SSL_CTX_set_record_padding_callback(SSL_CTX *ctx,
+ size_t (*cb) (SSL *ssl, int type,
+ size_t len, void *arg));
+void SSL_CTX_set_record_padding_callback_arg(SSL_CTX *ctx, void *arg);
+void *SSL_CTX_get_record_padding_callback_arg(const SSL_CTX *ctx);
+int SSL_CTX_set_block_padding(SSL_CTX *ctx, size_t block_size);
+
+int SSL_set_record_padding_callback(SSL *ssl,
+ size_t (*cb) (SSL *ssl, int type,
+ size_t len, void *arg));
+void SSL_set_record_padding_callback_arg(SSL *ssl, void *arg);
+void *SSL_get_record_padding_callback_arg(const SSL *ssl);
+int SSL_set_block_padding(SSL *ssl, size_t block_size);
+
+int SSL_set_num_tickets(SSL *s, size_t num_tickets);
+size_t SSL_get_num_tickets(const SSL *s);
+int SSL_CTX_set_num_tickets(SSL_CTX *ctx, size_t num_tickets);
+size_t SSL_CTX_get_num_tickets(const SSL_CTX *ctx);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define SSL_cache_hit(s) SSL_session_reused(s)
+# endif
+
+__owur int SSL_session_reused(const SSL *s);
+__owur int SSL_is_server(const SSL *s);
+
+__owur __owur SSL_CONF_CTX *SSL_CONF_CTX_new(void);
+int SSL_CONF_CTX_finish(SSL_CONF_CTX *cctx);
+void SSL_CONF_CTX_free(SSL_CONF_CTX *cctx);
+unsigned int SSL_CONF_CTX_set_flags(SSL_CONF_CTX *cctx, unsigned int flags);
+__owur unsigned int SSL_CONF_CTX_clear_flags(SSL_CONF_CTX *cctx,
+ unsigned int flags);
+__owur int SSL_CONF_CTX_set1_prefix(SSL_CONF_CTX *cctx, const char *pre);
+
+void SSL_CONF_CTX_set_ssl(SSL_CONF_CTX *cctx, SSL *ssl);
+void SSL_CONF_CTX_set_ssl_ctx(SSL_CONF_CTX *cctx, SSL_CTX *ctx);
+
+__owur int SSL_CONF_cmd(SSL_CONF_CTX *cctx, const char *cmd, const char *value);
+__owur int SSL_CONF_cmd_argv(SSL_CONF_CTX *cctx, int *pargc, char ***pargv);
+__owur int SSL_CONF_cmd_value_type(SSL_CONF_CTX *cctx, const char *cmd);
+
+void SSL_add_ssl_module(void);
+int SSL_config(SSL *s, const char *name);
+int SSL_CTX_config(SSL_CTX *ctx, const char *name);
+
+# ifndef OPENSSL_NO_SSL_TRACE
+void SSL_trace(int write_p, int version, int content_type,
+ const void *buf, size_t len, SSL *ssl, void *arg);
+# endif
+
+# ifndef OPENSSL_NO_SOCK
+int DTLSv1_listen(SSL *s, BIO_ADDR *client);
+# endif
+
+# ifndef OPENSSL_NO_CT
+
+/*
+ * A callback for verifying that the received SCTs are sufficient.
+ * Expected to return 1 if they are sufficient, otherwise 0.
+ * May return a negative integer if an error occurs.
+ * A connection should be aborted if the SCTs are deemed insufficient.
+ */
+typedef int (*ssl_ct_validation_cb)(const CT_POLICY_EVAL_CTX *ctx,
+ const STACK_OF(SCT) *scts, void *arg);
+
+/*
+ * Sets a |callback| that is invoked upon receipt of ServerHelloDone to validate
+ * the received SCTs.
+ * If the callback returns a non-positive result, the connection is terminated.
+ * Call this function before beginning a handshake.
+ * If a NULL |callback| is provided, SCT validation is disabled.
+ * |arg| is arbitrary userdata that will be passed to the callback whenever it
+ * is invoked. Ownership of |arg| remains with the caller.
+ *
+ * NOTE: A side-effect of setting a CT callback is that an OCSP stapled response
+ * will be requested.
+ */
+int SSL_set_ct_validation_callback(SSL *s, ssl_ct_validation_cb callback,
+ void *arg);
+int SSL_CTX_set_ct_validation_callback(SSL_CTX *ctx,
+ ssl_ct_validation_cb callback,
+ void *arg);
+#define SSL_disable_ct(s) \
+ ((void) SSL_set_validation_callback((s), NULL, NULL))
+#define SSL_CTX_disable_ct(ctx) \
+ ((void) SSL_CTX_set_validation_callback((ctx), NULL, NULL))
+
+/*
+ * The validation type enumerates the available behaviours of the built-in SSL
+ * CT validation callback selected via SSL_enable_ct() and SSL_CTX_enable_ct().
+ * The underlying callback is a static function in libssl.
+ */
+enum {
+ SSL_CT_VALIDATION_PERMISSIVE = 0,
+ SSL_CT_VALIDATION_STRICT
+};
+
+/*
+ * Enable CT by setting up a callback that implements one of the built-in
+ * validation variants. The SSL_CT_VALIDATION_PERMISSIVE variant always
+ * continues the handshake, the application can make appropriate decisions at
+ * handshake completion. The SSL_CT_VALIDATION_STRICT variant requires at
+ * least one valid SCT, or else handshake termination will be requested. The
+ * handshake may continue anyway if SSL_VERIFY_NONE is in effect.
+ */
+int SSL_enable_ct(SSL *s, int validation_mode);
+int SSL_CTX_enable_ct(SSL_CTX *ctx, int validation_mode);
+
+/*
+ * Report whether a non-NULL callback is enabled.
+ */
+int SSL_ct_is_enabled(const SSL *s);
+int SSL_CTX_ct_is_enabled(const SSL_CTX *ctx);
+
+/* Gets the SCTs received from a connection */
+const STACK_OF(SCT) *SSL_get0_peer_scts(SSL *s);
+
+/*
+ * Loads the CT log list from the default location.
+ * If a CTLOG_STORE has previously been set using SSL_CTX_set_ctlog_store,
+ * the log information loaded from this file will be appended to the
+ * CTLOG_STORE.
+ * Returns 1 on success, 0 otherwise.
+ */
+int SSL_CTX_set_default_ctlog_list_file(SSL_CTX *ctx);
+
+/*
+ * Loads the CT log list from the specified file path.
+ * If a CTLOG_STORE has previously been set using SSL_CTX_set_ctlog_store,
+ * the log information loaded from this file will be appended to the
+ * CTLOG_STORE.
+ * Returns 1 on success, 0 otherwise.
+ */
+int SSL_CTX_set_ctlog_list_file(SSL_CTX *ctx, const char *path);
+
+/*
+ * Sets the CT log list used by all SSL connections created from this SSL_CTX.
+ * Ownership of the CTLOG_STORE is transferred to the SSL_CTX.
+ */
+void SSL_CTX_set0_ctlog_store(SSL_CTX *ctx, CTLOG_STORE *logs);
+
+/*
+ * Gets the CT log list used by all SSL connections created from this SSL_CTX.
+ * This will be NULL unless one of the following functions has been called:
+ * - SSL_CTX_set_default_ctlog_list_file
+ * - SSL_CTX_set_ctlog_list_file
+ * - SSL_CTX_set_ctlog_store
+ */
+const CTLOG_STORE *SSL_CTX_get0_ctlog_store(const SSL_CTX *ctx);
+
+# endif /* OPENSSL_NO_CT */
+
+/* What the "other" parameter contains in security callback */
+/* Mask for type */
+# define SSL_SECOP_OTHER_TYPE 0xffff0000
+# define SSL_SECOP_OTHER_NONE 0
+# define SSL_SECOP_OTHER_CIPHER (1 << 16)
+# define SSL_SECOP_OTHER_CURVE (2 << 16)
+# define SSL_SECOP_OTHER_DH (3 << 16)
+# define SSL_SECOP_OTHER_PKEY (4 << 16)
+# define SSL_SECOP_OTHER_SIGALG (5 << 16)
+# define SSL_SECOP_OTHER_CERT (6 << 16)
+
+/* Indicated operation refers to peer key or certificate */
+# define SSL_SECOP_PEER 0x1000
+
+/* Values for "op" parameter in security callback */
+
+/* Called to filter ciphers */
+/* Ciphers client supports */
+# define SSL_SECOP_CIPHER_SUPPORTED (1 | SSL_SECOP_OTHER_CIPHER)
+/* Cipher shared by client/server */
+# define SSL_SECOP_CIPHER_SHARED (2 | SSL_SECOP_OTHER_CIPHER)
+/* Sanity check of cipher server selects */
+# define SSL_SECOP_CIPHER_CHECK (3 | SSL_SECOP_OTHER_CIPHER)
+/* Curves supported by client */
+# define SSL_SECOP_CURVE_SUPPORTED (4 | SSL_SECOP_OTHER_CURVE)
+/* Curves shared by client/server */
+# define SSL_SECOP_CURVE_SHARED (5 | SSL_SECOP_OTHER_CURVE)
+/* Sanity check of curve server selects */
+# define SSL_SECOP_CURVE_CHECK (6 | SSL_SECOP_OTHER_CURVE)
+/* Temporary DH key */
+# define SSL_SECOP_TMP_DH (7 | SSL_SECOP_OTHER_PKEY)
+/* SSL/TLS version */
+# define SSL_SECOP_VERSION (9 | SSL_SECOP_OTHER_NONE)
+/* Session tickets */
+# define SSL_SECOP_TICKET (10 | SSL_SECOP_OTHER_NONE)
+/* Supported signature algorithms sent to peer */
+# define SSL_SECOP_SIGALG_SUPPORTED (11 | SSL_SECOP_OTHER_SIGALG)
+/* Shared signature algorithm */
+# define SSL_SECOP_SIGALG_SHARED (12 | SSL_SECOP_OTHER_SIGALG)
+/* Sanity check signature algorithm allowed */
+# define SSL_SECOP_SIGALG_CHECK (13 | SSL_SECOP_OTHER_SIGALG)
+/* Used to get mask of supported public key signature algorithms */
+# define SSL_SECOP_SIGALG_MASK (14 | SSL_SECOP_OTHER_SIGALG)
+/* Use to see if compression is allowed */
+# define SSL_SECOP_COMPRESSION (15 | SSL_SECOP_OTHER_NONE)
+/* EE key in certificate */
+# define SSL_SECOP_EE_KEY (16 | SSL_SECOP_OTHER_CERT)
+/* CA key in certificate */
+# define SSL_SECOP_CA_KEY (17 | SSL_SECOP_OTHER_CERT)
+/* CA digest algorithm in certificate */
+# define SSL_SECOP_CA_MD (18 | SSL_SECOP_OTHER_CERT)
+/* Peer EE key in certificate */
+# define SSL_SECOP_PEER_EE_KEY (SSL_SECOP_EE_KEY | SSL_SECOP_PEER)
+/* Peer CA key in certificate */
+# define SSL_SECOP_PEER_CA_KEY (SSL_SECOP_CA_KEY | SSL_SECOP_PEER)
+/* Peer CA digest algorithm in certificate */
+# define SSL_SECOP_PEER_CA_MD (SSL_SECOP_CA_MD | SSL_SECOP_PEER)
+
+void SSL_set_security_level(SSL *s, int level);
+__owur int SSL_get_security_level(const SSL *s);
+void SSL_set_security_callback(SSL *s,
+ int (*cb) (const SSL *s, const SSL_CTX *ctx,
+ int op, int bits, int nid,
+ void *other, void *ex));
+int (*SSL_get_security_callback(const SSL *s)) (const SSL *s,
+ const SSL_CTX *ctx, int op,
+ int bits, int nid, void *other,
+ void *ex);
+void SSL_set0_security_ex_data(SSL *s, void *ex);
+__owur void *SSL_get0_security_ex_data(const SSL *s);
+
+void SSL_CTX_set_security_level(SSL_CTX *ctx, int level);
+__owur int SSL_CTX_get_security_level(const SSL_CTX *ctx);
+void SSL_CTX_set_security_callback(SSL_CTX *ctx,
+ int (*cb) (const SSL *s, const SSL_CTX *ctx,
+ int op, int bits, int nid,
+ void *other, void *ex));
+int (*SSL_CTX_get_security_callback(const SSL_CTX *ctx)) (const SSL *s,
+ const SSL_CTX *ctx,
+ int op, int bits,
+ int nid,
+ void *other,
+ void *ex);
+void SSL_CTX_set0_security_ex_data(SSL_CTX *ctx, void *ex);
+__owur void *SSL_CTX_get0_security_ex_data(const SSL_CTX *ctx);
+
+/* OPENSSL_INIT flag 0x010000 reserved for internal use */
+# define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L
+# define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L
+
+# define OPENSSL_INIT_SSL_DEFAULT \
+ (OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS)
+
+int OPENSSL_init_ssl(uint64_t opts, const OPENSSL_INIT_SETTINGS *settings);
+
+# ifndef OPENSSL_NO_UNIT_TEST
+__owur const struct openssl_ssl_test_functions *SSL_test_functions(void);
+# endif
+
+__owur int SSL_free_buffers(SSL *ssl);
+__owur int SSL_alloc_buffers(SSL *ssl);
+
+/* Status codes passed to the decrypt session ticket callback. Some of these
+ * are for internal use only and are never passed to the callback. */
+typedef int SSL_TICKET_STATUS;
+
+/* Support for ticket appdata */
+/* fatal error, malloc failure */
+# define SSL_TICKET_FATAL_ERR_MALLOC 0
+/* fatal error, either from parsing or decrypting the ticket */
+# define SSL_TICKET_FATAL_ERR_OTHER 1
+/* No ticket present */
+# define SSL_TICKET_NONE 2
+/* Empty ticket present */
+# define SSL_TICKET_EMPTY 3
+/* the ticket couldn't be decrypted */
+# define SSL_TICKET_NO_DECRYPT 4
+/* a ticket was successfully decrypted */
+# define SSL_TICKET_SUCCESS 5
+/* same as above but the ticket needs to be renewed */
+# define SSL_TICKET_SUCCESS_RENEW 6
+
+/* Return codes for the decrypt session ticket callback */
+typedef int SSL_TICKET_RETURN;
+
+/* An error occurred */
+#define SSL_TICKET_RETURN_ABORT 0
+/* Do not use the ticket, do not send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_IGNORE 1
+/* Do not use the ticket, send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_IGNORE_RENEW 2
+/* Use the ticket, do not send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_USE 3
+/* Use the ticket, send a renewed ticket to the client */
+#define SSL_TICKET_RETURN_USE_RENEW 4
+
+typedef int (*SSL_CTX_generate_session_ticket_fn)(SSL *s, void *arg);
+typedef SSL_TICKET_RETURN (*SSL_CTX_decrypt_session_ticket_fn)(SSL *s, SSL_SESSION *ss,
+ const unsigned char *keyname,
+ size_t keyname_length,
+ SSL_TICKET_STATUS status,
+ void *arg);
+int SSL_CTX_set_session_ticket_cb(SSL_CTX *ctx,
+ SSL_CTX_generate_session_ticket_fn gen_cb,
+ SSL_CTX_decrypt_session_ticket_fn dec_cb,
+ void *arg);
+int SSL_SESSION_set1_ticket_appdata(SSL_SESSION *ss, const void *data, size_t len);
+int SSL_SESSION_get0_ticket_appdata(SSL_SESSION *ss, void **data, size_t *len);
+
+typedef unsigned int (*DTLS_timer_cb)(SSL *s, unsigned int timer_us);
+
+void DTLS_set_timer_cb(SSL *s, DTLS_timer_cb cb);
+
+
+typedef int (*SSL_allow_early_data_cb_fn)(SSL *s, void *arg);
+void SSL_CTX_set_allow_early_data_cb(SSL_CTX *ctx,
+ SSL_allow_early_data_cb_fn cb,
+ void *arg);
+void SSL_set_allow_early_data_cb(SSL *s,
+ SSL_allow_early_data_cb_fn cb,
+ void *arg);
+
+/* store the default cipher strings inside the library */
+const char *OSSL_default_cipher_list(void);
+const char *OSSL_default_ciphersuites(void);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/ssl2.h b/include/openssl/ssl2.h
new file mode 100644
index 00000000..428ead05
--- /dev/null
+++ b/include/openssl/ssl2.h
@@ -0,0 +1,30 @@
+/*
+ * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_SSL2_H
+# define OPENSSL_SSL2_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SSL2_H
+# endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define SSL2_VERSION 0x0002
+
+# define SSL2_MT_CLIENT_HELLO 1
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/ssl3.h b/include/openssl/ssl3.h
new file mode 100644
index 00000000..49bd51f2
--- /dev/null
+++ b/include/openssl/ssl3.h
@@ -0,0 +1,347 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_SSL3_H
+# define OPENSSL_SSL3_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SSL3_H
+# endif
+
+# include <openssl/comp.h>
+# include <openssl/buffer.h>
+# include <openssl/evp.h>
+# include <openssl/ssl.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Signalling cipher suite value from RFC 5746
+ * (TLS_EMPTY_RENEGOTIATION_INFO_SCSV)
+ */
+# define SSL3_CK_SCSV 0x030000FF
+
+/*
+ * Signalling cipher suite value from draft-ietf-tls-downgrade-scsv-00
+ * (TLS_FALLBACK_SCSV)
+ */
+# define SSL3_CK_FALLBACK_SCSV 0x03005600
+
+# define SSL3_CK_RSA_NULL_MD5 0x03000001
+# define SSL3_CK_RSA_NULL_SHA 0x03000002
+# define SSL3_CK_RSA_RC4_40_MD5 0x03000003
+# define SSL3_CK_RSA_RC4_128_MD5 0x03000004
+# define SSL3_CK_RSA_RC4_128_SHA 0x03000005
+# define SSL3_CK_RSA_RC2_40_MD5 0x03000006
+# define SSL3_CK_RSA_IDEA_128_SHA 0x03000007
+# define SSL3_CK_RSA_DES_40_CBC_SHA 0x03000008
+# define SSL3_CK_RSA_DES_64_CBC_SHA 0x03000009
+# define SSL3_CK_RSA_DES_192_CBC3_SHA 0x0300000A
+
+# define SSL3_CK_DH_DSS_DES_40_CBC_SHA 0x0300000B
+# define SSL3_CK_DH_DSS_DES_64_CBC_SHA 0x0300000C
+# define SSL3_CK_DH_DSS_DES_192_CBC3_SHA 0x0300000D
+# define SSL3_CK_DH_RSA_DES_40_CBC_SHA 0x0300000E
+# define SSL3_CK_DH_RSA_DES_64_CBC_SHA 0x0300000F
+# define SSL3_CK_DH_RSA_DES_192_CBC3_SHA 0x03000010
+
+# define SSL3_CK_DHE_DSS_DES_40_CBC_SHA 0x03000011
+# define SSL3_CK_EDH_DSS_DES_40_CBC_SHA SSL3_CK_DHE_DSS_DES_40_CBC_SHA
+# define SSL3_CK_DHE_DSS_DES_64_CBC_SHA 0x03000012
+# define SSL3_CK_EDH_DSS_DES_64_CBC_SHA SSL3_CK_DHE_DSS_DES_64_CBC_SHA
+# define SSL3_CK_DHE_DSS_DES_192_CBC3_SHA 0x03000013
+# define SSL3_CK_EDH_DSS_DES_192_CBC3_SHA SSL3_CK_DHE_DSS_DES_192_CBC3_SHA
+# define SSL3_CK_DHE_RSA_DES_40_CBC_SHA 0x03000014
+# define SSL3_CK_EDH_RSA_DES_40_CBC_SHA SSL3_CK_DHE_RSA_DES_40_CBC_SHA
+# define SSL3_CK_DHE_RSA_DES_64_CBC_SHA 0x03000015
+# define SSL3_CK_EDH_RSA_DES_64_CBC_SHA SSL3_CK_DHE_RSA_DES_64_CBC_SHA
+# define SSL3_CK_DHE_RSA_DES_192_CBC3_SHA 0x03000016
+# define SSL3_CK_EDH_RSA_DES_192_CBC3_SHA SSL3_CK_DHE_RSA_DES_192_CBC3_SHA
+
+# define SSL3_CK_ADH_RC4_40_MD5 0x03000017
+# define SSL3_CK_ADH_RC4_128_MD5 0x03000018
+# define SSL3_CK_ADH_DES_40_CBC_SHA 0x03000019
+# define SSL3_CK_ADH_DES_64_CBC_SHA 0x0300001A
+# define SSL3_CK_ADH_DES_192_CBC_SHA 0x0300001B
+
+/* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] */
+# define SSL3_RFC_RSA_NULL_MD5 "TLS_RSA_WITH_NULL_MD5"
+# define SSL3_RFC_RSA_NULL_SHA "TLS_RSA_WITH_NULL_SHA"
+# define SSL3_RFC_RSA_DES_192_CBC3_SHA "TLS_RSA_WITH_3DES_EDE_CBC_SHA"
+# define SSL3_RFC_DHE_DSS_DES_192_CBC3_SHA "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"
+# define SSL3_RFC_DHE_RSA_DES_192_CBC3_SHA "TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"
+# define SSL3_RFC_ADH_DES_192_CBC_SHA "TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"
+# define SSL3_RFC_RSA_IDEA_128_SHA "TLS_RSA_WITH_IDEA_CBC_SHA"
+# define SSL3_RFC_RSA_RC4_128_MD5 "TLS_RSA_WITH_RC4_128_MD5"
+# define SSL3_RFC_RSA_RC4_128_SHA "TLS_RSA_WITH_RC4_128_SHA"
+# define SSL3_RFC_ADH_RC4_128_MD5 "TLS_DH_anon_WITH_RC4_128_MD5"
+
+# define SSL3_TXT_RSA_NULL_MD5 "NULL-MD5"
+# define SSL3_TXT_RSA_NULL_SHA "NULL-SHA"
+# define SSL3_TXT_RSA_RC4_40_MD5 "EXP-RC4-MD5"
+# define SSL3_TXT_RSA_RC4_128_MD5 "RC4-MD5"
+# define SSL3_TXT_RSA_RC4_128_SHA "RC4-SHA"
+# define SSL3_TXT_RSA_RC2_40_MD5 "EXP-RC2-CBC-MD5"
+# define SSL3_TXT_RSA_IDEA_128_SHA "IDEA-CBC-SHA"
+# define SSL3_TXT_RSA_DES_40_CBC_SHA "EXP-DES-CBC-SHA"
+# define SSL3_TXT_RSA_DES_64_CBC_SHA "DES-CBC-SHA"
+# define SSL3_TXT_RSA_DES_192_CBC3_SHA "DES-CBC3-SHA"
+
+# define SSL3_TXT_DH_DSS_DES_40_CBC_SHA "EXP-DH-DSS-DES-CBC-SHA"
+# define SSL3_TXT_DH_DSS_DES_64_CBC_SHA "DH-DSS-DES-CBC-SHA"
+# define SSL3_TXT_DH_DSS_DES_192_CBC3_SHA "DH-DSS-DES-CBC3-SHA"
+# define SSL3_TXT_DH_RSA_DES_40_CBC_SHA "EXP-DH-RSA-DES-CBC-SHA"
+# define SSL3_TXT_DH_RSA_DES_64_CBC_SHA "DH-RSA-DES-CBC-SHA"
+# define SSL3_TXT_DH_RSA_DES_192_CBC3_SHA "DH-RSA-DES-CBC3-SHA"
+
+# define SSL3_TXT_DHE_DSS_DES_40_CBC_SHA "EXP-DHE-DSS-DES-CBC-SHA"
+# define SSL3_TXT_DHE_DSS_DES_64_CBC_SHA "DHE-DSS-DES-CBC-SHA"
+# define SSL3_TXT_DHE_DSS_DES_192_CBC3_SHA "DHE-DSS-DES-CBC3-SHA"
+# define SSL3_TXT_DHE_RSA_DES_40_CBC_SHA "EXP-DHE-RSA-DES-CBC-SHA"
+# define SSL3_TXT_DHE_RSA_DES_64_CBC_SHA "DHE-RSA-DES-CBC-SHA"
+# define SSL3_TXT_DHE_RSA_DES_192_CBC3_SHA "DHE-RSA-DES-CBC3-SHA"
+
+/*
+ * This next block of six "EDH" labels is for backward compatibility with
+ * older versions of OpenSSL. New code should use the six "DHE" labels above
+ * instead:
+ */
+# define SSL3_TXT_EDH_DSS_DES_40_CBC_SHA "EXP-EDH-DSS-DES-CBC-SHA"
+# define SSL3_TXT_EDH_DSS_DES_64_CBC_SHA "EDH-DSS-DES-CBC-SHA"
+# define SSL3_TXT_EDH_DSS_DES_192_CBC3_SHA "EDH-DSS-DES-CBC3-SHA"
+# define SSL3_TXT_EDH_RSA_DES_40_CBC_SHA "EXP-EDH-RSA-DES-CBC-SHA"
+# define SSL3_TXT_EDH_RSA_DES_64_CBC_SHA "EDH-RSA-DES-CBC-SHA"
+# define SSL3_TXT_EDH_RSA_DES_192_CBC3_SHA "EDH-RSA-DES-CBC3-SHA"
+
+# define SSL3_TXT_ADH_RC4_40_MD5 "EXP-ADH-RC4-MD5"
+# define SSL3_TXT_ADH_RC4_128_MD5 "ADH-RC4-MD5"
+# define SSL3_TXT_ADH_DES_40_CBC_SHA "EXP-ADH-DES-CBC-SHA"
+# define SSL3_TXT_ADH_DES_64_CBC_SHA "ADH-DES-CBC-SHA"
+# define SSL3_TXT_ADH_DES_192_CBC_SHA "ADH-DES-CBC3-SHA"
+
+# define SSL3_SSL_SESSION_ID_LENGTH 32
+# define SSL3_MAX_SSL_SESSION_ID_LENGTH 32
+
+# define SSL3_MASTER_SECRET_SIZE 48
+# define SSL3_RANDOM_SIZE 32
+# define SSL3_SESSION_ID_SIZE 32
+# define SSL3_RT_HEADER_LENGTH 5
+
+# define SSL3_HM_HEADER_LENGTH 4
+
+# ifndef SSL3_ALIGN_PAYLOAD
+ /*
+ * Some will argue that this increases memory footprint, but it's not
+ * actually true. Point is that malloc has to return at least 64-bit aligned
+ * pointers, meaning that allocating 5 bytes wastes 3 bytes in either case.
+ * Suggested pre-gaping simply moves these wasted bytes from the end of
+ * allocated region to its front, but makes data payload aligned, which
+ * improves performance:-)
+ */
+# define SSL3_ALIGN_PAYLOAD 8
+# else
+# if (SSL3_ALIGN_PAYLOAD&(SSL3_ALIGN_PAYLOAD-1))!=0
+# error "insane SSL3_ALIGN_PAYLOAD"
+# undef SSL3_ALIGN_PAYLOAD
+# endif
+# endif
+
+/*
+ * This is the maximum MAC (digest) size used by the SSL library. Currently
+ * maximum of 20 is used by SHA1, but we reserve for future extension for
+ * 512-bit hashes.
+ */
+
+# define SSL3_RT_MAX_MD_SIZE 64
+
+/*
+ * Maximum block size used in all ciphersuites. Currently 16 for AES.
+ */
+
+# define SSL_RT_MAX_CIPHER_BLOCK_SIZE 16
+
+# define SSL3_RT_MAX_EXTRA (16384)
+
+/* Maximum plaintext length: defined by SSL/TLS standards */
+# define SSL3_RT_MAX_PLAIN_LENGTH 16384
+/* Maximum compression overhead: defined by SSL/TLS standards */
+# define SSL3_RT_MAX_COMPRESSED_OVERHEAD 1024
+
+/*
+ * The standards give a maximum encryption overhead of 1024 bytes. In
+ * practice the value is lower than this. The overhead is the maximum number
+ * of padding bytes (256) plus the mac size.
+ */
+# define SSL3_RT_MAX_ENCRYPTED_OVERHEAD (256 + SSL3_RT_MAX_MD_SIZE)
+# define SSL3_RT_MAX_TLS13_ENCRYPTED_OVERHEAD 256
+
+/*
+ * OpenSSL currently only uses a padding length of at most one block so the
+ * send overhead is smaller.
+ */
+
+# define SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD \
+ (SSL_RT_MAX_CIPHER_BLOCK_SIZE + SSL3_RT_MAX_MD_SIZE)
+
+/* If compression isn't used don't include the compression overhead */
+
+# ifdef OPENSSL_NO_COMP
+# define SSL3_RT_MAX_COMPRESSED_LENGTH SSL3_RT_MAX_PLAIN_LENGTH
+# else
+# define SSL3_RT_MAX_COMPRESSED_LENGTH \
+ (SSL3_RT_MAX_PLAIN_LENGTH+SSL3_RT_MAX_COMPRESSED_OVERHEAD)
+# endif
+# define SSL3_RT_MAX_ENCRYPTED_LENGTH \
+ (SSL3_RT_MAX_ENCRYPTED_OVERHEAD+SSL3_RT_MAX_COMPRESSED_LENGTH)
+# define SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH \
+ (SSL3_RT_MAX_PLAIN_LENGTH + SSL3_RT_MAX_TLS13_ENCRYPTED_OVERHEAD)
+# define SSL3_RT_MAX_PACKET_SIZE \
+ (SSL3_RT_MAX_ENCRYPTED_LENGTH+SSL3_RT_HEADER_LENGTH)
+
+# define SSL3_MD_CLIENT_FINISHED_CONST "\x43\x4C\x4E\x54"
+# define SSL3_MD_SERVER_FINISHED_CONST "\x53\x52\x56\x52"
+
+/* SSL3_VERSION is defined in prov_ssl.h */
+# define SSL3_VERSION_MAJOR 0x03
+# define SSL3_VERSION_MINOR 0x00
+
+# define SSL3_RT_CHANGE_CIPHER_SPEC 20
+# define SSL3_RT_ALERT 21
+# define SSL3_RT_HANDSHAKE 22
+# define SSL3_RT_APPLICATION_DATA 23
+
+/* Pseudo content types to indicate additional parameters */
+# define TLS1_RT_CRYPTO 0x1000
+# define TLS1_RT_CRYPTO_PREMASTER (TLS1_RT_CRYPTO | 0x1)
+# define TLS1_RT_CRYPTO_CLIENT_RANDOM (TLS1_RT_CRYPTO | 0x2)
+# define TLS1_RT_CRYPTO_SERVER_RANDOM (TLS1_RT_CRYPTO | 0x3)
+# define TLS1_RT_CRYPTO_MASTER (TLS1_RT_CRYPTO | 0x4)
+
+# define TLS1_RT_CRYPTO_READ 0x0000
+# define TLS1_RT_CRYPTO_WRITE 0x0100
+# define TLS1_RT_CRYPTO_MAC (TLS1_RT_CRYPTO | 0x5)
+# define TLS1_RT_CRYPTO_KEY (TLS1_RT_CRYPTO | 0x6)
+# define TLS1_RT_CRYPTO_IV (TLS1_RT_CRYPTO | 0x7)
+# define TLS1_RT_CRYPTO_FIXED_IV (TLS1_RT_CRYPTO | 0x8)
+
+/* Pseudo content types for SSL/TLS header info */
+# define SSL3_RT_HEADER 0x100
+# define SSL3_RT_INNER_CONTENT_TYPE 0x101
+
+# define SSL3_AL_WARNING 1
+# define SSL3_AL_FATAL 2
+
+# define SSL3_AD_CLOSE_NOTIFY 0
+# define SSL3_AD_UNEXPECTED_MESSAGE 10/* fatal */
+# define SSL3_AD_BAD_RECORD_MAC 20/* fatal */
+# define SSL3_AD_DECOMPRESSION_FAILURE 30/* fatal */
+# define SSL3_AD_HANDSHAKE_FAILURE 40/* fatal */
+# define SSL3_AD_NO_CERTIFICATE 41
+# define SSL3_AD_BAD_CERTIFICATE 42
+# define SSL3_AD_UNSUPPORTED_CERTIFICATE 43
+# define SSL3_AD_CERTIFICATE_REVOKED 44
+# define SSL3_AD_CERTIFICATE_EXPIRED 45
+# define SSL3_AD_CERTIFICATE_UNKNOWN 46
+# define SSL3_AD_ILLEGAL_PARAMETER 47/* fatal */
+
+# define TLS1_HB_REQUEST 1
+# define TLS1_HB_RESPONSE 2
+
+
+# define SSL3_CT_RSA_SIGN 1
+# define SSL3_CT_DSS_SIGN 2
+# define SSL3_CT_RSA_FIXED_DH 3
+# define SSL3_CT_DSS_FIXED_DH 4
+# define SSL3_CT_RSA_EPHEMERAL_DH 5
+# define SSL3_CT_DSS_EPHEMERAL_DH 6
+# define SSL3_CT_FORTEZZA_DMS 20
+/*
+ * SSL3_CT_NUMBER is used to size arrays and it must be large enough to
+ * contain all of the cert types defined for *either* SSLv3 and TLSv1.
+ */
+# define SSL3_CT_NUMBER 12
+
+# if defined(TLS_CT_NUMBER)
+# if TLS_CT_NUMBER != SSL3_CT_NUMBER
+# error "SSL/TLS CT_NUMBER values do not match"
+# endif
+# endif
+
+/* No longer used as of OpenSSL 1.1.1 */
+# define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001
+
+/* Removed from OpenSSL 1.1.0 */
+# define TLS1_FLAGS_TLS_PADDING_BUG 0x0
+
+# define TLS1_FLAGS_SKIP_CERT_VERIFY 0x0010
+
+/* Set if we encrypt then mac instead of usual mac then encrypt */
+# define TLS1_FLAGS_ENCRYPT_THEN_MAC_READ 0x0100
+# define TLS1_FLAGS_ENCRYPT_THEN_MAC TLS1_FLAGS_ENCRYPT_THEN_MAC_READ
+
+/* Set if extended master secret extension received from peer */
+# define TLS1_FLAGS_RECEIVED_EXTMS 0x0200
+
+# define TLS1_FLAGS_ENCRYPT_THEN_MAC_WRITE 0x0400
+
+# define TLS1_FLAGS_STATELESS 0x0800
+
+/* Set if extended master secret extension required on renegotiation */
+# define TLS1_FLAGS_REQUIRED_EXTMS 0x1000
+
+# define SSL3_MT_HELLO_REQUEST 0
+# define SSL3_MT_CLIENT_HELLO 1
+# define SSL3_MT_SERVER_HELLO 2
+# define SSL3_MT_NEWSESSION_TICKET 4
+# define SSL3_MT_END_OF_EARLY_DATA 5
+# define SSL3_MT_ENCRYPTED_EXTENSIONS 8
+# define SSL3_MT_CERTIFICATE 11
+# define SSL3_MT_SERVER_KEY_EXCHANGE 12
+# define SSL3_MT_CERTIFICATE_REQUEST 13
+# define SSL3_MT_SERVER_DONE 14
+# define SSL3_MT_CERTIFICATE_VERIFY 15
+# define SSL3_MT_CLIENT_KEY_EXCHANGE 16
+# define SSL3_MT_FINISHED 20
+# define SSL3_MT_CERTIFICATE_URL 21
+# define SSL3_MT_CERTIFICATE_STATUS 22
+# define SSL3_MT_SUPPLEMENTAL_DATA 23
+# define SSL3_MT_KEY_UPDATE 24
+# ifndef OPENSSL_NO_NEXTPROTONEG
+# define SSL3_MT_NEXT_PROTO 67
+# endif
+# define SSL3_MT_MESSAGE_HASH 254
+# define DTLS1_MT_HELLO_VERIFY_REQUEST 3
+
+/* Dummy message type for handling CCS like a normal handshake message */
+# define SSL3_MT_CHANGE_CIPHER_SPEC 0x0101
+
+# define SSL3_MT_CCS 1
+
+/* These are used when changing over to a new cipher */
+# define SSL3_CC_READ 0x001
+# define SSL3_CC_WRITE 0x002
+# define SSL3_CC_CLIENT 0x010
+# define SSL3_CC_SERVER 0x020
+# define SSL3_CC_EARLY 0x040
+# define SSL3_CC_HANDSHAKE 0x080
+# define SSL3_CC_APPLICATION 0x100
+# define SSL3_CHANGE_CIPHER_CLIENT_WRITE (SSL3_CC_CLIENT|SSL3_CC_WRITE)
+# define SSL3_CHANGE_CIPHER_SERVER_READ (SSL3_CC_SERVER|SSL3_CC_READ)
+# define SSL3_CHANGE_CIPHER_CLIENT_READ (SSL3_CC_CLIENT|SSL3_CC_READ)
+# define SSL3_CHANGE_CIPHER_SERVER_WRITE (SSL3_CC_SERVER|SSL3_CC_WRITE)
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/sslerr.h b/include/openssl/sslerr.h
new file mode 100644
index 00000000..a4746d70
--- /dev/null
+++ b/include/openssl/sslerr.h
@@ -0,0 +1,343 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_SSLERR_H
+# define OPENSSL_SSLERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/sslerr_legacy.h>
+
+
+
+/*
+ * SSL reason codes.
+ */
+# define SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY 291
+# define SSL_R_APP_DATA_IN_HANDSHAKE 100
+# define SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT 272
+# define SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE 158
+# define SSL_R_BAD_CHANGE_CIPHER_SPEC 103
+# define SSL_R_BAD_CIPHER 186
+# define SSL_R_BAD_DATA 390
+# define SSL_R_BAD_DATA_RETURNED_BY_CALLBACK 106
+# define SSL_R_BAD_DECOMPRESSION 107
+# define SSL_R_BAD_DH_VALUE 102
+# define SSL_R_BAD_DIGEST_LENGTH 111
+# define SSL_R_BAD_EARLY_DATA 233
+# define SSL_R_BAD_ECC_CERT 304
+# define SSL_R_BAD_ECPOINT 306
+# define SSL_R_BAD_EXTENSION 110
+# define SSL_R_BAD_HANDSHAKE_LENGTH 332
+# define SSL_R_BAD_HANDSHAKE_STATE 236
+# define SSL_R_BAD_HELLO_REQUEST 105
+# define SSL_R_BAD_HRR_VERSION 263
+# define SSL_R_BAD_KEY_SHARE 108
+# define SSL_R_BAD_KEY_UPDATE 122
+# define SSL_R_BAD_LEGACY_VERSION 292
+# define SSL_R_BAD_LENGTH 271
+# define SSL_R_BAD_PACKET 240
+# define SSL_R_BAD_PACKET_LENGTH 115
+# define SSL_R_BAD_PROTOCOL_VERSION_NUMBER 116
+# define SSL_R_BAD_PSK 219
+# define SSL_R_BAD_PSK_IDENTITY 114
+# define SSL_R_BAD_RECORD_TYPE 443
+# define SSL_R_BAD_RSA_ENCRYPT 119
+# define SSL_R_BAD_SIGNATURE 123
+# define SSL_R_BAD_SRP_A_LENGTH 347
+# define SSL_R_BAD_SRP_PARAMETERS 371
+# define SSL_R_BAD_SRTP_MKI_VALUE 352
+# define SSL_R_BAD_SRTP_PROTECTION_PROFILE_LIST 353
+# define SSL_R_BAD_SSL_FILETYPE 124
+# define SSL_R_BAD_VALUE 384
+# define SSL_R_BAD_WRITE_RETRY 127
+# define SSL_R_BINDER_DOES_NOT_VERIFY 253
+# define SSL_R_BIO_NOT_SET 128
+# define SSL_R_BLOCK_CIPHER_PAD_IS_WRONG 129
+# define SSL_R_BN_LIB 130
+# define SSL_R_CALLBACK_FAILED 234
+# define SSL_R_CANNOT_CHANGE_CIPHER 109
+# define SSL_R_CANNOT_GET_GROUP_NAME 299
+# define SSL_R_CA_DN_LENGTH_MISMATCH 131
+# define SSL_R_CA_KEY_TOO_SMALL 397
+# define SSL_R_CA_MD_TOO_WEAK 398
+# define SSL_R_CCS_RECEIVED_EARLY 133
+# define SSL_R_CERTIFICATE_VERIFY_FAILED 134
+# define SSL_R_CERT_CB_ERROR 377
+# define SSL_R_CERT_LENGTH_MISMATCH 135
+# define SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED 218
+# define SSL_R_CIPHER_CODE_WRONG_LENGTH 137
+# define SSL_R_CLIENTHELLO_TLSEXT 226
+# define SSL_R_COMPRESSED_LENGTH_TOO_LONG 140
+# define SSL_R_COMPRESSION_DISABLED 343
+# define SSL_R_COMPRESSION_FAILURE 141
+# define SSL_R_COMPRESSION_ID_NOT_WITHIN_PRIVATE_RANGE 307
+# define SSL_R_COMPRESSION_LIBRARY_ERROR 142
+# define SSL_R_CONNECTION_TYPE_NOT_SET 144
+# define SSL_R_CONTEXT_NOT_DANE_ENABLED 167
+# define SSL_R_COOKIE_GEN_CALLBACK_FAILURE 400
+# define SSL_R_COOKIE_MISMATCH 308
+# define SSL_R_COPY_PARAMETERS_FAILED 296
+# define SSL_R_CUSTOM_EXT_HANDLER_ALREADY_INSTALLED 206
+# define SSL_R_DANE_ALREADY_ENABLED 172
+# define SSL_R_DANE_CANNOT_OVERRIDE_MTYPE_FULL 173
+# define SSL_R_DANE_NOT_ENABLED 175
+# define SSL_R_DANE_TLSA_BAD_CERTIFICATE 180
+# define SSL_R_DANE_TLSA_BAD_CERTIFICATE_USAGE 184
+# define SSL_R_DANE_TLSA_BAD_DATA_LENGTH 189
+# define SSL_R_DANE_TLSA_BAD_DIGEST_LENGTH 192
+# define SSL_R_DANE_TLSA_BAD_MATCHING_TYPE 200
+# define SSL_R_DANE_TLSA_BAD_PUBLIC_KEY 201
+# define SSL_R_DANE_TLSA_BAD_SELECTOR 202
+# define SSL_R_DANE_TLSA_NULL_DATA 203
+# define SSL_R_DATA_BETWEEN_CCS_AND_FINISHED 145
+# define SSL_R_DATA_LENGTH_TOO_LONG 146
+# define SSL_R_DECRYPTION_FAILED 147
+# define SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC 281
+# define SSL_R_DH_KEY_TOO_SMALL 394
+# define SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG 148
+# define SSL_R_DIGEST_CHECK_FAILED 149
+# define SSL_R_DTLS_MESSAGE_TOO_BIG 334
+# define SSL_R_DUPLICATE_COMPRESSION_ID 309
+# define SSL_R_ECC_CERT_NOT_FOR_SIGNING 318
+# define SSL_R_ECDH_REQUIRED_FOR_SUITEB_MODE 374
+# define SSL_R_EE_KEY_TOO_SMALL 399
+# define SSL_R_EMPTY_SRTP_PROTECTION_PROFILE_LIST 354
+# define SSL_R_ENCRYPTED_LENGTH_TOO_LONG 150
+# define SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST 151
+# define SSL_R_ERROR_SETTING_TLSA_BASE_DOMAIN 204
+# define SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE 194
+# define SSL_R_EXCESSIVE_MESSAGE_SIZE 152
+# define SSL_R_EXTENSION_NOT_RECEIVED 279
+# define SSL_R_EXTRA_DATA_IN_MESSAGE 153
+# define SSL_R_EXT_LENGTH_MISMATCH 163
+# define SSL_R_FAILED_TO_INIT_ASYNC 405
+# define SSL_R_FRAGMENTED_CLIENT_HELLO 401
+# define SSL_R_GOT_A_FIN_BEFORE_A_CCS 154
+# define SSL_R_HTTPS_PROXY_REQUEST 155
+# define SSL_R_HTTP_REQUEST 156
+# define SSL_R_ILLEGAL_POINT_COMPRESSION 162
+# define SSL_R_ILLEGAL_SUITEB_DIGEST 380
+# define SSL_R_INAPPROPRIATE_FALLBACK 373
+# define SSL_R_INCONSISTENT_COMPRESSION 340
+# define SSL_R_INCONSISTENT_EARLY_DATA_ALPN 222
+# define SSL_R_INCONSISTENT_EARLY_DATA_SNI 231
+# define SSL_R_INCONSISTENT_EXTMS 104
+# define SSL_R_INSUFFICIENT_SECURITY 241
+# define SSL_R_INVALID_ALERT 205
+# define SSL_R_INVALID_CCS_MESSAGE 260
+# define SSL_R_INVALID_CERTIFICATE_OR_ALG 238
+# define SSL_R_INVALID_COMMAND 280
+# define SSL_R_INVALID_COMPRESSION_ALGORITHM 341
+# define SSL_R_INVALID_CONFIG 283
+# define SSL_R_INVALID_CONFIGURATION_NAME 113
+# define SSL_R_INVALID_CONTEXT 282
+# define SSL_R_INVALID_CT_VALIDATION_TYPE 212
+# define SSL_R_INVALID_KEY_UPDATE_TYPE 120
+# define SSL_R_INVALID_MAX_EARLY_DATA 174
+# define SSL_R_INVALID_NULL_CMD_NAME 385
+# define SSL_R_INVALID_SEQUENCE_NUMBER 402
+# define SSL_R_INVALID_SERVERINFO_DATA 388
+# define SSL_R_INVALID_SESSION_ID 999
+# define SSL_R_INVALID_SRP_USERNAME 357
+# define SSL_R_INVALID_STATUS_RESPONSE 328
+# define SSL_R_INVALID_TICKET_KEYS_LENGTH 325
+# define SSL_R_LENGTH_MISMATCH 159
+# define SSL_R_LENGTH_TOO_LONG 404
+# define SSL_R_LENGTH_TOO_SHORT 160
+# define SSL_R_LIBRARY_BUG 274
+# define SSL_R_LIBRARY_HAS_NO_CIPHERS 161
+# define SSL_R_MISSING_DSA_SIGNING_CERT 165
+# define SSL_R_MISSING_ECDSA_SIGNING_CERT 381
+# define SSL_R_MISSING_FATAL 256
+# define SSL_R_MISSING_PARAMETERS 290
+# define SSL_R_MISSING_PSK_KEX_MODES_EXTENSION 310
+# define SSL_R_MISSING_RSA_CERTIFICATE 168
+# define SSL_R_MISSING_RSA_ENCRYPTING_CERT 169
+# define SSL_R_MISSING_RSA_SIGNING_CERT 170
+# define SSL_R_MISSING_SIGALGS_EXTENSION 112
+# define SSL_R_MISSING_SIGNING_CERT 221
+# define SSL_R_MISSING_SRP_PARAM 358
+# define SSL_R_MISSING_SUPPORTED_GROUPS_EXTENSION 209
+# define SSL_R_MISSING_TMP_DH_KEY 171
+# define SSL_R_MISSING_TMP_ECDH_KEY 311
+# define SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA 293
+# define SSL_R_NOT_ON_RECORD_BOUNDARY 182
+# define SSL_R_NOT_REPLACING_CERTIFICATE 289
+# define SSL_R_NOT_SERVER 284
+# define SSL_R_NO_APPLICATION_PROTOCOL 235
+# define SSL_R_NO_CERTIFICATES_RETURNED 176
+# define SSL_R_NO_CERTIFICATE_ASSIGNED 177
+# define SSL_R_NO_CERTIFICATE_SET 179
+# define SSL_R_NO_CHANGE_FOLLOWING_HRR 214
+# define SSL_R_NO_CIPHERS_AVAILABLE 181
+# define SSL_R_NO_CIPHERS_SPECIFIED 183
+# define SSL_R_NO_CIPHER_MATCH 185
+# define SSL_R_NO_CLIENT_CERT_METHOD 331
+# define SSL_R_NO_COMPRESSION_SPECIFIED 187
+# define SSL_R_NO_COOKIE_CALLBACK_SET 287
+# define SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER 330
+# define SSL_R_NO_METHOD_SPECIFIED 188
+# define SSL_R_NO_PEM_EXTENSIONS 389
+# define SSL_R_NO_PRIVATE_KEY_ASSIGNED 190
+# define SSL_R_NO_PROTOCOLS_AVAILABLE 191
+# define SSL_R_NO_RENEGOTIATION 339
+# define SSL_R_NO_REQUIRED_DIGEST 324
+# define SSL_R_NO_SHARED_CIPHER 193
+# define SSL_R_NO_SHARED_GROUPS 410
+# define SSL_R_NO_SHARED_SIGNATURE_ALGORITHMS 376
+# define SSL_R_NO_SRTP_PROFILES 359
+# define SSL_R_NO_SUITABLE_DIGEST_ALGORITHM 297
+# define SSL_R_NO_SUITABLE_GROUPS 295
+# define SSL_R_NO_SUITABLE_KEY_SHARE 101
+# define SSL_R_NO_SUITABLE_SIGNATURE_ALGORITHM 118
+# define SSL_R_NO_VALID_SCTS 216
+# define SSL_R_NO_VERIFY_COOKIE_CALLBACK 403
+# define SSL_R_NULL_SSL_CTX 195
+# define SSL_R_NULL_SSL_METHOD_PASSED 196
+# define SSL_R_OCSP_CALLBACK_FAILURE 305
+# define SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED 197
+# define SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED 344
+# define SSL_R_OVERFLOW_ERROR 237
+# define SSL_R_PACKET_LENGTH_TOO_LONG 198
+# define SSL_R_PARSE_TLSEXT 227
+# define SSL_R_PATH_TOO_LONG 270
+# define SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE 199
+# define SSL_R_PEM_NAME_BAD_PREFIX 391
+# define SSL_R_PEM_NAME_TOO_SHORT 392
+# define SSL_R_PIPELINE_FAILURE 406
+# define SSL_R_POST_HANDSHAKE_AUTH_ENCODING_ERR 278
+# define SSL_R_PRIVATE_KEY_MISMATCH 288
+# define SSL_R_PROTOCOL_IS_SHUTDOWN 207
+# define SSL_R_PSK_IDENTITY_NOT_FOUND 223
+# define SSL_R_PSK_NO_CLIENT_CB 224
+# define SSL_R_PSK_NO_SERVER_CB 225
+# define SSL_R_READ_BIO_NOT_SET 211
+# define SSL_R_READ_TIMEOUT_EXPIRED 312
+# define SSL_R_RECORD_LENGTH_MISMATCH 213
+# define SSL_R_RECORD_TOO_SMALL 298
+# define SSL_R_RENEGOTIATE_EXT_TOO_LONG 335
+# define SSL_R_RENEGOTIATION_ENCODING_ERR 336
+# define SSL_R_RENEGOTIATION_MISMATCH 337
+# define SSL_R_REQUEST_PENDING 285
+# define SSL_R_REQUEST_SENT 286
+# define SSL_R_REQUIRED_CIPHER_MISSING 215
+# define SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING 342
+# define SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING 345
+# define SSL_R_SCT_VERIFICATION_FAILED 208
+# define SSL_R_SERVERHELLO_TLSEXT 275
+# define SSL_R_SESSION_ID_CONTEXT_UNINITIALIZED 277
+# define SSL_R_SHUTDOWN_WHILE_IN_INIT 407
+# define SSL_R_SIGNATURE_ALGORITHMS_ERROR 360
+# define SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE 220
+# define SSL_R_SRP_A_CALC 361
+# define SSL_R_SRTP_COULD_NOT_ALLOCATE_PROFILES 362
+# define SSL_R_SRTP_PROTECTION_PROFILE_LIST_TOO_LONG 363
+# define SSL_R_SRTP_UNKNOWN_PROTECTION_PROFILE 364
+# define SSL_R_SSL3_EXT_INVALID_MAX_FRAGMENT_LENGTH 232
+# define SSL_R_SSL3_EXT_INVALID_SERVERNAME 319
+# define SSL_R_SSL3_EXT_INVALID_SERVERNAME_TYPE 320
+# define SSL_R_SSL3_SESSION_ID_TOO_LONG 300
+# define SSL_R_SSLV3_ALERT_BAD_CERTIFICATE 1042
+# define SSL_R_SSLV3_ALERT_BAD_RECORD_MAC 1020
+# define SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED 1045
+# define SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED 1044
+# define SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN 1046
+# define SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE 1030
+# define SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE 1040
+# define SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER 1047
+# define SSL_R_SSLV3_ALERT_NO_CERTIFICATE 1041
+# define SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE 1010
+# define SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE 1043
+# define SSL_R_SSL_COMMAND_SECTION_EMPTY 117
+# define SSL_R_SSL_COMMAND_SECTION_NOT_FOUND 125
+# define SSL_R_SSL_CTX_HAS_NO_DEFAULT_SSL_VERSION 228
+# define SSL_R_SSL_HANDSHAKE_FAILURE 229
+# define SSL_R_SSL_LIBRARY_HAS_NO_CIPHERS 230
+# define SSL_R_SSL_NEGATIVE_LENGTH 372
+# define SSL_R_SSL_SECTION_EMPTY 126
+# define SSL_R_SSL_SECTION_NOT_FOUND 136
+# define SSL_R_SSL_SESSION_ID_CALLBACK_FAILED 301
+# define SSL_R_SSL_SESSION_ID_CONFLICT 302
+# define SSL_R_SSL_SESSION_ID_CONTEXT_TOO_LONG 273
+# define SSL_R_SSL_SESSION_ID_HAS_BAD_LENGTH 303
+# define SSL_R_SSL_SESSION_ID_TOO_LONG 408
+# define SSL_R_SSL_SESSION_VERSION_MISMATCH 210
+# define SSL_R_STILL_IN_INIT 121
+# define SSL_R_TLSV13_ALERT_CERTIFICATE_REQUIRED 1116
+# define SSL_R_TLSV13_ALERT_MISSING_EXTENSION 1109
+# define SSL_R_TLSV1_ALERT_ACCESS_DENIED 1049
+# define SSL_R_TLSV1_ALERT_DECODE_ERROR 1050
+# define SSL_R_TLSV1_ALERT_DECRYPTION_FAILED 1021
+# define SSL_R_TLSV1_ALERT_DECRYPT_ERROR 1051
+# define SSL_R_TLSV1_ALERT_EXPORT_RESTRICTION 1060
+# define SSL_R_TLSV1_ALERT_INAPPROPRIATE_FALLBACK 1086
+# define SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY 1071
+# define SSL_R_TLSV1_ALERT_INTERNAL_ERROR 1080
+# define SSL_R_TLSV1_ALERT_NO_RENEGOTIATION 1100
+# define SSL_R_TLSV1_ALERT_PROTOCOL_VERSION 1070
+# define SSL_R_TLSV1_ALERT_RECORD_OVERFLOW 1022
+# define SSL_R_TLSV1_ALERT_UNKNOWN_CA 1048
+# define SSL_R_TLSV1_ALERT_USER_CANCELLED 1090
+# define SSL_R_TLSV1_BAD_CERTIFICATE_HASH_VALUE 1114
+# define SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE 1113
+# define SSL_R_TLSV1_CERTIFICATE_UNOBTAINABLE 1111
+# define SSL_R_TLSV1_UNRECOGNIZED_NAME 1112
+# define SSL_R_TLSV1_UNSUPPORTED_EXTENSION 1110
+# define SSL_R_TLS_ILLEGAL_EXPORTER_LABEL 367
+# define SSL_R_TLS_INVALID_ECPOINTFORMAT_LIST 157
+# define SSL_R_TOO_MANY_KEY_UPDATES 132
+# define SSL_R_TOO_MANY_WARN_ALERTS 409
+# define SSL_R_TOO_MUCH_EARLY_DATA 164
+# define SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS 314
+# define SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS 239
+# define SSL_R_UNABLE_TO_LOAD_SSL3_MD5_ROUTINES 242
+# define SSL_R_UNABLE_TO_LOAD_SSL3_SHA1_ROUTINES 243
+# define SSL_R_UNEXPECTED_CCS_MESSAGE 262
+# define SSL_R_UNEXPECTED_END_OF_EARLY_DATA 178
+# define SSL_R_UNEXPECTED_EOF_WHILE_READING 294
+# define SSL_R_UNEXPECTED_MESSAGE 244
+# define SSL_R_UNEXPECTED_RECORD 245
+# define SSL_R_UNINITIALIZED 276
+# define SSL_R_UNKNOWN_ALERT_TYPE 246
+# define SSL_R_UNKNOWN_CERTIFICATE_TYPE 247
+# define SSL_R_UNKNOWN_CIPHER_RETURNED 248
+# define SSL_R_UNKNOWN_CIPHER_TYPE 249
+# define SSL_R_UNKNOWN_CMD_NAME 386
+# define SSL_R_UNKNOWN_COMMAND 139
+# define SSL_R_UNKNOWN_DIGEST 368
+# define SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE 250
+# define SSL_R_UNKNOWN_PKEY_TYPE 251
+# define SSL_R_UNKNOWN_PROTOCOL 252
+# define SSL_R_UNKNOWN_SSL_VERSION 254
+# define SSL_R_UNKNOWN_STATE 255
+# define SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED 338
+# define SSL_R_UNSOLICITED_EXTENSION 217
+# define SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM 257
+# define SSL_R_UNSUPPORTED_ELLIPTIC_CURVE 315
+# define SSL_R_UNSUPPORTED_PROTOCOL 258
+# define SSL_R_UNSUPPORTED_SSL_VERSION 259
+# define SSL_R_UNSUPPORTED_STATUS_TYPE 329
+# define SSL_R_USE_SRTP_NOT_NEGOTIATED 369
+# define SSL_R_VERSION_TOO_HIGH 166
+# define SSL_R_VERSION_TOO_LOW 396
+# define SSL_R_WRONG_CERTIFICATE_TYPE 383
+# define SSL_R_WRONG_CIPHER_RETURNED 261
+# define SSL_R_WRONG_CURVE 378
+# define SSL_R_WRONG_SIGNATURE_LENGTH 264
+# define SSL_R_WRONG_SIGNATURE_SIZE 265
+# define SSL_R_WRONG_SIGNATURE_TYPE 370
+# define SSL_R_WRONG_SSL_VERSION 266
+# define SSL_R_WRONG_VERSION_NUMBER 267
+# define SSL_R_X509_LIB 268
+# define SSL_R_X509_VERIFICATION_SETUP_PROBLEMS 269
+
+#endif
diff --git a/include/openssl/sslerr_legacy.h b/include/openssl/sslerr_legacy.h
new file mode 100644
index 00000000..ccf6d3b3
--- /dev/null
+++ b/include/openssl/sslerr_legacy.h
@@ -0,0 +1,468 @@
+/*
+ * Copyright 2020-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+/*
+ * This header file preserves symbols from pre-3.0 OpenSSL.
+ * It should never be included directly, as it's already included
+ * by the public sslerr.h headers, and since it will go away some
+ * time in the future.
+ */
+
+#ifndef OPENSSL_SSLERR_LEGACY_H
+# define OPENSSL_SSLERR_LEGACY_H
+# pragma once
+
+# include <openssl/macros.h>
+# include <openssl/symhacks.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int ERR_load_SSL_strings(void);
+
+/* Collected _F_ macros from OpenSSL 1.1.1 */
+
+/*
+ * SSL function codes.
+ */
+# define SSL_F_ADD_CLIENT_KEY_SHARE_EXT 0
+# define SSL_F_ADD_KEY_SHARE 0
+# define SSL_F_BYTES_TO_CIPHER_LIST 0
+# define SSL_F_CHECK_SUITEB_CIPHER_LIST 0
+# define SSL_F_CIPHERSUITE_CB 0
+# define SSL_F_CONSTRUCT_CA_NAMES 0
+# define SSL_F_CONSTRUCT_KEY_EXCHANGE_TBS 0
+# define SSL_F_CONSTRUCT_STATEFUL_TICKET 0
+# define SSL_F_CONSTRUCT_STATELESS_TICKET 0
+# define SSL_F_CREATE_SYNTHETIC_MESSAGE_HASH 0
+# define SSL_F_CREATE_TICKET_PREQUEL 0
+# define SSL_F_CT_MOVE_SCTS 0
+# define SSL_F_CT_STRICT 0
+# define SSL_F_CUSTOM_EXT_ADD 0
+# define SSL_F_CUSTOM_EXT_PARSE 0
+# define SSL_F_D2I_SSL_SESSION 0
+# define SSL_F_DANE_CTX_ENABLE 0
+# define SSL_F_DANE_MTYPE_SET 0
+# define SSL_F_DANE_TLSA_ADD 0
+# define SSL_F_DERIVE_SECRET_KEY_AND_IV 0
+# define SSL_F_DO_DTLS1_WRITE 0
+# define SSL_F_DO_SSL3_WRITE 0
+# define SSL_F_DTLS1_BUFFER_RECORD 0
+# define SSL_F_DTLS1_CHECK_TIMEOUT_NUM 0
+# define SSL_F_DTLS1_HEARTBEAT 0
+# define SSL_F_DTLS1_HM_FRAGMENT_NEW 0
+# define SSL_F_DTLS1_PREPROCESS_FRAGMENT 0
+# define SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS 0
+# define SSL_F_DTLS1_PROCESS_RECORD 0
+# define SSL_F_DTLS1_READ_BYTES 0
+# define SSL_F_DTLS1_READ_FAILED 0
+# define SSL_F_DTLS1_RETRANSMIT_MESSAGE 0
+# define SSL_F_DTLS1_WRITE_APP_DATA_BYTES 0
+# define SSL_F_DTLS1_WRITE_BYTES 0
+# define SSL_F_DTLSV1_LISTEN 0
+# define SSL_F_DTLS_CONSTRUCT_CHANGE_CIPHER_SPEC 0
+# define SSL_F_DTLS_CONSTRUCT_HELLO_VERIFY_REQUEST 0
+# define SSL_F_DTLS_GET_REASSEMBLED_MESSAGE 0
+# define SSL_F_DTLS_PROCESS_HELLO_VERIFY 0
+# define SSL_F_DTLS_RECORD_LAYER_NEW 0
+# define SSL_F_DTLS_WAIT_FOR_DRY 0
+# define SSL_F_EARLY_DATA_COUNT_OK 0
+# define SSL_F_FINAL_EARLY_DATA 0
+# define SSL_F_FINAL_EC_PT_FORMATS 0
+# define SSL_F_FINAL_EMS 0
+# define SSL_F_FINAL_KEY_SHARE 0
+# define SSL_F_FINAL_MAXFRAGMENTLEN 0
+# define SSL_F_FINAL_RENEGOTIATE 0
+# define SSL_F_FINAL_SERVER_NAME 0
+# define SSL_F_FINAL_SIG_ALGS 0
+# define SSL_F_GET_CERT_VERIFY_TBS_DATA 0
+# define SSL_F_NSS_KEYLOG_INT 0
+# define SSL_F_OPENSSL_INIT_SSL 0
+# define SSL_F_OSSL_STATEM_CLIENT13_READ_TRANSITION 0
+# define SSL_F_OSSL_STATEM_CLIENT13_WRITE_TRANSITION 0
+# define SSL_F_OSSL_STATEM_CLIENT_CONSTRUCT_MESSAGE 0
+# define SSL_F_OSSL_STATEM_CLIENT_POST_PROCESS_MESSAGE 0
+# define SSL_F_OSSL_STATEM_CLIENT_PROCESS_MESSAGE 0
+# define SSL_F_OSSL_STATEM_CLIENT_READ_TRANSITION 0
+# define SSL_F_OSSL_STATEM_CLIENT_WRITE_TRANSITION 0
+# define SSL_F_OSSL_STATEM_SERVER13_READ_TRANSITION 0
+# define SSL_F_OSSL_STATEM_SERVER13_WRITE_TRANSITION 0
+# define SSL_F_OSSL_STATEM_SERVER_CONSTRUCT_MESSAGE 0
+# define SSL_F_OSSL_STATEM_SERVER_POST_PROCESS_MESSAGE 0
+# define SSL_F_OSSL_STATEM_SERVER_POST_WORK 0
+# define SSL_F_OSSL_STATEM_SERVER_PRE_WORK 0
+# define SSL_F_OSSL_STATEM_SERVER_PROCESS_MESSAGE 0
+# define SSL_F_OSSL_STATEM_SERVER_READ_TRANSITION 0
+# define SSL_F_OSSL_STATEM_SERVER_WRITE_TRANSITION 0
+# define SSL_F_PARSE_CA_NAMES 0
+# define SSL_F_PITEM_NEW 0
+# define SSL_F_PQUEUE_NEW 0
+# define SSL_F_PROCESS_KEY_SHARE_EXT 0
+# define SSL_F_READ_STATE_MACHINE 0
+# define SSL_F_SET_CLIENT_CIPHERSUITE 0
+# define SSL_F_SRP_GENERATE_CLIENT_MASTER_SECRET 0
+# define SSL_F_SRP_GENERATE_SERVER_MASTER_SECRET 0
+# define SSL_F_SRP_VERIFY_SERVER_PARAM 0
+# define SSL_F_SSL3_CHANGE_CIPHER_STATE 0
+# define SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM 0
+# define SSL_F_SSL3_CTRL 0
+# define SSL_F_SSL3_CTX_CTRL 0
+# define SSL_F_SSL3_DIGEST_CACHED_RECORDS 0
+# define SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC 0
+# define SSL_F_SSL3_ENC 0
+# define SSL_F_SSL3_FINAL_FINISH_MAC 0
+# define SSL_F_SSL3_FINISH_MAC 0
+# define SSL_F_SSL3_GENERATE_KEY_BLOCK 0
+# define SSL_F_SSL3_GENERATE_MASTER_SECRET 0
+# define SSL_F_SSL3_GET_RECORD 0
+# define SSL_F_SSL3_INIT_FINISHED_MAC 0
+# define SSL_F_SSL3_OUTPUT_CERT_CHAIN 0
+# define SSL_F_SSL3_READ_BYTES 0
+# define SSL_F_SSL3_READ_N 0
+# define SSL_F_SSL3_SETUP_KEY_BLOCK 0
+# define SSL_F_SSL3_SETUP_READ_BUFFER 0
+# define SSL_F_SSL3_SETUP_WRITE_BUFFER 0
+# define SSL_F_SSL3_WRITE_BYTES 0
+# define SSL_F_SSL3_WRITE_PENDING 0
+# define SSL_F_SSL_ADD_CERT_CHAIN 0
+# define SSL_F_SSL_ADD_CERT_TO_BUF 0
+# define SSL_F_SSL_ADD_CERT_TO_WPACKET 0
+# define SSL_F_SSL_ADD_CLIENTHELLO_RENEGOTIATE_EXT 0
+# define SSL_F_SSL_ADD_CLIENTHELLO_TLSEXT 0
+# define SSL_F_SSL_ADD_CLIENTHELLO_USE_SRTP_EXT 0
+# define SSL_F_SSL_ADD_DIR_CERT_SUBJECTS_TO_STACK 0
+# define SSL_F_SSL_ADD_FILE_CERT_SUBJECTS_TO_STACK 0
+# define SSL_F_SSL_ADD_SERVERHELLO_RENEGOTIATE_EXT 0
+# define SSL_F_SSL_ADD_SERVERHELLO_TLSEXT 0
+# define SSL_F_SSL_ADD_SERVERHELLO_USE_SRTP_EXT 0
+# define SSL_F_SSL_BAD_METHOD 0
+# define SSL_F_SSL_BUILD_CERT_CHAIN 0
+# define SSL_F_SSL_BYTES_TO_CIPHER_LIST 0
+# define SSL_F_SSL_CACHE_CIPHERLIST 0
+# define SSL_F_SSL_CERT_ADD0_CHAIN_CERT 0
+# define SSL_F_SSL_CERT_DUP 0
+# define SSL_F_SSL_CERT_NEW 0
+# define SSL_F_SSL_CERT_SET0_CHAIN 0
+# define SSL_F_SSL_CHECK_PRIVATE_KEY 0
+# define SSL_F_SSL_CHECK_SERVERHELLO_TLSEXT 0
+# define SSL_F_SSL_CHECK_SRP_EXT_CLIENTHELLO 0
+# define SSL_F_SSL_CHECK_SRVR_ECC_CERT_AND_ALG 0
+# define SSL_F_SSL_CHOOSE_CLIENT_VERSION 0
+# define SSL_F_SSL_CIPHER_DESCRIPTION 0
+# define SSL_F_SSL_CIPHER_LIST_TO_BYTES 0
+# define SSL_F_SSL_CIPHER_PROCESS_RULESTR 0
+# define SSL_F_SSL_CIPHER_STRENGTH_SORT 0
+# define SSL_F_SSL_CLEAR 0
+# define SSL_F_SSL_CLIENT_HELLO_GET1_EXTENSIONS_PRESENT 0
+# define SSL_F_SSL_COMP_ADD_COMPRESSION_METHOD 0
+# define SSL_F_SSL_CONF_CMD 0
+# define SSL_F_SSL_CREATE_CIPHER_LIST 0
+# define SSL_F_SSL_CTRL 0
+# define SSL_F_SSL_CTX_CHECK_PRIVATE_KEY 0
+# define SSL_F_SSL_CTX_ENABLE_CT 0
+# define SSL_F_SSL_CTX_MAKE_PROFILES 0
+# define SSL_F_SSL_CTX_NEW 0
+# define SSL_F_SSL_CTX_SET_ALPN_PROTOS 0
+# define SSL_F_SSL_CTX_SET_CIPHER_LIST 0
+# define SSL_F_SSL_CTX_SET_CLIENT_CERT_ENGINE 0
+# define SSL_F_SSL_CTX_SET_CT_VALIDATION_CALLBACK 0
+# define SSL_F_SSL_CTX_SET_SESSION_ID_CONTEXT 0
+# define SSL_F_SSL_CTX_SET_SSL_VERSION 0
+# define SSL_F_SSL_CTX_SET_TLSEXT_MAX_FRAGMENT_LENGTH 0
+# define SSL_F_SSL_CTX_USE_CERTIFICATE 0
+# define SSL_F_SSL_CTX_USE_CERTIFICATE_ASN1 0
+# define SSL_F_SSL_CTX_USE_CERTIFICATE_FILE 0
+# define SSL_F_SSL_CTX_USE_PRIVATEKEY 0
+# define SSL_F_SSL_CTX_USE_PRIVATEKEY_ASN1 0
+# define SSL_F_SSL_CTX_USE_PRIVATEKEY_FILE 0
+# define SSL_F_SSL_CTX_USE_PSK_IDENTITY_HINT 0
+# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY 0
+# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_ASN1 0
+# define SSL_F_SSL_CTX_USE_RSAPRIVATEKEY_FILE 0
+# define SSL_F_SSL_CTX_USE_SERVERINFO 0
+# define SSL_F_SSL_CTX_USE_SERVERINFO_EX 0
+# define SSL_F_SSL_CTX_USE_SERVERINFO_FILE 0
+# define SSL_F_SSL_DANE_DUP 0
+# define SSL_F_SSL_DANE_ENABLE 0
+# define SSL_F_SSL_DERIVE 0
+# define SSL_F_SSL_DO_CONFIG 0
+# define SSL_F_SSL_DO_HANDSHAKE 0
+# define SSL_F_SSL_DUP_CA_LIST 0
+# define SSL_F_SSL_ENABLE_CT 0
+# define SSL_F_SSL_GENERATE_PKEY_GROUP 0
+# define SSL_F_SSL_GENERATE_SESSION_ID 0
+# define SSL_F_SSL_GET_NEW_SESSION 0
+# define SSL_F_SSL_GET_PREV_SESSION 0
+# define SSL_F_SSL_GET_SERVER_CERT_INDEX 0
+# define SSL_F_SSL_GET_SIGN_PKEY 0
+# define SSL_F_SSL_HANDSHAKE_HASH 0
+# define SSL_F_SSL_INIT_WBIO_BUFFER 0
+# define SSL_F_SSL_KEY_UPDATE 0
+# define SSL_F_SSL_LOAD_CLIENT_CA_FILE 0
+# define SSL_F_SSL_LOG_MASTER_SECRET 0
+# define SSL_F_SSL_LOG_RSA_CLIENT_KEY_EXCHANGE 0
+# define SSL_F_SSL_MODULE_INIT 0
+# define SSL_F_SSL_NEW 0
+# define SSL_F_SSL_NEXT_PROTO_VALIDATE 0
+# define SSL_F_SSL_PARSE_CLIENTHELLO_RENEGOTIATE_EXT 0
+# define SSL_F_SSL_PARSE_CLIENTHELLO_TLSEXT 0
+# define SSL_F_SSL_PARSE_CLIENTHELLO_USE_SRTP_EXT 0
+# define SSL_F_SSL_PARSE_SERVERHELLO_RENEGOTIATE_EXT 0
+# define SSL_F_SSL_PARSE_SERVERHELLO_TLSEXT 0
+# define SSL_F_SSL_PARSE_SERVERHELLO_USE_SRTP_EXT 0
+# define SSL_F_SSL_PEEK 0
+# define SSL_F_SSL_PEEK_EX 0
+# define SSL_F_SSL_PEEK_INTERNAL 0
+# define SSL_F_SSL_READ 0
+# define SSL_F_SSL_READ_EARLY_DATA 0
+# define SSL_F_SSL_READ_EX 0
+# define SSL_F_SSL_READ_INTERNAL 0
+# define SSL_F_SSL_RENEGOTIATE 0
+# define SSL_F_SSL_RENEGOTIATE_ABBREVIATED 0
+# define SSL_F_SSL_SCAN_CLIENTHELLO_TLSEXT 0
+# define SSL_F_SSL_SCAN_SERVERHELLO_TLSEXT 0
+# define SSL_F_SSL_SESSION_DUP 0
+# define SSL_F_SSL_SESSION_NEW 0
+# define SSL_F_SSL_SESSION_PRINT_FP 0
+# define SSL_F_SSL_SESSION_SET1_ID 0
+# define SSL_F_SSL_SESSION_SET1_ID_CONTEXT 0
+# define SSL_F_SSL_SET_ALPN_PROTOS 0
+# define SSL_F_SSL_SET_CERT 0
+# define SSL_F_SSL_SET_CERT_AND_KEY 0
+# define SSL_F_SSL_SET_CIPHER_LIST 0
+# define SSL_F_SSL_SET_CT_VALIDATION_CALLBACK 0
+# define SSL_F_SSL_SET_FD 0
+# define SSL_F_SSL_SET_PKEY 0
+# define SSL_F_SSL_SET_RFD 0
+# define SSL_F_SSL_SET_SESSION 0
+# define SSL_F_SSL_SET_SESSION_ID_CONTEXT 0
+# define SSL_F_SSL_SET_SESSION_TICKET_EXT 0
+# define SSL_F_SSL_SET_TLSEXT_MAX_FRAGMENT_LENGTH 0
+# define SSL_F_SSL_SET_WFD 0
+# define SSL_F_SSL_SHUTDOWN 0
+# define SSL_F_SSL_SRP_CTX_INIT 0
+# define SSL_F_SSL_START_ASYNC_JOB 0
+# define SSL_F_SSL_UNDEFINED_FUNCTION 0
+# define SSL_F_SSL_UNDEFINED_VOID_FUNCTION 0
+# define SSL_F_SSL_USE_CERTIFICATE 0
+# define SSL_F_SSL_USE_CERTIFICATE_ASN1 0
+# define SSL_F_SSL_USE_CERTIFICATE_FILE 0
+# define SSL_F_SSL_USE_PRIVATEKEY 0
+# define SSL_F_SSL_USE_PRIVATEKEY_ASN1 0
+# define SSL_F_SSL_USE_PRIVATEKEY_FILE 0
+# define SSL_F_SSL_USE_PSK_IDENTITY_HINT 0
+# define SSL_F_SSL_USE_RSAPRIVATEKEY 0
+# define SSL_F_SSL_USE_RSAPRIVATEKEY_ASN1 0
+# define SSL_F_SSL_USE_RSAPRIVATEKEY_FILE 0
+# define SSL_F_SSL_VALIDATE_CT 0
+# define SSL_F_SSL_VERIFY_CERT_CHAIN 0
+# define SSL_F_SSL_VERIFY_CLIENT_POST_HANDSHAKE 0
+# define SSL_F_SSL_WRITE 0
+# define SSL_F_SSL_WRITE_EARLY_DATA 0
+# define SSL_F_SSL_WRITE_EARLY_FINISH 0
+# define SSL_F_SSL_WRITE_EX 0
+# define SSL_F_SSL_WRITE_INTERNAL 0
+# define SSL_F_STATE_MACHINE 0
+# define SSL_F_TLS12_CHECK_PEER_SIGALG 0
+# define SSL_F_TLS12_COPY_SIGALGS 0
+# define SSL_F_TLS13_CHANGE_CIPHER_STATE 0
+# define SSL_F_TLS13_ENC 0
+# define SSL_F_TLS13_FINAL_FINISH_MAC 0
+# define SSL_F_TLS13_GENERATE_SECRET 0
+# define SSL_F_TLS13_HKDF_EXPAND 0
+# define SSL_F_TLS13_RESTORE_HANDSHAKE_DIGEST_FOR_PHA 0
+# define SSL_F_TLS13_SAVE_HANDSHAKE_DIGEST_FOR_PHA 0
+# define SSL_F_TLS13_SETUP_KEY_BLOCK 0
+# define SSL_F_TLS1_CHANGE_CIPHER_STATE 0
+# define SSL_F_TLS1_CHECK_DUPLICATE_EXTENSIONS 0
+# define SSL_F_TLS1_ENC 0
+# define SSL_F_TLS1_EXPORT_KEYING_MATERIAL 0
+# define SSL_F_TLS1_GET_CURVELIST 0
+# define SSL_F_TLS1_PRF 0
+# define SSL_F_TLS1_SAVE_U16 0
+# define SSL_F_TLS1_SETUP_KEY_BLOCK 0
+# define SSL_F_TLS1_SET_GROUPS 0
+# define SSL_F_TLS1_SET_RAW_SIGALGS 0
+# define SSL_F_TLS1_SET_SERVER_SIGALGS 0
+# define SSL_F_TLS1_SET_SHARED_SIGALGS 0
+# define SSL_F_TLS1_SET_SIGALGS 0
+# define SSL_F_TLS_CHOOSE_SIGALG 0
+# define SSL_F_TLS_CLIENT_KEY_EXCHANGE_POST_WORK 0
+# define SSL_F_TLS_COLLECT_EXTENSIONS 0
+# define SSL_F_TLS_CONSTRUCT_CERTIFICATE_AUTHORITIES 0
+# define SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST 0
+# define SSL_F_TLS_CONSTRUCT_CERT_STATUS 0
+# define SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY 0
+# define SSL_F_TLS_CONSTRUCT_CERT_VERIFY 0
+# define SSL_F_TLS_CONSTRUCT_CHANGE_CIPHER_SPEC 0
+# define SSL_F_TLS_CONSTRUCT_CKE_DHE 0
+# define SSL_F_TLS_CONSTRUCT_CKE_ECDHE 0
+# define SSL_F_TLS_CONSTRUCT_CKE_GOST 0
+# define SSL_F_TLS_CONSTRUCT_CKE_PSK_PREAMBLE 0
+# define SSL_F_TLS_CONSTRUCT_CKE_RSA 0
+# define SSL_F_TLS_CONSTRUCT_CKE_SRP 0
+# define SSL_F_TLS_CONSTRUCT_CLIENT_CERTIFICATE 0
+# define SSL_F_TLS_CONSTRUCT_CLIENT_HELLO 0
+# define SSL_F_TLS_CONSTRUCT_CLIENT_KEY_EXCHANGE 0
+# define SSL_F_TLS_CONSTRUCT_CLIENT_VERIFY 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_ALPN 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_CERTIFICATE 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_COOKIE 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_EARLY_DATA 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_EC_PT_FORMATS 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_EMS 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_ETM 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_HELLO 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_KEY_EXCHANGE 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_KEY_SHARE 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_MAXFRAGMENTLEN 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_NPN 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_PADDING 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_POST_HANDSHAKE_AUTH 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_PSK 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_PSK_KEX_MODES 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_RENEGOTIATE 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_SCT 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_SERVER_NAME 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_SESSION_TICKET 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_SIG_ALGS 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_SRP 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_STATUS_REQUEST 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_SUPPORTED_GROUPS 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_SUPPORTED_VERSIONS 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_USE_SRTP 0
+# define SSL_F_TLS_CONSTRUCT_CTOS_VERIFY 0
+# define SSL_F_TLS_CONSTRUCT_ENCRYPTED_EXTENSIONS 0
+# define SSL_F_TLS_CONSTRUCT_END_OF_EARLY_DATA 0
+# define SSL_F_TLS_CONSTRUCT_EXTENSIONS 0
+# define SSL_F_TLS_CONSTRUCT_FINISHED 0
+# define SSL_F_TLS_CONSTRUCT_HELLO_REQUEST 0
+# define SSL_F_TLS_CONSTRUCT_HELLO_RETRY_REQUEST 0
+# define SSL_F_TLS_CONSTRUCT_KEY_UPDATE 0
+# define SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET 0
+# define SSL_F_TLS_CONSTRUCT_NEXT_PROTO 0
+# define SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE 0
+# define SSL_F_TLS_CONSTRUCT_SERVER_HELLO 0
+# define SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE 0
+# define SSL_F_TLS_CONSTRUCT_STOC_ALPN 0
+# define SSL_F_TLS_CONSTRUCT_STOC_CERTIFICATE 0
+# define SSL_F_TLS_CONSTRUCT_STOC_COOKIE 0
+# define SSL_F_TLS_CONSTRUCT_STOC_CRYPTOPRO_BUG 0
+# define SSL_F_TLS_CONSTRUCT_STOC_DONE 0
+# define SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA 0
+# define SSL_F_TLS_CONSTRUCT_STOC_EARLY_DATA_INFO 0
+# define SSL_F_TLS_CONSTRUCT_STOC_EC_PT_FORMATS 0
+# define SSL_F_TLS_CONSTRUCT_STOC_EMS 0
+# define SSL_F_TLS_CONSTRUCT_STOC_ETM 0
+# define SSL_F_TLS_CONSTRUCT_STOC_HELLO 0
+# define SSL_F_TLS_CONSTRUCT_STOC_KEY_EXCHANGE 0
+# define SSL_F_TLS_CONSTRUCT_STOC_KEY_SHARE 0
+# define SSL_F_TLS_CONSTRUCT_STOC_MAXFRAGMENTLEN 0
+# define SSL_F_TLS_CONSTRUCT_STOC_NEXT_PROTO_NEG 0
+# define SSL_F_TLS_CONSTRUCT_STOC_PSK 0
+# define SSL_F_TLS_CONSTRUCT_STOC_RENEGOTIATE 0
+# define SSL_F_TLS_CONSTRUCT_STOC_SERVER_NAME 0
+# define SSL_F_TLS_CONSTRUCT_STOC_SESSION_TICKET 0
+# define SSL_F_TLS_CONSTRUCT_STOC_STATUS_REQUEST 0
+# define SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_GROUPS 0
+# define SSL_F_TLS_CONSTRUCT_STOC_SUPPORTED_VERSIONS 0
+# define SSL_F_TLS_CONSTRUCT_STOC_USE_SRTP 0
+# define SSL_F_TLS_EARLY_POST_PROCESS_CLIENT_HELLO 0
+# define SSL_F_TLS_FINISH_HANDSHAKE 0
+# define SSL_F_TLS_GET_MESSAGE_BODY 0
+# define SSL_F_TLS_GET_MESSAGE_HEADER 0
+# define SSL_F_TLS_HANDLE_ALPN 0
+# define SSL_F_TLS_HANDLE_STATUS_REQUEST 0
+# define SSL_F_TLS_PARSE_CERTIFICATE_AUTHORITIES 0
+# define SSL_F_TLS_PARSE_CLIENTHELLO_TLSEXT 0
+# define SSL_F_TLS_PARSE_CTOS_ALPN 0
+# define SSL_F_TLS_PARSE_CTOS_COOKIE 0
+# define SSL_F_TLS_PARSE_CTOS_EARLY_DATA 0
+# define SSL_F_TLS_PARSE_CTOS_EC_PT_FORMATS 0
+# define SSL_F_TLS_PARSE_CTOS_EMS 0
+# define SSL_F_TLS_PARSE_CTOS_KEY_SHARE 0
+# define SSL_F_TLS_PARSE_CTOS_MAXFRAGMENTLEN 0
+# define SSL_F_TLS_PARSE_CTOS_POST_HANDSHAKE_AUTH 0
+# define SSL_F_TLS_PARSE_CTOS_PSK 0
+# define SSL_F_TLS_PARSE_CTOS_PSK_KEX_MODES 0
+# define SSL_F_TLS_PARSE_CTOS_RENEGOTIATE 0
+# define SSL_F_TLS_PARSE_CTOS_SERVER_NAME 0
+# define SSL_F_TLS_PARSE_CTOS_SESSION_TICKET 0
+# define SSL_F_TLS_PARSE_CTOS_SIG_ALGS 0
+# define SSL_F_TLS_PARSE_CTOS_SIG_ALGS_CERT 0
+# define SSL_F_TLS_PARSE_CTOS_SRP 0
+# define SSL_F_TLS_PARSE_CTOS_STATUS_REQUEST 0
+# define SSL_F_TLS_PARSE_CTOS_SUPPORTED_GROUPS 0
+# define SSL_F_TLS_PARSE_CTOS_USE_SRTP 0
+# define SSL_F_TLS_PARSE_STOC_ALPN 0
+# define SSL_F_TLS_PARSE_STOC_COOKIE 0
+# define SSL_F_TLS_PARSE_STOC_EARLY_DATA 0
+# define SSL_F_TLS_PARSE_STOC_EARLY_DATA_INFO 0
+# define SSL_F_TLS_PARSE_STOC_EC_PT_FORMATS 0
+# define SSL_F_TLS_PARSE_STOC_KEY_SHARE 0
+# define SSL_F_TLS_PARSE_STOC_MAXFRAGMENTLEN 0
+# define SSL_F_TLS_PARSE_STOC_NPN 0
+# define SSL_F_TLS_PARSE_STOC_PSK 0
+# define SSL_F_TLS_PARSE_STOC_RENEGOTIATE 0
+# define SSL_F_TLS_PARSE_STOC_SCT 0
+# define SSL_F_TLS_PARSE_STOC_SERVER_NAME 0
+# define SSL_F_TLS_PARSE_STOC_SESSION_TICKET 0
+# define SSL_F_TLS_PARSE_STOC_STATUS_REQUEST 0
+# define SSL_F_TLS_PARSE_STOC_SUPPORTED_VERSIONS 0
+# define SSL_F_TLS_PARSE_STOC_USE_SRTP 0
+# define SSL_F_TLS_POST_PROCESS_CLIENT_HELLO 0
+# define SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE 0
+# define SSL_F_TLS_PREPARE_CLIENT_CERTIFICATE 0
+# define SSL_F_TLS_PROCESS_AS_HELLO_RETRY_REQUEST 0
+# define SSL_F_TLS_PROCESS_CERTIFICATE_REQUEST 0
+# define SSL_F_TLS_PROCESS_CERT_STATUS 0
+# define SSL_F_TLS_PROCESS_CERT_STATUS_BODY 0
+# define SSL_F_TLS_PROCESS_CERT_VERIFY 0
+# define SSL_F_TLS_PROCESS_CHANGE_CIPHER_SPEC 0
+# define SSL_F_TLS_PROCESS_CKE_DHE 0
+# define SSL_F_TLS_PROCESS_CKE_ECDHE 0
+# define SSL_F_TLS_PROCESS_CKE_GOST 0
+# define SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE 0
+# define SSL_F_TLS_PROCESS_CKE_RSA 0
+# define SSL_F_TLS_PROCESS_CKE_SRP 0
+# define SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE 0
+# define SSL_F_TLS_PROCESS_CLIENT_HELLO 0
+# define SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE 0
+# define SSL_F_TLS_PROCESS_ENCRYPTED_EXTENSIONS 0
+# define SSL_F_TLS_PROCESS_END_OF_EARLY_DATA 0
+# define SSL_F_TLS_PROCESS_FINISHED 0
+# define SSL_F_TLS_PROCESS_HELLO_REQ 0
+# define SSL_F_TLS_PROCESS_HELLO_RETRY_REQUEST 0
+# define SSL_F_TLS_PROCESS_INITIAL_SERVER_FLIGHT 0
+# define SSL_F_TLS_PROCESS_KEY_EXCHANGE 0
+# define SSL_F_TLS_PROCESS_KEY_UPDATE 0
+# define SSL_F_TLS_PROCESS_NEW_SESSION_TICKET 0
+# define SSL_F_TLS_PROCESS_NEXT_PROTO 0
+# define SSL_F_TLS_PROCESS_SERVER_CERTIFICATE 0
+# define SSL_F_TLS_PROCESS_SERVER_DONE 0
+# define SSL_F_TLS_PROCESS_SERVER_HELLO 0
+# define SSL_F_TLS_PROCESS_SKE_DHE 0
+# define SSL_F_TLS_PROCESS_SKE_ECDHE 0
+# define SSL_F_TLS_PROCESS_SKE_PSK_PREAMBLE 0
+# define SSL_F_TLS_PROCESS_SKE_SRP 0
+# define SSL_F_TLS_PSK_DO_BINDER 0
+# define SSL_F_TLS_SCAN_CLIENTHELLO_TLSEXT 0
+# define SSL_F_TLS_SETUP_HANDSHAKE 0
+# define SSL_F_USE_CERTIFICATE_CHAIN_FILE 0
+# define SSL_F_WPACKET_INTERN_INIT_LEN 0
+# define SSL_F_WPACKET_START_SUB_PACKET_LEN__ 0
+# define SSL_F_WRITE_STATE_MACHINE 0
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/stack.h b/include/openssl/stack.h
new file mode 100644
index 00000000..f0c5c547
--- /dev/null
+++ b/include/openssl/stack.h
@@ -0,0 +1,90 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_STACK_H
+# define OPENSSL_STACK_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_STACK_H
+# endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct stack_st OPENSSL_STACK; /* Use STACK_OF(...) instead */
+
+typedef int (*OPENSSL_sk_compfunc)(const void *, const void *);
+typedef void (*OPENSSL_sk_freefunc)(void *);
+typedef void *(*OPENSSL_sk_copyfunc)(const void *);
+
+int OPENSSL_sk_num(const OPENSSL_STACK *);
+void *OPENSSL_sk_value(const OPENSSL_STACK *, int);
+
+void *OPENSSL_sk_set(OPENSSL_STACK *st, int i, const void *data);
+
+OPENSSL_STACK *OPENSSL_sk_new(OPENSSL_sk_compfunc cmp);
+OPENSSL_STACK *OPENSSL_sk_new_null(void);
+OPENSSL_STACK *OPENSSL_sk_new_reserve(OPENSSL_sk_compfunc c, int n);
+int OPENSSL_sk_reserve(OPENSSL_STACK *st, int n);
+void OPENSSL_sk_free(OPENSSL_STACK *);
+void OPENSSL_sk_pop_free(OPENSSL_STACK *st, void (*func) (void *));
+OPENSSL_STACK *OPENSSL_sk_deep_copy(const OPENSSL_STACK *,
+ OPENSSL_sk_copyfunc c,
+ OPENSSL_sk_freefunc f);
+int OPENSSL_sk_insert(OPENSSL_STACK *sk, const void *data, int where);
+void *OPENSSL_sk_delete(OPENSSL_STACK *st, int loc);
+void *OPENSSL_sk_delete_ptr(OPENSSL_STACK *st, const void *p);
+int OPENSSL_sk_find(OPENSSL_STACK *st, const void *data);
+int OPENSSL_sk_find_ex(OPENSSL_STACK *st, const void *data);
+int OPENSSL_sk_find_all(OPENSSL_STACK *st, const void *data, int *pnum);
+int OPENSSL_sk_push(OPENSSL_STACK *st, const void *data);
+int OPENSSL_sk_unshift(OPENSSL_STACK *st, const void *data);
+void *OPENSSL_sk_shift(OPENSSL_STACK *st);
+void *OPENSSL_sk_pop(OPENSSL_STACK *st);
+void OPENSSL_sk_zero(OPENSSL_STACK *st);
+OPENSSL_sk_compfunc OPENSSL_sk_set_cmp_func(OPENSSL_STACK *sk,
+ OPENSSL_sk_compfunc cmp);
+OPENSSL_STACK *OPENSSL_sk_dup(const OPENSSL_STACK *st);
+void OPENSSL_sk_sort(OPENSSL_STACK *st);
+int OPENSSL_sk_is_sorted(const OPENSSL_STACK *st);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define _STACK OPENSSL_STACK
+# define sk_num OPENSSL_sk_num
+# define sk_value OPENSSL_sk_value
+# define sk_set OPENSSL_sk_set
+# define sk_new OPENSSL_sk_new
+# define sk_new_null OPENSSL_sk_new_null
+# define sk_free OPENSSL_sk_free
+# define sk_pop_free OPENSSL_sk_pop_free
+# define sk_deep_copy OPENSSL_sk_deep_copy
+# define sk_insert OPENSSL_sk_insert
+# define sk_delete OPENSSL_sk_delete
+# define sk_delete_ptr OPENSSL_sk_delete_ptr
+# define sk_find OPENSSL_sk_find
+# define sk_find_ex OPENSSL_sk_find_ex
+# define sk_push OPENSSL_sk_push
+# define sk_unshift OPENSSL_sk_unshift
+# define sk_shift OPENSSL_sk_shift
+# define sk_pop OPENSSL_sk_pop
+# define sk_zero OPENSSL_sk_zero
+# define sk_set_cmp_func OPENSSL_sk_set_cmp_func
+# define sk_dup OPENSSL_sk_dup
+# define sk_sort OPENSSL_sk_sort
+# define sk_is_sorted OPENSSL_sk_is_sorted
+# endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/store.h b/include/openssl/store.h
new file mode 100644
index 00000000..3c1445e0
--- /dev/null
+++ b/include/openssl/store.h
@@ -0,0 +1,369 @@
+/*
+ * Copyright 2016-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_STORE_H
+# define OPENSSL_STORE_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_OSSL_STORE_H
+# endif
+
+# include <stdarg.h>
+# include <openssl/types.h>
+# include <openssl/pem.h>
+# include <openssl/storeerr.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*-
+ * The main OSSL_STORE functions.
+ * ------------------------------
+ *
+ * These allow applications to open a channel to a resource with supported
+ * data (keys, certs, crls, ...), read the data a piece at a time and decide
+ * what to do with it, and finally close.
+ */
+
+typedef struct ossl_store_ctx_st OSSL_STORE_CTX;
+
+/*
+ * Typedef for the OSSL_STORE_INFO post processing callback. This can be used
+ * to massage the given OSSL_STORE_INFO, or to drop it entirely (by returning
+ * NULL).
+ */
+typedef OSSL_STORE_INFO *(*OSSL_STORE_post_process_info_fn)(OSSL_STORE_INFO *,
+ void *);
+
+/*
+ * Open a channel given a URI. The given UI method will be used any time the
+ * loader needs extra input, for example when a password or pin is needed, and
+ * will be passed the same user data every time it's needed in this context.
+ *
+ * Returns a context reference which represents the channel to communicate
+ * through.
+ */
+OSSL_STORE_CTX *
+OSSL_STORE_open(const char *uri, const UI_METHOD *ui_method, void *ui_data,
+ OSSL_STORE_post_process_info_fn post_process,
+ void *post_process_data);
+OSSL_STORE_CTX *
+OSSL_STORE_open_ex(const char *uri, OSSL_LIB_CTX *libctx, const char *propq,
+ const UI_METHOD *ui_method, void *ui_data,
+ const OSSL_PARAM params[],
+ OSSL_STORE_post_process_info_fn post_process,
+ void *post_process_data);
+
+/*
+ * Control / fine tune the OSSL_STORE channel. |cmd| determines what is to be
+ * done, and depends on the underlying loader (use OSSL_STORE_get0_scheme to
+ * determine which loader is used), except for common commands (see below).
+ * Each command takes different arguments.
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int OSSL_STORE_ctrl(OSSL_STORE_CTX *ctx, int cmd,
+ ... /* args */);
+OSSL_DEPRECATEDIN_3_0 int OSSL_STORE_vctrl(OSSL_STORE_CTX *ctx, int cmd,
+ va_list args);
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+/*
+ * Common ctrl commands that different loaders may choose to support.
+ */
+/* int on = 0 or 1; STORE_ctrl(ctx, STORE_C_USE_SECMEM, &on); */
+# define OSSL_STORE_C_USE_SECMEM 1
+/* Where custom commands start */
+# define OSSL_STORE_C_CUSTOM_START 100
+
+# endif
+
+/*
+ * Read one data item (a key, a cert, a CRL) that is supported by the OSSL_STORE
+ * functionality, given a context.
+ * Returns a OSSL_STORE_INFO pointer, from which OpenSSL typed data can be
+ * extracted with OSSL_STORE_INFO_get0_PKEY(), OSSL_STORE_INFO_get0_CERT(), ...
+ * NULL is returned on error, which may include that the data found at the URI
+ * can't be figured out for certain or is ambiguous.
+ */
+OSSL_STORE_INFO *OSSL_STORE_load(OSSL_STORE_CTX *ctx);
+
+/*
+ * Check if end of data (end of file) is reached
+ * Returns 1 on end, 0 otherwise.
+ */
+int OSSL_STORE_eof(OSSL_STORE_CTX *ctx);
+
+/*
+ * Check if an error occurred
+ * Returns 1 if it did, 0 otherwise.
+ */
+int OSSL_STORE_error(OSSL_STORE_CTX *ctx);
+
+/*
+ * Close the channel
+ * Returns 1 on success, 0 on error.
+ */
+int OSSL_STORE_close(OSSL_STORE_CTX *ctx);
+
+/*
+ * Attach to a BIO. This works like OSSL_STORE_open() except it takes a
+ * BIO instead of a uri, along with a scheme to use when reading.
+ * The given UI method will be used any time the loader needs extra input,
+ * for example when a password or pin is needed, and will be passed the
+ * same user data every time it's needed in this context.
+ *
+ * Returns a context reference which represents the channel to communicate
+ * through.
+ *
+ * Note that this function is considered unsafe, all depending on what the
+ * BIO actually reads.
+ */
+OSSL_STORE_CTX *OSSL_STORE_attach(BIO *bio, const char *scheme,
+ OSSL_LIB_CTX *libctx, const char *propq,
+ const UI_METHOD *ui_method, void *ui_data,
+ const OSSL_PARAM params[],
+ OSSL_STORE_post_process_info_fn post_process,
+ void *post_process_data);
+
+/*-
+ * Extracting OpenSSL types from and creating new OSSL_STORE_INFOs
+ * ---------------------------------------------------------------
+ */
+
+/*
+ * Types of data that can be ossl_stored in a OSSL_STORE_INFO.
+ * OSSL_STORE_INFO_NAME is typically found when getting a listing of
+ * available "files" / "tokens" / what have you.
+ */
+# define OSSL_STORE_INFO_NAME 1 /* char * */
+# define OSSL_STORE_INFO_PARAMS 2 /* EVP_PKEY * */
+# define OSSL_STORE_INFO_PUBKEY 3 /* EVP_PKEY * */
+# define OSSL_STORE_INFO_PKEY 4 /* EVP_PKEY * */
+# define OSSL_STORE_INFO_CERT 5 /* X509 * */
+# define OSSL_STORE_INFO_CRL 6 /* X509_CRL * */
+
+/*
+ * Functions to generate OSSL_STORE_INFOs, one function for each type we
+ * support having in them, as well as a generic constructor.
+ *
+ * In all cases, ownership of the object is transferred to the OSSL_STORE_INFO
+ * and will therefore be freed when the OSSL_STORE_INFO is freed.
+ */
+OSSL_STORE_INFO *OSSL_STORE_INFO_new(int type, void *data);
+OSSL_STORE_INFO *OSSL_STORE_INFO_new_NAME(char *name);
+int OSSL_STORE_INFO_set0_NAME_description(OSSL_STORE_INFO *info, char *desc);
+OSSL_STORE_INFO *OSSL_STORE_INFO_new_PARAMS(EVP_PKEY *params);
+OSSL_STORE_INFO *OSSL_STORE_INFO_new_PUBKEY(EVP_PKEY *pubkey);
+OSSL_STORE_INFO *OSSL_STORE_INFO_new_PKEY(EVP_PKEY *pkey);
+OSSL_STORE_INFO *OSSL_STORE_INFO_new_CERT(X509 *x509);
+OSSL_STORE_INFO *OSSL_STORE_INFO_new_CRL(X509_CRL *crl);
+
+/*
+ * Functions to try to extract data from a OSSL_STORE_INFO.
+ */
+int OSSL_STORE_INFO_get_type(const OSSL_STORE_INFO *info);
+void *OSSL_STORE_INFO_get0_data(int type, const OSSL_STORE_INFO *info);
+const char *OSSL_STORE_INFO_get0_NAME(const OSSL_STORE_INFO *info);
+char *OSSL_STORE_INFO_get1_NAME(const OSSL_STORE_INFO *info);
+const char *OSSL_STORE_INFO_get0_NAME_description(const OSSL_STORE_INFO *info);
+char *OSSL_STORE_INFO_get1_NAME_description(const OSSL_STORE_INFO *info);
+EVP_PKEY *OSSL_STORE_INFO_get0_PARAMS(const OSSL_STORE_INFO *info);
+EVP_PKEY *OSSL_STORE_INFO_get1_PARAMS(const OSSL_STORE_INFO *info);
+EVP_PKEY *OSSL_STORE_INFO_get0_PUBKEY(const OSSL_STORE_INFO *info);
+EVP_PKEY *OSSL_STORE_INFO_get1_PUBKEY(const OSSL_STORE_INFO *info);
+EVP_PKEY *OSSL_STORE_INFO_get0_PKEY(const OSSL_STORE_INFO *info);
+EVP_PKEY *OSSL_STORE_INFO_get1_PKEY(const OSSL_STORE_INFO *info);
+X509 *OSSL_STORE_INFO_get0_CERT(const OSSL_STORE_INFO *info);
+X509 *OSSL_STORE_INFO_get1_CERT(const OSSL_STORE_INFO *info);
+X509_CRL *OSSL_STORE_INFO_get0_CRL(const OSSL_STORE_INFO *info);
+X509_CRL *OSSL_STORE_INFO_get1_CRL(const OSSL_STORE_INFO *info);
+
+const char *OSSL_STORE_INFO_type_string(int type);
+
+/*
+ * Free the OSSL_STORE_INFO
+ */
+void OSSL_STORE_INFO_free(OSSL_STORE_INFO *info);
+
+
+/*-
+ * Functions to construct a search URI from a base URI and search criteria
+ * -----------------------------------------------------------------------
+ */
+
+/* OSSL_STORE search types */
+# define OSSL_STORE_SEARCH_BY_NAME 1 /* subject in certs, issuer in CRLs */
+# define OSSL_STORE_SEARCH_BY_ISSUER_SERIAL 2
+# define OSSL_STORE_SEARCH_BY_KEY_FINGERPRINT 3
+# define OSSL_STORE_SEARCH_BY_ALIAS 4
+
+/* To check what search types the scheme handler supports */
+int OSSL_STORE_supports_search(OSSL_STORE_CTX *ctx, int search_type);
+
+/* Search term constructors */
+/*
+ * The input is considered to be owned by the caller, and must therefore
+ * remain present throughout the lifetime of the returned OSSL_STORE_SEARCH
+ */
+OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_name(X509_NAME *name);
+OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_issuer_serial(X509_NAME *name,
+ const ASN1_INTEGER
+ *serial);
+OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_key_fingerprint(const EVP_MD *digest,
+ const unsigned char
+ *bytes, size_t len);
+OSSL_STORE_SEARCH *OSSL_STORE_SEARCH_by_alias(const char *alias);
+
+/* Search term destructor */
+void OSSL_STORE_SEARCH_free(OSSL_STORE_SEARCH *search);
+
+/* Search term accessors */
+int OSSL_STORE_SEARCH_get_type(const OSSL_STORE_SEARCH *criterion);
+X509_NAME *OSSL_STORE_SEARCH_get0_name(const OSSL_STORE_SEARCH *criterion);
+const ASN1_INTEGER *OSSL_STORE_SEARCH_get0_serial(const OSSL_STORE_SEARCH
+ *criterion);
+const unsigned char *OSSL_STORE_SEARCH_get0_bytes(const OSSL_STORE_SEARCH
+ *criterion, size_t *length);
+const char *OSSL_STORE_SEARCH_get0_string(const OSSL_STORE_SEARCH *criterion);
+const EVP_MD *OSSL_STORE_SEARCH_get0_digest(const OSSL_STORE_SEARCH *criterion);
+
+/*
+ * Add search criterion and expected return type (which can be unspecified)
+ * to the loading channel. This MUST happen before the first OSSL_STORE_load().
+ */
+int OSSL_STORE_expect(OSSL_STORE_CTX *ctx, int expected_type);
+int OSSL_STORE_find(OSSL_STORE_CTX *ctx, const OSSL_STORE_SEARCH *search);
+
+
+/*-
+ * Function to fetch a loader and extract data from it
+ * ---------------------------------------------------
+ */
+
+typedef struct ossl_store_loader_st OSSL_STORE_LOADER;
+
+OSSL_STORE_LOADER *OSSL_STORE_LOADER_fetch(OSSL_LIB_CTX *libctx,
+ const char *scheme,
+ const char *properties);
+int OSSL_STORE_LOADER_up_ref(OSSL_STORE_LOADER *loader);
+void OSSL_STORE_LOADER_free(OSSL_STORE_LOADER *loader);
+const OSSL_PROVIDER *OSSL_STORE_LOADER_get0_provider(const OSSL_STORE_LOADER *
+ loader);
+const char *OSSL_STORE_LOADER_get0_properties(const OSSL_STORE_LOADER *loader);
+const char *OSSL_STORE_LOADER_get0_description(const OSSL_STORE_LOADER *loader);
+int OSSL_STORE_LOADER_is_a(const OSSL_STORE_LOADER *loader,
+ const char *scheme);
+void OSSL_STORE_LOADER_do_all_provided(OSSL_LIB_CTX *libctx,
+ void (*fn)(OSSL_STORE_LOADER *loader,
+ void *arg),
+ void *arg);
+int OSSL_STORE_LOADER_names_do_all(const OSSL_STORE_LOADER *loader,
+ void (*fn)(const char *name, void *data),
+ void *data);
+
+/*-
+ * Function to register a loader for the given URI scheme.
+ * -------------------------------------------------------
+ *
+ * The loader receives all the main components of an URI except for the
+ * scheme.
+ */
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+
+/* struct ossl_store_loader_ctx_st is defined differently by each loader */
+typedef struct ossl_store_loader_ctx_st OSSL_STORE_LOADER_CTX;
+typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_fn)
+ (const OSSL_STORE_LOADER *loader, const char *uri,
+ const UI_METHOD *ui_method, void *ui_data);
+typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_open_ex_fn)
+ (const OSSL_STORE_LOADER *loader,
+ const char *uri, OSSL_LIB_CTX *libctx, const char *propq,
+ const UI_METHOD *ui_method, void *ui_data);
+
+typedef OSSL_STORE_LOADER_CTX *(*OSSL_STORE_attach_fn)
+ (const OSSL_STORE_LOADER *loader, BIO *bio,
+ OSSL_LIB_CTX *libctx, const char *propq,
+ const UI_METHOD *ui_method, void *ui_data);
+typedef int (*OSSL_STORE_ctrl_fn)
+ (OSSL_STORE_LOADER_CTX *ctx, int cmd, va_list args);
+typedef int (*OSSL_STORE_expect_fn)
+ (OSSL_STORE_LOADER_CTX *ctx, int expected);
+typedef int (*OSSL_STORE_find_fn)
+ (OSSL_STORE_LOADER_CTX *ctx, const OSSL_STORE_SEARCH *criteria);
+typedef OSSL_STORE_INFO *(*OSSL_STORE_load_fn)
+ (OSSL_STORE_LOADER_CTX *ctx, const UI_METHOD *ui_method, void *ui_data);
+typedef int (*OSSL_STORE_eof_fn)(OSSL_STORE_LOADER_CTX *ctx);
+typedef int (*OSSL_STORE_error_fn)(OSSL_STORE_LOADER_CTX *ctx);
+typedef int (*OSSL_STORE_close_fn)(OSSL_STORE_LOADER_CTX *ctx);
+
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+OSSL_STORE_LOADER *OSSL_STORE_LOADER_new(ENGINE *e, const char *scheme);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_open(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_open_fn open_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_open_ex(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_open_ex_fn open_ex_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_attach(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_attach_fn attach_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_ctrl(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_ctrl_fn ctrl_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_expect(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_expect_fn expect_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_find(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_find_fn find_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_load(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_load_fn load_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_eof(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_eof_fn eof_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_error(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_error_fn error_function);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_LOADER_set_close(OSSL_STORE_LOADER *loader,
+ OSSL_STORE_close_fn close_function);
+OSSL_DEPRECATEDIN_3_0
+const ENGINE *OSSL_STORE_LOADER_get0_engine(const OSSL_STORE_LOADER *loader);
+OSSL_DEPRECATEDIN_3_0
+const char * OSSL_STORE_LOADER_get0_scheme(const OSSL_STORE_LOADER *loader);
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_register_loader(OSSL_STORE_LOADER *loader);
+OSSL_DEPRECATEDIN_3_0
+OSSL_STORE_LOADER *OSSL_STORE_unregister_loader(const char *scheme);
+# endif
+
+/*-
+ * Functions to list STORE loaders
+ * -------------------------------
+ */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int OSSL_STORE_do_all_loaders(void (*do_function)(const OSSL_STORE_LOADER *loader,
+ void *do_arg),
+ void *do_arg);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/storeerr.h b/include/openssl/storeerr.h
new file mode 100644
index 00000000..00529c88
--- /dev/null
+++ b/include/openssl/storeerr.h
@@ -0,0 +1,49 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_STOREERR_H
+# define OPENSSL_STOREERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * OSSL_STORE reason codes.
+ */
+# define OSSL_STORE_R_AMBIGUOUS_CONTENT_TYPE 107
+# define OSSL_STORE_R_BAD_PASSWORD_READ 115
+# define OSSL_STORE_R_ERROR_VERIFYING_PKCS12_MAC 113
+# define OSSL_STORE_R_FINGERPRINT_SIZE_DOES_NOT_MATCH_DIGEST 121
+# define OSSL_STORE_R_INVALID_SCHEME 106
+# define OSSL_STORE_R_IS_NOT_A 112
+# define OSSL_STORE_R_LOADER_INCOMPLETE 116
+# define OSSL_STORE_R_LOADING_STARTED 117
+# define OSSL_STORE_R_NOT_A_CERTIFICATE 100
+# define OSSL_STORE_R_NOT_A_CRL 101
+# define OSSL_STORE_R_NOT_A_NAME 103
+# define OSSL_STORE_R_NOT_A_PRIVATE_KEY 102
+# define OSSL_STORE_R_NOT_A_PUBLIC_KEY 122
+# define OSSL_STORE_R_NOT_PARAMETERS 104
+# define OSSL_STORE_R_NO_LOADERS_FOUND 123
+# define OSSL_STORE_R_PASSPHRASE_CALLBACK_ERROR 114
+# define OSSL_STORE_R_PATH_MUST_BE_ABSOLUTE 108
+# define OSSL_STORE_R_SEARCH_ONLY_SUPPORTED_FOR_DIRECTORIES 119
+# define OSSL_STORE_R_UI_PROCESS_INTERRUPTED_OR_CANCELLED 109
+# define OSSL_STORE_R_UNREGISTERED_SCHEME 105
+# define OSSL_STORE_R_UNSUPPORTED_CONTENT_TYPE 110
+# define OSSL_STORE_R_UNSUPPORTED_OPERATION 118
+# define OSSL_STORE_R_UNSUPPORTED_SEARCH_TYPE 120
+# define OSSL_STORE_R_URI_AUTHORITY_UNSUPPORTED 111
+
+#endif
diff --git a/include/openssl/symhacks.h b/include/openssl/symhacks.h
new file mode 100644
index 00000000..816f8f99
--- /dev/null
+++ b/include/openssl/symhacks.h
@@ -0,0 +1,39 @@
+/*
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_SYMHACKS_H
+# define OPENSSL_SYMHACKS_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_SYMHACKS_H
+# endif
+
+# include <openssl/e_os2.h>
+
+/* Case insensitive linking causes problems.... */
+# if defined(OPENSSL_SYS_VMS)
+# undef ERR_load_CRYPTO_strings
+# define ERR_load_CRYPTO_strings ERR_load_CRYPTOlib_strings
+# undef OCSP_crlID_new
+# define OCSP_crlID_new OCSP_crlID2_new
+
+# undef d2i_ECPARAMETERS
+# define d2i_ECPARAMETERS d2i_UC_ECPARAMETERS
+# undef i2d_ECPARAMETERS
+# define i2d_ECPARAMETERS i2d_UC_ECPARAMETERS
+# undef d2i_ECPKPARAMETERS
+# define d2i_ECPKPARAMETERS d2i_UC_ECPKPARAMETERS
+# undef i2d_ECPKPARAMETERS
+# define i2d_ECPKPARAMETERS i2d_UC_ECPKPARAMETERS
+
+# endif
+
+#endif /* ! defined HEADER_VMS_IDHACKS_H */
diff --git a/include/openssl/tls1.h b/include/openssl/tls1.h
new file mode 100644
index 00000000..d6e9331f
--- /dev/null
+++ b/include/openssl/tls1.h
@@ -0,0 +1,1223 @@
+/*
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ * Copyright 2005 Nokia. All rights reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_TLS1_H
+# define OPENSSL_TLS1_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_TLS1_H
+# endif
+
+# include <openssl/buffer.h>
+# include <openssl/x509.h>
+# include <openssl/prov_ssl.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Default security level if not overridden at config time */
+# ifndef OPENSSL_TLS_SECURITY_LEVEL
+# define OPENSSL_TLS_SECURITY_LEVEL 1
+# endif
+
+/* TLS*_VERSION constants are defined in prov_ssl.h */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define TLS_MAX_VERSION TLS1_3_VERSION
+# endif
+
+/* Special value for method supporting multiple versions */
+# define TLS_ANY_VERSION 0x10000
+
+# define TLS1_VERSION_MAJOR 0x03
+# define TLS1_VERSION_MINOR 0x01
+
+# define TLS1_1_VERSION_MAJOR 0x03
+# define TLS1_1_VERSION_MINOR 0x02
+
+# define TLS1_2_VERSION_MAJOR 0x03
+# define TLS1_2_VERSION_MINOR 0x03
+
+# define TLS1_get_version(s) \
+ ((SSL_version(s) >> 8) == TLS1_VERSION_MAJOR ? SSL_version(s) : 0)
+
+# define TLS1_get_client_version(s) \
+ ((SSL_client_version(s) >> 8) == TLS1_VERSION_MAJOR ? SSL_client_version(s) : 0)
+
+# define TLS1_AD_DECRYPTION_FAILED 21
+# define TLS1_AD_RECORD_OVERFLOW 22
+# define TLS1_AD_UNKNOWN_CA 48/* fatal */
+# define TLS1_AD_ACCESS_DENIED 49/* fatal */
+# define TLS1_AD_DECODE_ERROR 50/* fatal */
+# define TLS1_AD_DECRYPT_ERROR 51
+# define TLS1_AD_EXPORT_RESTRICTION 60/* fatal */
+# define TLS1_AD_PROTOCOL_VERSION 70/* fatal */
+# define TLS1_AD_INSUFFICIENT_SECURITY 71/* fatal */
+# define TLS1_AD_INTERNAL_ERROR 80/* fatal */
+# define TLS1_AD_INAPPROPRIATE_FALLBACK 86/* fatal */
+# define TLS1_AD_USER_CANCELLED 90
+# define TLS1_AD_NO_RENEGOTIATION 100
+/* TLSv1.3 alerts */
+# define TLS13_AD_MISSING_EXTENSION 109 /* fatal */
+# define TLS13_AD_CERTIFICATE_REQUIRED 116 /* fatal */
+/* codes 110-114 are from RFC3546 */
+# define TLS1_AD_UNSUPPORTED_EXTENSION 110
+# define TLS1_AD_CERTIFICATE_UNOBTAINABLE 111
+# define TLS1_AD_UNRECOGNIZED_NAME 112
+# define TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE 113
+# define TLS1_AD_BAD_CERTIFICATE_HASH_VALUE 114
+# define TLS1_AD_UNKNOWN_PSK_IDENTITY 115/* fatal */
+# define TLS1_AD_NO_APPLICATION_PROTOCOL 120 /* fatal */
+
+/* ExtensionType values from RFC3546 / RFC4366 / RFC6066 */
+# define TLSEXT_TYPE_server_name 0
+# define TLSEXT_TYPE_max_fragment_length 1
+# define TLSEXT_TYPE_client_certificate_url 2
+# define TLSEXT_TYPE_trusted_ca_keys 3
+# define TLSEXT_TYPE_truncated_hmac 4
+# define TLSEXT_TYPE_status_request 5
+/* ExtensionType values from RFC4681 */
+# define TLSEXT_TYPE_user_mapping 6
+/* ExtensionType values from RFC5878 */
+# define TLSEXT_TYPE_client_authz 7
+# define TLSEXT_TYPE_server_authz 8
+/* ExtensionType values from RFC6091 */
+# define TLSEXT_TYPE_cert_type 9
+
+/* ExtensionType values from RFC4492 */
+/*
+ * Prior to TLSv1.3 the supported_groups extension was known as
+ * elliptic_curves
+ */
+# define TLSEXT_TYPE_supported_groups 10
+# define TLSEXT_TYPE_elliptic_curves TLSEXT_TYPE_supported_groups
+# define TLSEXT_TYPE_ec_point_formats 11
+
+
+/* ExtensionType value from RFC5054 */
+# define TLSEXT_TYPE_srp 12
+
+/* ExtensionType values from RFC5246 */
+# define TLSEXT_TYPE_signature_algorithms 13
+
+/* ExtensionType value from RFC5764 */
+# define TLSEXT_TYPE_use_srtp 14
+
+/* ExtensionType value from RFC7301 */
+# define TLSEXT_TYPE_application_layer_protocol_negotiation 16
+
+/*
+ * Extension type for Certificate Transparency
+ * https://tools.ietf.org/html/rfc6962#section-3.3.1
+ */
+# define TLSEXT_TYPE_signed_certificate_timestamp 18
+
+/*
+ * ExtensionType value for TLS padding extension.
+ * http://tools.ietf.org/html/draft-agl-tls-padding
+ */
+# define TLSEXT_TYPE_padding 21
+
+/* ExtensionType value from RFC7366 */
+# define TLSEXT_TYPE_encrypt_then_mac 22
+
+/* ExtensionType value from RFC7627 */
+# define TLSEXT_TYPE_extended_master_secret 23
+
+/* ExtensionType value from RFC4507 */
+# define TLSEXT_TYPE_session_ticket 35
+
+/* As defined for TLS1.3 */
+# define TLSEXT_TYPE_psk 41
+# define TLSEXT_TYPE_early_data 42
+# define TLSEXT_TYPE_supported_versions 43
+# define TLSEXT_TYPE_cookie 44
+# define TLSEXT_TYPE_psk_kex_modes 45
+# define TLSEXT_TYPE_certificate_authorities 47
+# define TLSEXT_TYPE_post_handshake_auth 49
+# define TLSEXT_TYPE_signature_algorithms_cert 50
+# define TLSEXT_TYPE_key_share 51
+
+/* Temporary extension type */
+# define TLSEXT_TYPE_renegotiate 0xff01
+
+# ifndef OPENSSL_NO_NEXTPROTONEG
+/* This is not an IANA defined extension number */
+# define TLSEXT_TYPE_next_proto_neg 13172
+# endif
+
+/* NameType value from RFC3546 */
+# define TLSEXT_NAMETYPE_host_name 0
+/* status request value from RFC3546 */
+# define TLSEXT_STATUSTYPE_ocsp 1
+
+/* ECPointFormat values from RFC4492 */
+# define TLSEXT_ECPOINTFORMAT_first 0
+# define TLSEXT_ECPOINTFORMAT_uncompressed 0
+# define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_prime 1
+# define TLSEXT_ECPOINTFORMAT_ansiX962_compressed_char2 2
+# define TLSEXT_ECPOINTFORMAT_last 2
+
+/* Signature and hash algorithms from RFC5246 */
+# define TLSEXT_signature_anonymous 0
+# define TLSEXT_signature_rsa 1
+# define TLSEXT_signature_dsa 2
+# define TLSEXT_signature_ecdsa 3
+# define TLSEXT_signature_gostr34102001 237
+# define TLSEXT_signature_gostr34102012_256 238
+# define TLSEXT_signature_gostr34102012_512 239
+
+/* Total number of different signature algorithms */
+# define TLSEXT_signature_num 7
+
+# define TLSEXT_hash_none 0
+# define TLSEXT_hash_md5 1
+# define TLSEXT_hash_sha1 2
+# define TLSEXT_hash_sha224 3
+# define TLSEXT_hash_sha256 4
+# define TLSEXT_hash_sha384 5
+# define TLSEXT_hash_sha512 6
+# define TLSEXT_hash_gostr3411 237
+# define TLSEXT_hash_gostr34112012_256 238
+# define TLSEXT_hash_gostr34112012_512 239
+
+/* Total number of different digest algorithms */
+
+# define TLSEXT_hash_num 10
+
+/* Flag set for unrecognised algorithms */
+# define TLSEXT_nid_unknown 0x1000000
+
+/* ECC curves */
+
+# define TLSEXT_curve_P_256 23
+# define TLSEXT_curve_P_384 24
+
+/* OpenSSL value to disable maximum fragment length extension */
+# define TLSEXT_max_fragment_length_DISABLED 0
+/* Allowed values for max fragment length extension */
+# define TLSEXT_max_fragment_length_512 1
+# define TLSEXT_max_fragment_length_1024 2
+# define TLSEXT_max_fragment_length_2048 3
+# define TLSEXT_max_fragment_length_4096 4
+
+int SSL_CTX_set_tlsext_max_fragment_length(SSL_CTX *ctx, uint8_t mode);
+int SSL_set_tlsext_max_fragment_length(SSL *ssl, uint8_t mode);
+
+# define TLSEXT_MAXLEN_host_name 255
+
+__owur const char *SSL_get_servername(const SSL *s, const int type);
+__owur int SSL_get_servername_type(const SSL *s);
+/*
+ * SSL_export_keying_material exports a value derived from the master secret,
+ * as specified in RFC 5705. It writes |olen| bytes to |out| given a label and
+ * optional context. (Since a zero length context is allowed, the |use_context|
+ * flag controls whether a context is included.) It returns 1 on success and
+ * 0 or -1 otherwise.
+ */
+__owur int SSL_export_keying_material(SSL *s, unsigned char *out, size_t olen,
+ const char *label, size_t llen,
+ const unsigned char *context,
+ size_t contextlen, int use_context);
+
+/*
+ * SSL_export_keying_material_early exports a value derived from the
+ * early exporter master secret, as specified in
+ * https://tools.ietf.org/html/draft-ietf-tls-tls13-23. It writes
+ * |olen| bytes to |out| given a label and optional context. It
+ * returns 1 on success and 0 otherwise.
+ */
+__owur int SSL_export_keying_material_early(SSL *s, unsigned char *out,
+ size_t olen, const char *label,
+ size_t llen,
+ const unsigned char *context,
+ size_t contextlen);
+
+int SSL_get_peer_signature_type_nid(const SSL *s, int *pnid);
+int SSL_get_signature_type_nid(const SSL *s, int *pnid);
+
+int SSL_get_sigalgs(SSL *s, int idx,
+ int *psign, int *phash, int *psignandhash,
+ unsigned char *rsig, unsigned char *rhash);
+
+int SSL_get_shared_sigalgs(SSL *s, int idx,
+ int *psign, int *phash, int *psignandhash,
+ unsigned char *rsig, unsigned char *rhash);
+
+__owur int SSL_check_chain(SSL *s, X509 *x, EVP_PKEY *pk, STACK_OF(X509) *chain);
+
+# define SSL_set_tlsext_host_name(s,name) \
+ SSL_ctrl(s,SSL_CTRL_SET_TLSEXT_HOSTNAME,TLSEXT_NAMETYPE_host_name,\
+ (void *)name)
+
+# define SSL_set_tlsext_debug_callback(ssl, cb) \
+ SSL_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_CB,\
+ (void (*)(void))cb)
+
+# define SSL_set_tlsext_debug_arg(ssl, arg) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_DEBUG_ARG,0,arg)
+
+# define SSL_get_tlsext_status_type(ssl) \
+ SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE,0,NULL)
+
+# define SSL_set_tlsext_status_type(ssl, type) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE,type,NULL)
+
+# define SSL_get_tlsext_status_exts(ssl, arg) \
+ SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_EXTS,0,arg)
+
+# define SSL_set_tlsext_status_exts(ssl, arg) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_EXTS,0,arg)
+
+# define SSL_get_tlsext_status_ids(ssl, arg) \
+ SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_IDS,0,arg)
+
+# define SSL_set_tlsext_status_ids(ssl, arg) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_IDS,0,arg)
+
+# define SSL_get_tlsext_status_ocsp_resp(ssl, arg) \
+ SSL_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_OCSP_RESP,0,arg)
+
+# define SSL_set_tlsext_status_ocsp_resp(ssl, arg, arglen) \
+ SSL_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_OCSP_RESP,arglen,arg)
+
+# define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \
+ SSL_CTX_callback_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_CB,\
+ (void (*)(void))cb)
+
+# define SSL_TLSEXT_ERR_OK 0
+# define SSL_TLSEXT_ERR_ALERT_WARNING 1
+# define SSL_TLSEXT_ERR_ALERT_FATAL 2
+# define SSL_TLSEXT_ERR_NOACK 3
+
+# define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG,0,arg)
+
+# define SSL_CTX_get_tlsext_ticket_keys(ctx, keys, keylen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_GET_TLSEXT_TICKET_KEYS,keylen,keys)
+# define SSL_CTX_set_tlsext_ticket_keys(ctx, keys, keylen) \
+ SSL_CTX_ctrl(ctx,SSL_CTRL_SET_TLSEXT_TICKET_KEYS,keylen,keys)
+
+# define SSL_CTX_get_tlsext_status_cb(ssl, cb) \
+ SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB,0,(void *)cb)
+# define SSL_CTX_set_tlsext_status_cb(ssl, cb) \
+ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB,\
+ (void (*)(void))cb)
+
+# define SSL_CTX_get_tlsext_status_arg(ssl, arg) \
+ SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_CB_ARG,0,arg)
+# define SSL_CTX_set_tlsext_status_arg(ssl, arg) \
+ SSL_CTX_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_CB_ARG,0,arg)
+
+# define SSL_CTX_set_tlsext_status_type(ssl, type) \
+ SSL_CTX_ctrl(ssl,SSL_CTRL_SET_TLSEXT_STATUS_REQ_TYPE,type,NULL)
+
+# define SSL_CTX_get_tlsext_status_type(ssl) \
+ SSL_CTX_ctrl(ssl,SSL_CTRL_GET_TLSEXT_STATUS_REQ_TYPE,0,NULL)
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define SSL_CTX_set_tlsext_ticket_key_cb(ssl, cb) \
+ SSL_CTX_callback_ctrl(ssl,SSL_CTRL_SET_TLSEXT_TICKET_KEY_CB,\
+ (void (*)(void))cb)
+# endif
+int SSL_CTX_set_tlsext_ticket_key_evp_cb
+ (SSL_CTX *ctx, int (*fp)(SSL *, unsigned char *, unsigned char *,
+ EVP_CIPHER_CTX *, EVP_MAC_CTX *, int));
+
+/* PSK ciphersuites from 4279 */
+# define TLS1_CK_PSK_WITH_RC4_128_SHA 0x0300008A
+# define TLS1_CK_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008B
+# define TLS1_CK_PSK_WITH_AES_128_CBC_SHA 0x0300008C
+# define TLS1_CK_PSK_WITH_AES_256_CBC_SHA 0x0300008D
+# define TLS1_CK_DHE_PSK_WITH_RC4_128_SHA 0x0300008E
+# define TLS1_CK_DHE_PSK_WITH_3DES_EDE_CBC_SHA 0x0300008F
+# define TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA 0x03000090
+# define TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA 0x03000091
+# define TLS1_CK_RSA_PSK_WITH_RC4_128_SHA 0x03000092
+# define TLS1_CK_RSA_PSK_WITH_3DES_EDE_CBC_SHA 0x03000093
+# define TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA 0x03000094
+# define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA 0x03000095
+
+/* PSK ciphersuites from 5487 */
+# define TLS1_CK_PSK_WITH_AES_128_GCM_SHA256 0x030000A8
+# define TLS1_CK_PSK_WITH_AES_256_GCM_SHA384 0x030000A9
+# define TLS1_CK_DHE_PSK_WITH_AES_128_GCM_SHA256 0x030000AA
+# define TLS1_CK_DHE_PSK_WITH_AES_256_GCM_SHA384 0x030000AB
+# define TLS1_CK_RSA_PSK_WITH_AES_128_GCM_SHA256 0x030000AC
+# define TLS1_CK_RSA_PSK_WITH_AES_256_GCM_SHA384 0x030000AD
+# define TLS1_CK_PSK_WITH_AES_128_CBC_SHA256 0x030000AE
+# define TLS1_CK_PSK_WITH_AES_256_CBC_SHA384 0x030000AF
+# define TLS1_CK_PSK_WITH_NULL_SHA256 0x030000B0
+# define TLS1_CK_PSK_WITH_NULL_SHA384 0x030000B1
+# define TLS1_CK_DHE_PSK_WITH_AES_128_CBC_SHA256 0x030000B2
+# define TLS1_CK_DHE_PSK_WITH_AES_256_CBC_SHA384 0x030000B3
+# define TLS1_CK_DHE_PSK_WITH_NULL_SHA256 0x030000B4
+# define TLS1_CK_DHE_PSK_WITH_NULL_SHA384 0x030000B5
+# define TLS1_CK_RSA_PSK_WITH_AES_128_CBC_SHA256 0x030000B6
+# define TLS1_CK_RSA_PSK_WITH_AES_256_CBC_SHA384 0x030000B7
+# define TLS1_CK_RSA_PSK_WITH_NULL_SHA256 0x030000B8
+# define TLS1_CK_RSA_PSK_WITH_NULL_SHA384 0x030000B9
+
+/* NULL PSK ciphersuites from RFC4785 */
+# define TLS1_CK_PSK_WITH_NULL_SHA 0x0300002C
+# define TLS1_CK_DHE_PSK_WITH_NULL_SHA 0x0300002D
+# define TLS1_CK_RSA_PSK_WITH_NULL_SHA 0x0300002E
+
+/* AES ciphersuites from RFC3268 */
+# define TLS1_CK_RSA_WITH_AES_128_SHA 0x0300002F
+# define TLS1_CK_DH_DSS_WITH_AES_128_SHA 0x03000030
+# define TLS1_CK_DH_RSA_WITH_AES_128_SHA 0x03000031
+# define TLS1_CK_DHE_DSS_WITH_AES_128_SHA 0x03000032
+# define TLS1_CK_DHE_RSA_WITH_AES_128_SHA 0x03000033
+# define TLS1_CK_ADH_WITH_AES_128_SHA 0x03000034
+# define TLS1_CK_RSA_WITH_AES_256_SHA 0x03000035
+# define TLS1_CK_DH_DSS_WITH_AES_256_SHA 0x03000036
+# define TLS1_CK_DH_RSA_WITH_AES_256_SHA 0x03000037
+# define TLS1_CK_DHE_DSS_WITH_AES_256_SHA 0x03000038
+# define TLS1_CK_DHE_RSA_WITH_AES_256_SHA 0x03000039
+# define TLS1_CK_ADH_WITH_AES_256_SHA 0x0300003A
+
+/* TLS v1.2 ciphersuites */
+# define TLS1_CK_RSA_WITH_NULL_SHA256 0x0300003B
+# define TLS1_CK_RSA_WITH_AES_128_SHA256 0x0300003C
+# define TLS1_CK_RSA_WITH_AES_256_SHA256 0x0300003D
+# define TLS1_CK_DH_DSS_WITH_AES_128_SHA256 0x0300003E
+# define TLS1_CK_DH_RSA_WITH_AES_128_SHA256 0x0300003F
+# define TLS1_CK_DHE_DSS_WITH_AES_128_SHA256 0x03000040
+
+/* Camellia ciphersuites from RFC4132 */
+# define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000041
+# define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000042
+# define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000043
+# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA 0x03000044
+# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x03000045
+# define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA 0x03000046
+
+/* TLS v1.2 ciphersuites */
+# define TLS1_CK_DHE_RSA_WITH_AES_128_SHA256 0x03000067
+# define TLS1_CK_DH_DSS_WITH_AES_256_SHA256 0x03000068
+# define TLS1_CK_DH_RSA_WITH_AES_256_SHA256 0x03000069
+# define TLS1_CK_DHE_DSS_WITH_AES_256_SHA256 0x0300006A
+# define TLS1_CK_DHE_RSA_WITH_AES_256_SHA256 0x0300006B
+# define TLS1_CK_ADH_WITH_AES_128_SHA256 0x0300006C
+# define TLS1_CK_ADH_WITH_AES_256_SHA256 0x0300006D
+
+/* Camellia ciphersuites from RFC4132 */
+# define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000084
+# define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000085
+# define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000086
+# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA 0x03000087
+# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x03000088
+# define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA 0x03000089
+
+/* SEED ciphersuites from RFC4162 */
+# define TLS1_CK_RSA_WITH_SEED_SHA 0x03000096
+# define TLS1_CK_DH_DSS_WITH_SEED_SHA 0x03000097
+# define TLS1_CK_DH_RSA_WITH_SEED_SHA 0x03000098
+# define TLS1_CK_DHE_DSS_WITH_SEED_SHA 0x03000099
+# define TLS1_CK_DHE_RSA_WITH_SEED_SHA 0x0300009A
+# define TLS1_CK_ADH_WITH_SEED_SHA 0x0300009B
+
+/* TLS v1.2 GCM ciphersuites from RFC5288 */
+# define TLS1_CK_RSA_WITH_AES_128_GCM_SHA256 0x0300009C
+# define TLS1_CK_RSA_WITH_AES_256_GCM_SHA384 0x0300009D
+# define TLS1_CK_DHE_RSA_WITH_AES_128_GCM_SHA256 0x0300009E
+# define TLS1_CK_DHE_RSA_WITH_AES_256_GCM_SHA384 0x0300009F
+# define TLS1_CK_DH_RSA_WITH_AES_128_GCM_SHA256 0x030000A0
+# define TLS1_CK_DH_RSA_WITH_AES_256_GCM_SHA384 0x030000A1
+# define TLS1_CK_DHE_DSS_WITH_AES_128_GCM_SHA256 0x030000A2
+# define TLS1_CK_DHE_DSS_WITH_AES_256_GCM_SHA384 0x030000A3
+# define TLS1_CK_DH_DSS_WITH_AES_128_GCM_SHA256 0x030000A4
+# define TLS1_CK_DH_DSS_WITH_AES_256_GCM_SHA384 0x030000A5
+# define TLS1_CK_ADH_WITH_AES_128_GCM_SHA256 0x030000A6
+# define TLS1_CK_ADH_WITH_AES_256_GCM_SHA384 0x030000A7
+
+/* CCM ciphersuites from RFC6655 */
+# define TLS1_CK_RSA_WITH_AES_128_CCM 0x0300C09C
+# define TLS1_CK_RSA_WITH_AES_256_CCM 0x0300C09D
+# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM 0x0300C09E
+# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM 0x0300C09F
+# define TLS1_CK_RSA_WITH_AES_128_CCM_8 0x0300C0A0
+# define TLS1_CK_RSA_WITH_AES_256_CCM_8 0x0300C0A1
+# define TLS1_CK_DHE_RSA_WITH_AES_128_CCM_8 0x0300C0A2
+# define TLS1_CK_DHE_RSA_WITH_AES_256_CCM_8 0x0300C0A3
+# define TLS1_CK_PSK_WITH_AES_128_CCM 0x0300C0A4
+# define TLS1_CK_PSK_WITH_AES_256_CCM 0x0300C0A5
+# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM 0x0300C0A6
+# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM 0x0300C0A7
+# define TLS1_CK_PSK_WITH_AES_128_CCM_8 0x0300C0A8
+# define TLS1_CK_PSK_WITH_AES_256_CCM_8 0x0300C0A9
+# define TLS1_CK_DHE_PSK_WITH_AES_128_CCM_8 0x0300C0AA
+# define TLS1_CK_DHE_PSK_WITH_AES_256_CCM_8 0x0300C0AB
+
+/* CCM ciphersuites from RFC7251 */
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM 0x0300C0AC
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM 0x0300C0AD
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CCM_8 0x0300C0AE
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CCM_8 0x0300C0AF
+
+/* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */
+# define TLS1_CK_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BA
+# define TLS1_CK_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 0x030000BB
+# define TLS1_CK_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BC
+# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 0x030000BD
+# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x030000BE
+# define TLS1_CK_ADH_WITH_CAMELLIA_128_CBC_SHA256 0x030000BF
+
+# define TLS1_CK_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C0
+# define TLS1_CK_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 0x030000C1
+# define TLS1_CK_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C2
+# define TLS1_CK_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 0x030000C3
+# define TLS1_CK_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 0x030000C4
+# define TLS1_CK_ADH_WITH_CAMELLIA_256_CBC_SHA256 0x030000C5
+
+/* ECC ciphersuites from RFC4492 */
+# define TLS1_CK_ECDH_ECDSA_WITH_NULL_SHA 0x0300C001
+# define TLS1_CK_ECDH_ECDSA_WITH_RC4_128_SHA 0x0300C002
+# define TLS1_CK_ECDH_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C003
+# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0x0300C004
+# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0x0300C005
+
+# define TLS1_CK_ECDHE_ECDSA_WITH_NULL_SHA 0x0300C006
+# define TLS1_CK_ECDHE_ECDSA_WITH_RC4_128_SHA 0x0300C007
+# define TLS1_CK_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA 0x0300C008
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0x0300C009
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0x0300C00A
+
+# define TLS1_CK_ECDH_RSA_WITH_NULL_SHA 0x0300C00B
+# define TLS1_CK_ECDH_RSA_WITH_RC4_128_SHA 0x0300C00C
+# define TLS1_CK_ECDH_RSA_WITH_DES_192_CBC3_SHA 0x0300C00D
+# define TLS1_CK_ECDH_RSA_WITH_AES_128_CBC_SHA 0x0300C00E
+# define TLS1_CK_ECDH_RSA_WITH_AES_256_CBC_SHA 0x0300C00F
+
+# define TLS1_CK_ECDHE_RSA_WITH_NULL_SHA 0x0300C010
+# define TLS1_CK_ECDHE_RSA_WITH_RC4_128_SHA 0x0300C011
+# define TLS1_CK_ECDHE_RSA_WITH_DES_192_CBC3_SHA 0x0300C012
+# define TLS1_CK_ECDHE_RSA_WITH_AES_128_CBC_SHA 0x0300C013
+# define TLS1_CK_ECDHE_RSA_WITH_AES_256_CBC_SHA 0x0300C014
+
+# define TLS1_CK_ECDH_anon_WITH_NULL_SHA 0x0300C015
+# define TLS1_CK_ECDH_anon_WITH_RC4_128_SHA 0x0300C016
+# define TLS1_CK_ECDH_anon_WITH_DES_192_CBC3_SHA 0x0300C017
+# define TLS1_CK_ECDH_anon_WITH_AES_128_CBC_SHA 0x0300C018
+# define TLS1_CK_ECDH_anon_WITH_AES_256_CBC_SHA 0x0300C019
+
+/* SRP ciphersuites from RFC 5054 */
+# define TLS1_CK_SRP_SHA_WITH_3DES_EDE_CBC_SHA 0x0300C01A
+# define TLS1_CK_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA 0x0300C01B
+# define TLS1_CK_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA 0x0300C01C
+# define TLS1_CK_SRP_SHA_WITH_AES_128_CBC_SHA 0x0300C01D
+# define TLS1_CK_SRP_SHA_RSA_WITH_AES_128_CBC_SHA 0x0300C01E
+# define TLS1_CK_SRP_SHA_DSS_WITH_AES_128_CBC_SHA 0x0300C01F
+# define TLS1_CK_SRP_SHA_WITH_AES_256_CBC_SHA 0x0300C020
+# define TLS1_CK_SRP_SHA_RSA_WITH_AES_256_CBC_SHA 0x0300C021
+# define TLS1_CK_SRP_SHA_DSS_WITH_AES_256_CBC_SHA 0x0300C022
+
+/* ECDH HMAC based ciphersuites from RFC5289 */
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_SHA256 0x0300C023
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_SHA384 0x0300C024
+# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_SHA256 0x0300C025
+# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_SHA384 0x0300C026
+# define TLS1_CK_ECDHE_RSA_WITH_AES_128_SHA256 0x0300C027
+# define TLS1_CK_ECDHE_RSA_WITH_AES_256_SHA384 0x0300C028
+# define TLS1_CK_ECDH_RSA_WITH_AES_128_SHA256 0x0300C029
+# define TLS1_CK_ECDH_RSA_WITH_AES_256_SHA384 0x0300C02A
+
+/* ECDH GCM based ciphersuites from RFC5289 */
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02B
+# define TLS1_CK_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02C
+# define TLS1_CK_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0x0300C02D
+# define TLS1_CK_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0x0300C02E
+# define TLS1_CK_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0x0300C02F
+# define TLS1_CK_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0x0300C030
+# define TLS1_CK_ECDH_RSA_WITH_AES_128_GCM_SHA256 0x0300C031
+# define TLS1_CK_ECDH_RSA_WITH_AES_256_GCM_SHA384 0x0300C032
+
+/* ECDHE PSK ciphersuites from RFC5489 */
+# define TLS1_CK_ECDHE_PSK_WITH_RC4_128_SHA 0x0300C033
+# define TLS1_CK_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA 0x0300C034
+# define TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA 0x0300C035
+# define TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA 0x0300C036
+
+# define TLS1_CK_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0x0300C037
+# define TLS1_CK_ECDHE_PSK_WITH_AES_256_CBC_SHA384 0x0300C038
+
+/* NULL PSK ciphersuites from RFC4785 */
+# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA 0x0300C039
+# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA256 0x0300C03A
+# define TLS1_CK_ECDHE_PSK_WITH_NULL_SHA384 0x0300C03B
+
+/* Camellia-CBC ciphersuites from RFC6367 */
+# define TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C072
+# define TLS1_CK_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C073
+# define TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C074
+# define TLS1_CK_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C075
+# define TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C076
+# define TLS1_CK_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C077
+# define TLS1_CK_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0x0300C078
+# define TLS1_CK_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 0x0300C079
+
+# define TLS1_CK_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C094
+# define TLS1_CK_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C095
+# define TLS1_CK_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C096
+# define TLS1_CK_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C097
+# define TLS1_CK_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C098
+# define TLS1_CK_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C099
+# define TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0x0300C09A
+# define TLS1_CK_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0x0300C09B
+
+/* draft-ietf-tls-chacha20-poly1305-03 */
+# define TLS1_CK_ECDHE_RSA_WITH_CHACHA20_POLY1305 0x0300CCA8
+# define TLS1_CK_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 0x0300CCA9
+# define TLS1_CK_DHE_RSA_WITH_CHACHA20_POLY1305 0x0300CCAA
+# define TLS1_CK_PSK_WITH_CHACHA20_POLY1305 0x0300CCAB
+# define TLS1_CK_ECDHE_PSK_WITH_CHACHA20_POLY1305 0x0300CCAC
+# define TLS1_CK_DHE_PSK_WITH_CHACHA20_POLY1305 0x0300CCAD
+# define TLS1_CK_RSA_PSK_WITH_CHACHA20_POLY1305 0x0300CCAE
+
+/* TLS v1.3 ciphersuites */
+# define TLS1_3_CK_AES_128_GCM_SHA256 0x03001301
+# define TLS1_3_CK_AES_256_GCM_SHA384 0x03001302
+# define TLS1_3_CK_CHACHA20_POLY1305_SHA256 0x03001303
+# define TLS1_3_CK_AES_128_CCM_SHA256 0x03001304
+# define TLS1_3_CK_AES_128_CCM_8_SHA256 0x03001305
+
+/* Aria ciphersuites from RFC6209 */
+# define TLS1_CK_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C050
+# define TLS1_CK_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C051
+# define TLS1_CK_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C052
+# define TLS1_CK_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C053
+# define TLS1_CK_DH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C054
+# define TLS1_CK_DH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C055
+# define TLS1_CK_DHE_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C056
+# define TLS1_CK_DHE_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C057
+# define TLS1_CK_DH_DSS_WITH_ARIA_128_GCM_SHA256 0x0300C058
+# define TLS1_CK_DH_DSS_WITH_ARIA_256_GCM_SHA384 0x0300C059
+# define TLS1_CK_DH_anon_WITH_ARIA_128_GCM_SHA256 0x0300C05A
+# define TLS1_CK_DH_anon_WITH_ARIA_256_GCM_SHA384 0x0300C05B
+# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05C
+# define TLS1_CK_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05D
+# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0x0300C05E
+# define TLS1_CK_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0x0300C05F
+# define TLS1_CK_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C060
+# define TLS1_CK_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C061
+# define TLS1_CK_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0x0300C062
+# define TLS1_CK_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0x0300C063
+# define TLS1_CK_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06A
+# define TLS1_CK_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06B
+# define TLS1_CK_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06C
+# define TLS1_CK_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06D
+# define TLS1_CK_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0x0300C06E
+# define TLS1_CK_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0x0300C06F
+
+/* a bundle of RFC standard cipher names, generated from ssl3_ciphers[] */
+# define TLS1_RFC_RSA_WITH_AES_128_SHA "TLS_RSA_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_DHE_DSS_WITH_AES_128_SHA "TLS_DHE_DSS_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_DHE_RSA_WITH_AES_128_SHA "TLS_DHE_RSA_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_ADH_WITH_AES_128_SHA "TLS_DH_anon_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_RSA_WITH_AES_256_SHA "TLS_RSA_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_DHE_DSS_WITH_AES_256_SHA "TLS_DHE_DSS_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA "TLS_DHE_RSA_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_ADH_WITH_AES_256_SHA "TLS_DH_anon_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_RSA_WITH_NULL_SHA256 "TLS_RSA_WITH_NULL_SHA256"
+# define TLS1_RFC_RSA_WITH_AES_128_SHA256 "TLS_RSA_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_RSA_WITH_AES_256_SHA256 "TLS_RSA_WITH_AES_256_CBC_SHA256"
+# define TLS1_RFC_DHE_DSS_WITH_AES_128_SHA256 "TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_DHE_RSA_WITH_AES_128_SHA256 "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_DHE_DSS_WITH_AES_256_SHA256 "TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"
+# define TLS1_RFC_DHE_RSA_WITH_AES_256_SHA256 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"
+# define TLS1_RFC_ADH_WITH_AES_128_SHA256 "TLS_DH_anon_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_ADH_WITH_AES_256_SHA256 "TLS_DH_anon_WITH_AES_256_CBC_SHA256"
+# define TLS1_RFC_RSA_WITH_AES_128_GCM_SHA256 "TLS_RSA_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_RSA_WITH_AES_256_GCM_SHA384 "TLS_RSA_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_DHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_DHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_DHE_DSS_WITH_AES_128_GCM_SHA256 "TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_DHE_DSS_WITH_AES_256_GCM_SHA384 "TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_ADH_WITH_AES_128_GCM_SHA256 "TLS_DH_anon_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_ADH_WITH_AES_256_GCM_SHA384 "TLS_DH_anon_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_RSA_WITH_AES_128_CCM "TLS_RSA_WITH_AES_128_CCM"
+# define TLS1_RFC_RSA_WITH_AES_256_CCM "TLS_RSA_WITH_AES_256_CCM"
+# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM "TLS_DHE_RSA_WITH_AES_128_CCM"
+# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM "TLS_DHE_RSA_WITH_AES_256_CCM"
+# define TLS1_RFC_RSA_WITH_AES_128_CCM_8 "TLS_RSA_WITH_AES_128_CCM_8"
+# define TLS1_RFC_RSA_WITH_AES_256_CCM_8 "TLS_RSA_WITH_AES_256_CCM_8"
+# define TLS1_RFC_DHE_RSA_WITH_AES_128_CCM_8 "TLS_DHE_RSA_WITH_AES_128_CCM_8"
+# define TLS1_RFC_DHE_RSA_WITH_AES_256_CCM_8 "TLS_DHE_RSA_WITH_AES_256_CCM_8"
+# define TLS1_RFC_PSK_WITH_AES_128_CCM "TLS_PSK_WITH_AES_128_CCM"
+# define TLS1_RFC_PSK_WITH_AES_256_CCM "TLS_PSK_WITH_AES_256_CCM"
+# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM "TLS_DHE_PSK_WITH_AES_128_CCM"
+# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM "TLS_DHE_PSK_WITH_AES_256_CCM"
+# define TLS1_RFC_PSK_WITH_AES_128_CCM_8 "TLS_PSK_WITH_AES_128_CCM_8"
+# define TLS1_RFC_PSK_WITH_AES_256_CCM_8 "TLS_PSK_WITH_AES_256_CCM_8"
+# define TLS1_RFC_DHE_PSK_WITH_AES_128_CCM_8 "TLS_PSK_DHE_WITH_AES_128_CCM_8"
+# define TLS1_RFC_DHE_PSK_WITH_AES_256_CCM_8 "TLS_PSK_DHE_WITH_AES_256_CCM_8"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM "TLS_ECDHE_ECDSA_WITH_AES_128_CCM"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM "TLS_ECDHE_ECDSA_WITH_AES_256_CCM"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CCM_8 "TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"
+# define TLS1_3_RFC_AES_128_GCM_SHA256 "TLS_AES_128_GCM_SHA256"
+# define TLS1_3_RFC_AES_256_GCM_SHA384 "TLS_AES_256_GCM_SHA384"
+# define TLS1_3_RFC_CHACHA20_POLY1305_SHA256 "TLS_CHACHA20_POLY1305_SHA256"
+# define TLS1_3_RFC_AES_128_CCM_SHA256 "TLS_AES_128_CCM_SHA256"
+# define TLS1_3_RFC_AES_128_CCM_8_SHA256 "TLS_AES_128_CCM_8_SHA256"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_NULL_SHA "TLS_ECDHE_ECDSA_WITH_NULL_SHA"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_ECDHE_RSA_WITH_NULL_SHA "TLS_ECDHE_RSA_WITH_NULL_SHA"
+# define TLS1_RFC_ECDHE_RSA_WITH_DES_192_CBC3_SHA "TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_CBC_SHA "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_CBC_SHA "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_ECDH_anon_WITH_NULL_SHA "TLS_ECDH_anon_WITH_NULL_SHA"
+# define TLS1_RFC_ECDH_anon_WITH_DES_192_CBC3_SHA "TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_ECDH_anon_WITH_AES_128_CBC_SHA "TLS_ECDH_anon_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_ECDH_anon_WITH_AES_256_CBC_SHA "TLS_ECDH_anon_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"
+# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_PSK_WITH_NULL_SHA "TLS_PSK_WITH_NULL_SHA"
+# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA "TLS_DHE_PSK_WITH_NULL_SHA"
+# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA "TLS_RSA_PSK_WITH_NULL_SHA"
+# define TLS1_RFC_PSK_WITH_3DES_EDE_CBC_SHA "TLS_PSK_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA "TLS_PSK_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA "TLS_PSK_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_DHE_PSK_WITH_3DES_EDE_CBC_SHA "TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_DHE_PSK_WITH_AES_128_CBC_SHA "TLS_DHE_PSK_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_DHE_PSK_WITH_AES_256_CBC_SHA "TLS_DHE_PSK_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_RSA_PSK_WITH_3DES_EDE_CBC_SHA "TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA "TLS_RSA_PSK_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA "TLS_RSA_PSK_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_PSK_WITH_AES_128_GCM_SHA256 "TLS_PSK_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_PSK_WITH_AES_256_GCM_SHA384 "TLS_PSK_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_DHE_PSK_WITH_AES_128_GCM_SHA256 "TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_DHE_PSK_WITH_AES_256_GCM_SHA384 "TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_RSA_PSK_WITH_AES_128_GCM_SHA256 "TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"
+# define TLS1_RFC_RSA_PSK_WITH_AES_256_GCM_SHA384 "TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"
+# define TLS1_RFC_PSK_WITH_AES_128_CBC_SHA256 "TLS_PSK_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_PSK_WITH_AES_256_CBC_SHA384 "TLS_PSK_WITH_AES_256_CBC_SHA384"
+# define TLS1_RFC_PSK_WITH_NULL_SHA256 "TLS_PSK_WITH_NULL_SHA256"
+# define TLS1_RFC_PSK_WITH_NULL_SHA384 "TLS_PSK_WITH_NULL_SHA384"
+# define TLS1_RFC_DHE_PSK_WITH_AES_128_CBC_SHA256 "TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_DHE_PSK_WITH_AES_256_CBC_SHA384 "TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"
+# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA256 "TLS_DHE_PSK_WITH_NULL_SHA256"
+# define TLS1_RFC_DHE_PSK_WITH_NULL_SHA384 "TLS_DHE_PSK_WITH_NULL_SHA384"
+# define TLS1_RFC_RSA_PSK_WITH_AES_128_CBC_SHA256 "TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_RSA_PSK_WITH_AES_256_CBC_SHA384 "TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"
+# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA256 "TLS_RSA_PSK_WITH_NULL_SHA256"
+# define TLS1_RFC_RSA_PSK_WITH_NULL_SHA384 "TLS_RSA_PSK_WITH_NULL_SHA384"
+# define TLS1_RFC_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA "TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_ECDHE_PSK_WITH_AES_128_CBC_SHA "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_ECDHE_PSK_WITH_AES_256_CBC_SHA "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_ECDHE_PSK_WITH_AES_128_CBC_SHA256 "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"
+# define TLS1_RFC_ECDHE_PSK_WITH_AES_256_CBC_SHA384 "TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"
+# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA "TLS_ECDHE_PSK_WITH_NULL_SHA"
+# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA256 "TLS_ECDHE_PSK_WITH_NULL_SHA256"
+# define TLS1_RFC_ECDHE_PSK_WITH_NULL_SHA384 "TLS_ECDHE_PSK_WITH_NULL_SHA384"
+# define TLS1_RFC_SRP_SHA_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA "TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_RSA_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_DSS_WITH_AES_128_CBC_SHA "TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_RSA_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_SRP_SHA_DSS_WITH_AES_256_CBC_SHA "TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"
+# define TLS1_RFC_DHE_RSA_WITH_CHACHA20_POLY1305 "TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"
+# define TLS1_RFC_ECDHE_RSA_WITH_CHACHA20_POLY1305 "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"
+# define TLS1_RFC_PSK_WITH_CHACHA20_POLY1305 "TLS_PSK_WITH_CHACHA20_POLY1305_SHA256"
+# define TLS1_RFC_ECDHE_PSK_WITH_CHACHA20_POLY1305 "TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256"
+# define TLS1_RFC_DHE_PSK_WITH_CHACHA20_POLY1305 "TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256"
+# define TLS1_RFC_RSA_PSK_WITH_CHACHA20_POLY1305 "TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256"
+# define TLS1_RFC_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_ADH_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_RSA_WITH_CAMELLIA_256_CBC_SHA256 "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"
+# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"
+# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"
+# define TLS1_RFC_ADH_WITH_CAMELLIA_256_CBC_SHA256 "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"
+# define TLS1_RFC_RSA_WITH_CAMELLIA_256_CBC_SHA "TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"
+# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"
+# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"
+# define TLS1_RFC_ADH_WITH_CAMELLIA_256_CBC_SHA "TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"
+# define TLS1_RFC_RSA_WITH_CAMELLIA_128_CBC_SHA "TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"
+# define TLS1_RFC_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"
+# define TLS1_RFC_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"
+# define TLS1_RFC_ADH_WITH_CAMELLIA_128_CBC_SHA "TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"
+# define TLS1_RFC_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384"
+# define TLS1_RFC_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384"
+# define TLS1_RFC_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"
+# define TLS1_RFC_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384"
+# define TLS1_RFC_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"
+# define TLS1_RFC_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"
+# define TLS1_RFC_RSA_WITH_SEED_SHA "TLS_RSA_WITH_SEED_CBC_SHA"
+# define TLS1_RFC_DHE_DSS_WITH_SEED_SHA "TLS_DHE_DSS_WITH_SEED_CBC_SHA"
+# define TLS1_RFC_DHE_RSA_WITH_SEED_SHA "TLS_DHE_RSA_WITH_SEED_CBC_SHA"
+# define TLS1_RFC_ADH_WITH_SEED_SHA "TLS_DH_anon_WITH_SEED_CBC_SHA"
+# define TLS1_RFC_ECDHE_PSK_WITH_RC4_128_SHA "TLS_ECDHE_PSK_WITH_RC4_128_SHA"
+# define TLS1_RFC_ECDH_anon_WITH_RC4_128_SHA "TLS_ECDH_anon_WITH_RC4_128_SHA"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_RC4_128_SHA "TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"
+# define TLS1_RFC_ECDHE_RSA_WITH_RC4_128_SHA "TLS_ECDHE_RSA_WITH_RC4_128_SHA"
+# define TLS1_RFC_PSK_WITH_RC4_128_SHA "TLS_PSK_WITH_RC4_128_SHA"
+# define TLS1_RFC_RSA_PSK_WITH_RC4_128_SHA "TLS_RSA_PSK_WITH_RC4_128_SHA"
+# define TLS1_RFC_DHE_PSK_WITH_RC4_128_SHA "TLS_DHE_PSK_WITH_RC4_128_SHA"
+# define TLS1_RFC_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_DH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_DH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_DH_DSS_WITH_ARIA_128_GCM_SHA256 "TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_DH_DSS_WITH_ARIA_256_GCM_SHA384 "TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_DH_anon_WITH_ARIA_128_GCM_SHA256 "TLS_DH_anon_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_DH_anon_WITH_ARIA_256_GCM_SHA384 "TLS_DH_anon_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_PSK_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_PSK_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384"
+# define TLS1_RFC_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256"
+# define TLS1_RFC_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384"
+
+
+/*
+ * XXX Backward compatibility alert: Older versions of OpenSSL gave some DHE
+ * ciphers names with "EDH" instead of "DHE". Going forward, we should be
+ * using DHE everywhere, though we may indefinitely maintain aliases for
+ * users or configurations that used "EDH"
+ */
+# define TLS1_TXT_DHE_DSS_WITH_RC4_128_SHA "DHE-DSS-RC4-SHA"
+
+# define TLS1_TXT_PSK_WITH_NULL_SHA "PSK-NULL-SHA"
+# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA "DHE-PSK-NULL-SHA"
+# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA "RSA-PSK-NULL-SHA"
+
+/* AES ciphersuites from RFC3268 */
+# define TLS1_TXT_RSA_WITH_AES_128_SHA "AES128-SHA"
+# define TLS1_TXT_DH_DSS_WITH_AES_128_SHA "DH-DSS-AES128-SHA"
+# define TLS1_TXT_DH_RSA_WITH_AES_128_SHA "DH-RSA-AES128-SHA"
+# define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA "DHE-DSS-AES128-SHA"
+# define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA "DHE-RSA-AES128-SHA"
+# define TLS1_TXT_ADH_WITH_AES_128_SHA "ADH-AES128-SHA"
+
+# define TLS1_TXT_RSA_WITH_AES_256_SHA "AES256-SHA"
+# define TLS1_TXT_DH_DSS_WITH_AES_256_SHA "DH-DSS-AES256-SHA"
+# define TLS1_TXT_DH_RSA_WITH_AES_256_SHA "DH-RSA-AES256-SHA"
+# define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA "DHE-DSS-AES256-SHA"
+# define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA "DHE-RSA-AES256-SHA"
+# define TLS1_TXT_ADH_WITH_AES_256_SHA "ADH-AES256-SHA"
+
+/* ECC ciphersuites from RFC4492 */
+# define TLS1_TXT_ECDH_ECDSA_WITH_NULL_SHA "ECDH-ECDSA-NULL-SHA"
+# define TLS1_TXT_ECDH_ECDSA_WITH_RC4_128_SHA "ECDH-ECDSA-RC4-SHA"
+# define TLS1_TXT_ECDH_ECDSA_WITH_DES_192_CBC3_SHA "ECDH-ECDSA-DES-CBC3-SHA"
+# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_CBC_SHA "ECDH-ECDSA-AES128-SHA"
+# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_CBC_SHA "ECDH-ECDSA-AES256-SHA"
+
+# define TLS1_TXT_ECDHE_ECDSA_WITH_NULL_SHA "ECDHE-ECDSA-NULL-SHA"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_RC4_128_SHA "ECDHE-ECDSA-RC4-SHA"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_DES_192_CBC3_SHA "ECDHE-ECDSA-DES-CBC3-SHA"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CBC_SHA "ECDHE-ECDSA-AES128-SHA"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CBC_SHA "ECDHE-ECDSA-AES256-SHA"
+
+# define TLS1_TXT_ECDH_RSA_WITH_NULL_SHA "ECDH-RSA-NULL-SHA"
+# define TLS1_TXT_ECDH_RSA_WITH_RC4_128_SHA "ECDH-RSA-RC4-SHA"
+# define TLS1_TXT_ECDH_RSA_WITH_DES_192_CBC3_SHA "ECDH-RSA-DES-CBC3-SHA"
+# define TLS1_TXT_ECDH_RSA_WITH_AES_128_CBC_SHA "ECDH-RSA-AES128-SHA"
+# define TLS1_TXT_ECDH_RSA_WITH_AES_256_CBC_SHA "ECDH-RSA-AES256-SHA"
+
+# define TLS1_TXT_ECDHE_RSA_WITH_NULL_SHA "ECDHE-RSA-NULL-SHA"
+# define TLS1_TXT_ECDHE_RSA_WITH_RC4_128_SHA "ECDHE-RSA-RC4-SHA"
+# define TLS1_TXT_ECDHE_RSA_WITH_DES_192_CBC3_SHA "ECDHE-RSA-DES-CBC3-SHA"
+# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_CBC_SHA "ECDHE-RSA-AES128-SHA"
+# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_CBC_SHA "ECDHE-RSA-AES256-SHA"
+
+# define TLS1_TXT_ECDH_anon_WITH_NULL_SHA "AECDH-NULL-SHA"
+# define TLS1_TXT_ECDH_anon_WITH_RC4_128_SHA "AECDH-RC4-SHA"
+# define TLS1_TXT_ECDH_anon_WITH_DES_192_CBC3_SHA "AECDH-DES-CBC3-SHA"
+# define TLS1_TXT_ECDH_anon_WITH_AES_128_CBC_SHA "AECDH-AES128-SHA"
+# define TLS1_TXT_ECDH_anon_WITH_AES_256_CBC_SHA "AECDH-AES256-SHA"
+
+/* PSK ciphersuites from RFC 4279 */
+# define TLS1_TXT_PSK_WITH_RC4_128_SHA "PSK-RC4-SHA"
+# define TLS1_TXT_PSK_WITH_3DES_EDE_CBC_SHA "PSK-3DES-EDE-CBC-SHA"
+# define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA "PSK-AES128-CBC-SHA"
+# define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA "PSK-AES256-CBC-SHA"
+
+# define TLS1_TXT_DHE_PSK_WITH_RC4_128_SHA "DHE-PSK-RC4-SHA"
+# define TLS1_TXT_DHE_PSK_WITH_3DES_EDE_CBC_SHA "DHE-PSK-3DES-EDE-CBC-SHA"
+# define TLS1_TXT_DHE_PSK_WITH_AES_128_CBC_SHA "DHE-PSK-AES128-CBC-SHA"
+# define TLS1_TXT_DHE_PSK_WITH_AES_256_CBC_SHA "DHE-PSK-AES256-CBC-SHA"
+# define TLS1_TXT_RSA_PSK_WITH_RC4_128_SHA "RSA-PSK-RC4-SHA"
+# define TLS1_TXT_RSA_PSK_WITH_3DES_EDE_CBC_SHA "RSA-PSK-3DES-EDE-CBC-SHA"
+# define TLS1_TXT_RSA_PSK_WITH_AES_128_CBC_SHA "RSA-PSK-AES128-CBC-SHA"
+# define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA "RSA-PSK-AES256-CBC-SHA"
+
+/* PSK ciphersuites from RFC 5487 */
+# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256"
+# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384"
+# define TLS1_TXT_DHE_PSK_WITH_AES_128_GCM_SHA256 "DHE-PSK-AES128-GCM-SHA256"
+# define TLS1_TXT_DHE_PSK_WITH_AES_256_GCM_SHA384 "DHE-PSK-AES256-GCM-SHA384"
+# define TLS1_TXT_RSA_PSK_WITH_AES_128_GCM_SHA256 "RSA-PSK-AES128-GCM-SHA256"
+# define TLS1_TXT_RSA_PSK_WITH_AES_256_GCM_SHA384 "RSA-PSK-AES256-GCM-SHA384"
+
+# define TLS1_TXT_PSK_WITH_AES_128_CBC_SHA256 "PSK-AES128-CBC-SHA256"
+# define TLS1_TXT_PSK_WITH_AES_256_CBC_SHA384 "PSK-AES256-CBC-SHA384"
+# define TLS1_TXT_PSK_WITH_NULL_SHA256 "PSK-NULL-SHA256"
+# define TLS1_TXT_PSK_WITH_NULL_SHA384 "PSK-NULL-SHA384"
+
+# define TLS1_TXT_DHE_PSK_WITH_AES_128_CBC_SHA256 "DHE-PSK-AES128-CBC-SHA256"
+# define TLS1_TXT_DHE_PSK_WITH_AES_256_CBC_SHA384 "DHE-PSK-AES256-CBC-SHA384"
+# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA256 "DHE-PSK-NULL-SHA256"
+# define TLS1_TXT_DHE_PSK_WITH_NULL_SHA384 "DHE-PSK-NULL-SHA384"
+
+# define TLS1_TXT_RSA_PSK_WITH_AES_128_CBC_SHA256 "RSA-PSK-AES128-CBC-SHA256"
+# define TLS1_TXT_RSA_PSK_WITH_AES_256_CBC_SHA384 "RSA-PSK-AES256-CBC-SHA384"
+# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA256 "RSA-PSK-NULL-SHA256"
+# define TLS1_TXT_RSA_PSK_WITH_NULL_SHA384 "RSA-PSK-NULL-SHA384"
+
+/* SRP ciphersuite from RFC 5054 */
+# define TLS1_TXT_SRP_SHA_WITH_3DES_EDE_CBC_SHA "SRP-3DES-EDE-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA "SRP-RSA-3DES-EDE-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA "SRP-DSS-3DES-EDE-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_WITH_AES_128_CBC_SHA "SRP-AES-128-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_RSA_WITH_AES_128_CBC_SHA "SRP-RSA-AES-128-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_DSS_WITH_AES_128_CBC_SHA "SRP-DSS-AES-128-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_WITH_AES_256_CBC_SHA "SRP-AES-256-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_RSA_WITH_AES_256_CBC_SHA "SRP-RSA-AES-256-CBC-SHA"
+# define TLS1_TXT_SRP_SHA_DSS_WITH_AES_256_CBC_SHA "SRP-DSS-AES-256-CBC-SHA"
+
+/* Camellia ciphersuites from RFC4132 */
+# define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA "CAMELLIA128-SHA"
+# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA "DH-DSS-CAMELLIA128-SHA"
+# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA "DH-RSA-CAMELLIA128-SHA"
+# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA "DHE-DSS-CAMELLIA128-SHA"
+# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA "DHE-RSA-CAMELLIA128-SHA"
+# define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA "ADH-CAMELLIA128-SHA"
+
+# define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA "CAMELLIA256-SHA"
+# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA "DH-DSS-CAMELLIA256-SHA"
+# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA "DH-RSA-CAMELLIA256-SHA"
+# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA "DHE-DSS-CAMELLIA256-SHA"
+# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA "DHE-RSA-CAMELLIA256-SHA"
+# define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA "ADH-CAMELLIA256-SHA"
+
+/* TLS 1.2 Camellia SHA-256 ciphersuites from RFC5932 */
+# define TLS1_TXT_RSA_WITH_CAMELLIA_128_CBC_SHA256 "CAMELLIA128-SHA256"
+# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256 "DH-DSS-CAMELLIA128-SHA256"
+# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256 "DH-RSA-CAMELLIA128-SHA256"
+# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256 "DHE-DSS-CAMELLIA128-SHA256"
+# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "DHE-RSA-CAMELLIA128-SHA256"
+# define TLS1_TXT_ADH_WITH_CAMELLIA_128_CBC_SHA256 "ADH-CAMELLIA128-SHA256"
+
+# define TLS1_TXT_RSA_WITH_CAMELLIA_256_CBC_SHA256 "CAMELLIA256-SHA256"
+# define TLS1_TXT_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256 "DH-DSS-CAMELLIA256-SHA256"
+# define TLS1_TXT_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256 "DH-RSA-CAMELLIA256-SHA256"
+# define TLS1_TXT_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256 "DHE-DSS-CAMELLIA256-SHA256"
+# define TLS1_TXT_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 "DHE-RSA-CAMELLIA256-SHA256"
+# define TLS1_TXT_ADH_WITH_CAMELLIA_256_CBC_SHA256 "ADH-CAMELLIA256-SHA256"
+
+# define TLS1_TXT_PSK_WITH_CAMELLIA_128_CBC_SHA256 "PSK-CAMELLIA128-SHA256"
+# define TLS1_TXT_PSK_WITH_CAMELLIA_256_CBC_SHA384 "PSK-CAMELLIA256-SHA384"
+# define TLS1_TXT_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "DHE-PSK-CAMELLIA128-SHA256"
+# define TLS1_TXT_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "DHE-PSK-CAMELLIA256-SHA384"
+# define TLS1_TXT_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 "RSA-PSK-CAMELLIA128-SHA256"
+# define TLS1_TXT_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 "RSA-PSK-CAMELLIA256-SHA384"
+# define TLS1_TXT_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-PSK-CAMELLIA128-SHA256"
+# define TLS1_TXT_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-PSK-CAMELLIA256-SHA384"
+
+/* SEED ciphersuites from RFC4162 */
+# define TLS1_TXT_RSA_WITH_SEED_SHA "SEED-SHA"
+# define TLS1_TXT_DH_DSS_WITH_SEED_SHA "DH-DSS-SEED-SHA"
+# define TLS1_TXT_DH_RSA_WITH_SEED_SHA "DH-RSA-SEED-SHA"
+# define TLS1_TXT_DHE_DSS_WITH_SEED_SHA "DHE-DSS-SEED-SHA"
+# define TLS1_TXT_DHE_RSA_WITH_SEED_SHA "DHE-RSA-SEED-SHA"
+# define TLS1_TXT_ADH_WITH_SEED_SHA "ADH-SEED-SHA"
+
+/* TLS v1.2 ciphersuites */
+# define TLS1_TXT_RSA_WITH_NULL_SHA256 "NULL-SHA256"
+# define TLS1_TXT_RSA_WITH_AES_128_SHA256 "AES128-SHA256"
+# define TLS1_TXT_RSA_WITH_AES_256_SHA256 "AES256-SHA256"
+# define TLS1_TXT_DH_DSS_WITH_AES_128_SHA256 "DH-DSS-AES128-SHA256"
+# define TLS1_TXT_DH_RSA_WITH_AES_128_SHA256 "DH-RSA-AES128-SHA256"
+# define TLS1_TXT_DHE_DSS_WITH_AES_128_SHA256 "DHE-DSS-AES128-SHA256"
+# define TLS1_TXT_DHE_RSA_WITH_AES_128_SHA256 "DHE-RSA-AES128-SHA256"
+# define TLS1_TXT_DH_DSS_WITH_AES_256_SHA256 "DH-DSS-AES256-SHA256"
+# define TLS1_TXT_DH_RSA_WITH_AES_256_SHA256 "DH-RSA-AES256-SHA256"
+# define TLS1_TXT_DHE_DSS_WITH_AES_256_SHA256 "DHE-DSS-AES256-SHA256"
+# define TLS1_TXT_DHE_RSA_WITH_AES_256_SHA256 "DHE-RSA-AES256-SHA256"
+# define TLS1_TXT_ADH_WITH_AES_128_SHA256 "ADH-AES128-SHA256"
+# define TLS1_TXT_ADH_WITH_AES_256_SHA256 "ADH-AES256-SHA256"
+
+/* TLS v1.2 GCM ciphersuites from RFC5288 */
+# define TLS1_TXT_RSA_WITH_AES_128_GCM_SHA256 "AES128-GCM-SHA256"
+# define TLS1_TXT_RSA_WITH_AES_256_GCM_SHA384 "AES256-GCM-SHA384"
+# define TLS1_TXT_DHE_RSA_WITH_AES_128_GCM_SHA256 "DHE-RSA-AES128-GCM-SHA256"
+# define TLS1_TXT_DHE_RSA_WITH_AES_256_GCM_SHA384 "DHE-RSA-AES256-GCM-SHA384"
+# define TLS1_TXT_DH_RSA_WITH_AES_128_GCM_SHA256 "DH-RSA-AES128-GCM-SHA256"
+# define TLS1_TXT_DH_RSA_WITH_AES_256_GCM_SHA384 "DH-RSA-AES256-GCM-SHA384"
+# define TLS1_TXT_DHE_DSS_WITH_AES_128_GCM_SHA256 "DHE-DSS-AES128-GCM-SHA256"
+# define TLS1_TXT_DHE_DSS_WITH_AES_256_GCM_SHA384 "DHE-DSS-AES256-GCM-SHA384"
+# define TLS1_TXT_DH_DSS_WITH_AES_128_GCM_SHA256 "DH-DSS-AES128-GCM-SHA256"
+# define TLS1_TXT_DH_DSS_WITH_AES_256_GCM_SHA384 "DH-DSS-AES256-GCM-SHA384"
+# define TLS1_TXT_ADH_WITH_AES_128_GCM_SHA256 "ADH-AES128-GCM-SHA256"
+# define TLS1_TXT_ADH_WITH_AES_256_GCM_SHA384 "ADH-AES256-GCM-SHA384"
+
+/* CCM ciphersuites from RFC6655 */
+# define TLS1_TXT_RSA_WITH_AES_128_CCM "AES128-CCM"
+# define TLS1_TXT_RSA_WITH_AES_256_CCM "AES256-CCM"
+# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM "DHE-RSA-AES128-CCM"
+# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM "DHE-RSA-AES256-CCM"
+
+# define TLS1_TXT_RSA_WITH_AES_128_CCM_8 "AES128-CCM8"
+# define TLS1_TXT_RSA_WITH_AES_256_CCM_8 "AES256-CCM8"
+# define TLS1_TXT_DHE_RSA_WITH_AES_128_CCM_8 "DHE-RSA-AES128-CCM8"
+# define TLS1_TXT_DHE_RSA_WITH_AES_256_CCM_8 "DHE-RSA-AES256-CCM8"
+
+# define TLS1_TXT_PSK_WITH_AES_128_CCM "PSK-AES128-CCM"
+# define TLS1_TXT_PSK_WITH_AES_256_CCM "PSK-AES256-CCM"
+# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM "DHE-PSK-AES128-CCM"
+# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM "DHE-PSK-AES256-CCM"
+
+# define TLS1_TXT_PSK_WITH_AES_128_CCM_8 "PSK-AES128-CCM8"
+# define TLS1_TXT_PSK_WITH_AES_256_CCM_8 "PSK-AES256-CCM8"
+# define TLS1_TXT_DHE_PSK_WITH_AES_128_CCM_8 "DHE-PSK-AES128-CCM8"
+# define TLS1_TXT_DHE_PSK_WITH_AES_256_CCM_8 "DHE-PSK-AES256-CCM8"
+
+/* CCM ciphersuites from RFC7251 */
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM "ECDHE-ECDSA-AES128-CCM"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM "ECDHE-ECDSA-AES256-CCM"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_CCM_8 "ECDHE-ECDSA-AES128-CCM8"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_CCM_8 "ECDHE-ECDSA-AES256-CCM8"
+
+/* ECDH HMAC based ciphersuites from RFC5289 */
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_SHA256 "ECDHE-ECDSA-AES128-SHA256"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_SHA384 "ECDHE-ECDSA-AES256-SHA384"
+# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_SHA256 "ECDH-ECDSA-AES128-SHA256"
+# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_SHA384 "ECDH-ECDSA-AES256-SHA384"
+# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_SHA256 "ECDHE-RSA-AES128-SHA256"
+# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_SHA384 "ECDHE-RSA-AES256-SHA384"
+# define TLS1_TXT_ECDH_RSA_WITH_AES_128_SHA256 "ECDH-RSA-AES128-SHA256"
+# define TLS1_TXT_ECDH_RSA_WITH_AES_256_SHA384 "ECDH-RSA-AES256-SHA384"
+
+/* ECDH GCM based ciphersuites from RFC5289 */
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 "ECDHE-ECDSA-AES128-GCM-SHA256"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 "ECDHE-ECDSA-AES256-GCM-SHA384"
+# define TLS1_TXT_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 "ECDH-ECDSA-AES128-GCM-SHA256"
+# define TLS1_TXT_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 "ECDH-ECDSA-AES256-GCM-SHA384"
+# define TLS1_TXT_ECDHE_RSA_WITH_AES_128_GCM_SHA256 "ECDHE-RSA-AES128-GCM-SHA256"
+# define TLS1_TXT_ECDHE_RSA_WITH_AES_256_GCM_SHA384 "ECDHE-RSA-AES256-GCM-SHA384"
+# define TLS1_TXT_ECDH_RSA_WITH_AES_128_GCM_SHA256 "ECDH-RSA-AES128-GCM-SHA256"
+# define TLS1_TXT_ECDH_RSA_WITH_AES_256_GCM_SHA384 "ECDH-RSA-AES256-GCM-SHA384"
+
+/* TLS v1.2 PSK GCM ciphersuites from RFC5487 */
+# define TLS1_TXT_PSK_WITH_AES_128_GCM_SHA256 "PSK-AES128-GCM-SHA256"
+# define TLS1_TXT_PSK_WITH_AES_256_GCM_SHA384 "PSK-AES256-GCM-SHA384"
+
+/* ECDHE PSK ciphersuites from RFC 5489 */
+# define TLS1_TXT_ECDHE_PSK_WITH_RC4_128_SHA "ECDHE-PSK-RC4-SHA"
+# define TLS1_TXT_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA "ECDHE-PSK-3DES-EDE-CBC-SHA"
+# define TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA "ECDHE-PSK-AES128-CBC-SHA"
+# define TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA "ECDHE-PSK-AES256-CBC-SHA"
+
+# define TLS1_TXT_ECDHE_PSK_WITH_AES_128_CBC_SHA256 "ECDHE-PSK-AES128-CBC-SHA256"
+# define TLS1_TXT_ECDHE_PSK_WITH_AES_256_CBC_SHA384 "ECDHE-PSK-AES256-CBC-SHA384"
+
+# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA "ECDHE-PSK-NULL-SHA"
+# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA256 "ECDHE-PSK-NULL-SHA256"
+# define TLS1_TXT_ECDHE_PSK_WITH_NULL_SHA384 "ECDHE-PSK-NULL-SHA384"
+
+/* Camellia-CBC ciphersuites from RFC6367 */
+# define TLS1_TXT_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-ECDSA-CAMELLIA128-SHA256"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-ECDSA-CAMELLIA256-SHA384"
+# define TLS1_TXT_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDH-ECDSA-CAMELLIA128-SHA256"
+# define TLS1_TXT_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDH-ECDSA-CAMELLIA256-SHA384"
+# define TLS1_TXT_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDHE-RSA-CAMELLIA128-SHA256"
+# define TLS1_TXT_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDHE-RSA-CAMELLIA256-SHA384"
+# define TLS1_TXT_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 "ECDH-RSA-CAMELLIA128-SHA256"
+# define TLS1_TXT_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 "ECDH-RSA-CAMELLIA256-SHA384"
+
+/* draft-ietf-tls-chacha20-poly1305-03 */
+# define TLS1_TXT_ECDHE_RSA_WITH_CHACHA20_POLY1305 "ECDHE-RSA-CHACHA20-POLY1305"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_CHACHA20_POLY1305 "ECDHE-ECDSA-CHACHA20-POLY1305"
+# define TLS1_TXT_DHE_RSA_WITH_CHACHA20_POLY1305 "DHE-RSA-CHACHA20-POLY1305"
+# define TLS1_TXT_PSK_WITH_CHACHA20_POLY1305 "PSK-CHACHA20-POLY1305"
+# define TLS1_TXT_ECDHE_PSK_WITH_CHACHA20_POLY1305 "ECDHE-PSK-CHACHA20-POLY1305"
+# define TLS1_TXT_DHE_PSK_WITH_CHACHA20_POLY1305 "DHE-PSK-CHACHA20-POLY1305"
+# define TLS1_TXT_RSA_PSK_WITH_CHACHA20_POLY1305 "RSA-PSK-CHACHA20-POLY1305"
+
+/* Aria ciphersuites from RFC6209 */
+# define TLS1_TXT_RSA_WITH_ARIA_128_GCM_SHA256 "ARIA128-GCM-SHA256"
+# define TLS1_TXT_RSA_WITH_ARIA_256_GCM_SHA384 "ARIA256-GCM-SHA384"
+# define TLS1_TXT_DHE_RSA_WITH_ARIA_128_GCM_SHA256 "DHE-RSA-ARIA128-GCM-SHA256"
+# define TLS1_TXT_DHE_RSA_WITH_ARIA_256_GCM_SHA384 "DHE-RSA-ARIA256-GCM-SHA384"
+# define TLS1_TXT_DH_RSA_WITH_ARIA_128_GCM_SHA256 "DH-RSA-ARIA128-GCM-SHA256"
+# define TLS1_TXT_DH_RSA_WITH_ARIA_256_GCM_SHA384 "DH-RSA-ARIA256-GCM-SHA384"
+# define TLS1_TXT_DHE_DSS_WITH_ARIA_128_GCM_SHA256 "DHE-DSS-ARIA128-GCM-SHA256"
+# define TLS1_TXT_DHE_DSS_WITH_ARIA_256_GCM_SHA384 "DHE-DSS-ARIA256-GCM-SHA384"
+# define TLS1_TXT_DH_DSS_WITH_ARIA_128_GCM_SHA256 "DH-DSS-ARIA128-GCM-SHA256"
+# define TLS1_TXT_DH_DSS_WITH_ARIA_256_GCM_SHA384 "DH-DSS-ARIA256-GCM-SHA384"
+# define TLS1_TXT_DH_anon_WITH_ARIA_128_GCM_SHA256 "ADH-ARIA128-GCM-SHA256"
+# define TLS1_TXT_DH_anon_WITH_ARIA_256_GCM_SHA384 "ADH-ARIA256-GCM-SHA384"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ECDSA-ARIA128-GCM-SHA256"
+# define TLS1_TXT_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ECDSA-ARIA256-GCM-SHA384"
+# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ECDSA-ARIA128-GCM-SHA256"
+# define TLS1_TXT_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ECDSA-ARIA256-GCM-SHA384"
+# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 "ECDHE-ARIA128-GCM-SHA256"
+# define TLS1_TXT_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 "ECDHE-ARIA256-GCM-SHA384"
+# define TLS1_TXT_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 "ECDH-ARIA128-GCM-SHA256"
+# define TLS1_TXT_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 "ECDH-ARIA256-GCM-SHA384"
+# define TLS1_TXT_PSK_WITH_ARIA_128_GCM_SHA256 "PSK-ARIA128-GCM-SHA256"
+# define TLS1_TXT_PSK_WITH_ARIA_256_GCM_SHA384 "PSK-ARIA256-GCM-SHA384"
+# define TLS1_TXT_DHE_PSK_WITH_ARIA_128_GCM_SHA256 "DHE-PSK-ARIA128-GCM-SHA256"
+# define TLS1_TXT_DHE_PSK_WITH_ARIA_256_GCM_SHA384 "DHE-PSK-ARIA256-GCM-SHA384"
+# define TLS1_TXT_RSA_PSK_WITH_ARIA_128_GCM_SHA256 "RSA-PSK-ARIA128-GCM-SHA256"
+# define TLS1_TXT_RSA_PSK_WITH_ARIA_256_GCM_SHA384 "RSA-PSK-ARIA256-GCM-SHA384"
+
+# define TLS_CT_RSA_SIGN 1
+# define TLS_CT_DSS_SIGN 2
+# define TLS_CT_RSA_FIXED_DH 3
+# define TLS_CT_DSS_FIXED_DH 4
+# define TLS_CT_ECDSA_SIGN 64
+# define TLS_CT_RSA_FIXED_ECDH 65
+# define TLS_CT_ECDSA_FIXED_ECDH 66
+# define TLS_CT_GOST01_SIGN 22
+# define TLS_CT_GOST12_IANA_SIGN 67
+# define TLS_CT_GOST12_IANA_512_SIGN 68
+# define TLS_CT_GOST12_LEGACY_SIGN 238
+# define TLS_CT_GOST12_LEGACY_512_SIGN 239
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define TLS_CT_GOST12_SIGN TLS_CT_GOST12_LEGACY_SIGN
+# define TLS_CT_GOST12_512_SIGN TLS_CT_GOST12_LEGACY_512_SIGN
+# endif
+
+/*
+ * when correcting this number, correct also SSL3_CT_NUMBER in ssl3.h (see
+ * comment there)
+ */
+# define TLS_CT_NUMBER 12
+
+# if defined(SSL3_CT_NUMBER)
+# if TLS_CT_NUMBER != SSL3_CT_NUMBER
+# error "SSL/TLS CT_NUMBER values do not match"
+# endif
+# endif
+
+# define TLS1_FINISH_MAC_LENGTH 12
+
+# define TLS_MD_MAX_CONST_SIZE 22
+# define TLS_MD_CLIENT_FINISH_CONST "client finished"
+# define TLS_MD_CLIENT_FINISH_CONST_SIZE 15
+# define TLS_MD_SERVER_FINISH_CONST "server finished"
+# define TLS_MD_SERVER_FINISH_CONST_SIZE 15
+# define TLS_MD_KEY_EXPANSION_CONST "key expansion"
+# define TLS_MD_KEY_EXPANSION_CONST_SIZE 13
+# define TLS_MD_CLIENT_WRITE_KEY_CONST "client write key"
+# define TLS_MD_CLIENT_WRITE_KEY_CONST_SIZE 16
+# define TLS_MD_SERVER_WRITE_KEY_CONST "server write key"
+# define TLS_MD_SERVER_WRITE_KEY_CONST_SIZE 16
+# define TLS_MD_IV_BLOCK_CONST "IV block"
+# define TLS_MD_IV_BLOCK_CONST_SIZE 8
+# define TLS_MD_MASTER_SECRET_CONST "master secret"
+# define TLS_MD_MASTER_SECRET_CONST_SIZE 13
+# define TLS_MD_EXTENDED_MASTER_SECRET_CONST "extended master secret"
+# define TLS_MD_EXTENDED_MASTER_SECRET_CONST_SIZE 22
+
+# ifdef CHARSET_EBCDIC
+# undef TLS_MD_CLIENT_FINISH_CONST
+/*
+ * client finished
+ */
+# define TLS_MD_CLIENT_FINISH_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x66\x69\x6e\x69\x73\x68\x65\x64"
+
+# undef TLS_MD_SERVER_FINISH_CONST
+/*
+ * server finished
+ */
+# define TLS_MD_SERVER_FINISH_CONST "\x73\x65\x72\x76\x65\x72\x20\x66\x69\x6e\x69\x73\x68\x65\x64"
+
+# undef TLS_MD_SERVER_WRITE_KEY_CONST
+/*
+ * server write key
+ */
+# define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79"
+
+# undef TLS_MD_KEY_EXPANSION_CONST
+/*
+ * key expansion
+ */
+# define TLS_MD_KEY_EXPANSION_CONST "\x6b\x65\x79\x20\x65\x78\x70\x61\x6e\x73\x69\x6f\x6e"
+
+# undef TLS_MD_CLIENT_WRITE_KEY_CONST
+/*
+ * client write key
+ */
+# define TLS_MD_CLIENT_WRITE_KEY_CONST "\x63\x6c\x69\x65\x6e\x74\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79"
+
+# undef TLS_MD_SERVER_WRITE_KEY_CONST
+/*
+ * server write key
+ */
+# define TLS_MD_SERVER_WRITE_KEY_CONST "\x73\x65\x72\x76\x65\x72\x20\x77\x72\x69\x74\x65\x20\x6b\x65\x79"
+
+# undef TLS_MD_IV_BLOCK_CONST
+/*
+ * IV block
+ */
+# define TLS_MD_IV_BLOCK_CONST "\x49\x56\x20\x62\x6c\x6f\x63\x6b"
+
+# undef TLS_MD_MASTER_SECRET_CONST
+/*
+ * master secret
+ */
+# define TLS_MD_MASTER_SECRET_CONST "\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74"
+# undef TLS_MD_EXTENDED_MASTER_SECRET_CONST
+/*
+ * extended master secret
+ */
+# define TLS_MD_EXTENDED_MASTER_SECRET_CONST "\x65\x78\x74\x65\x6e\x64\x65\x64\x20\x6d\x61\x73\x74\x65\x72\x20\x73\x65\x63\x72\x65\x74"
+# endif
+
+/* TLS Session Ticket extension struct */
+struct tls_session_ticket_ext_st {
+ unsigned short length;
+ void *data;
+};
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/trace.h b/include/openssl/trace.h
new file mode 100644
index 00000000..28200133
--- /dev/null
+++ b/include/openssl/trace.h
@@ -0,0 +1,312 @@
+/*
+ * Copyright 2019-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_TRACE_H
+# define OPENSSL_TRACE_H
+# pragma once
+
+# include <stdarg.h>
+
+# include <openssl/bio.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * TRACE CATEGORIES
+ */
+
+/*
+ * The trace messages of the OpenSSL libraries are organized into different
+ * categories. For every trace category, the application can register a separate
+ * tracer callback. When a callback is registered, a so called trace channel is
+ * created for this category. This channel consists essentially of an internal
+ * BIO which sends all trace output it receives to the registered application
+ * callback.
+ *
+ * The ALL category can be used as a fallback category to register a single
+ * channel which receives the output from all categories. However, if the
+ * application intends to print the trace channel name in the line prefix,
+ * it is better to register channels for all categories separately.
+ * (This is how the openssl application does it.)
+ */
+# define OSSL_TRACE_CATEGORY_ALL 0 /* The fallback */
+# define OSSL_TRACE_CATEGORY_TRACE 1
+# define OSSL_TRACE_CATEGORY_INIT 2
+# define OSSL_TRACE_CATEGORY_TLS 3
+# define OSSL_TRACE_CATEGORY_TLS_CIPHER 4
+# define OSSL_TRACE_CATEGORY_CONF 5
+# ifndef OPENSSL_NO_ENGINE
+# define OSSL_TRACE_CATEGORY_ENGINE_TABLE 6
+# define OSSL_TRACE_CATEGORY_ENGINE_REF_COUNT 7
+# endif
+# define OSSL_TRACE_CATEGORY_PKCS5V2 8
+# define OSSL_TRACE_CATEGORY_PKCS12_KEYGEN 9
+# define OSSL_TRACE_CATEGORY_PKCS12_DECRYPT 10
+# define OSSL_TRACE_CATEGORY_X509V3_POLICY 11
+# define OSSL_TRACE_CATEGORY_BN_CTX 12
+# define OSSL_TRACE_CATEGORY_CMP 13
+# define OSSL_TRACE_CATEGORY_STORE 14
+# define OSSL_TRACE_CATEGORY_DECODER 15
+# define OSSL_TRACE_CATEGORY_ENCODER 16
+# define OSSL_TRACE_CATEGORY_REF_COUNT 17
+/* Count of available categories. */
+# define OSSL_TRACE_CATEGORY_NUM 18
+
+/* Returns the trace category number for the given |name| */
+int OSSL_trace_get_category_num(const char *name);
+
+/* Returns the trace category name for the given |num| */
+const char *OSSL_trace_get_category_name(int num);
+
+/*
+ * TRACE CONSUMERS
+ */
+
+/*
+ * Enables tracing for the given |category| by providing a BIO sink
+ * as |channel|. If a null pointer is passed as |channel|, an existing
+ * trace channel is removed and tracing for the category is disabled.
+ *
+ * Returns 1 on success and 0 on failure
+ */
+int OSSL_trace_set_channel(int category, BIO* channel);
+
+/*
+ * Attach a prefix and a suffix to the given |category|, to be printed at the
+ * beginning and at the end of each trace output group, i.e. when
+ * OSSL_trace_begin() and OSSL_trace_end() are called.
+ * If a null pointer is passed as argument, the existing prefix or suffix is
+ * removed.
+ *
+ * They return 1 on success and 0 on failure
+ */
+int OSSL_trace_set_prefix(int category, const char *prefix);
+int OSSL_trace_set_suffix(int category, const char *suffix);
+
+/*
+ * OSSL_trace_cb is the type tracing callback provided by the application.
+ * It MUST return the number of bytes written, or 0 on error (in other words,
+ * it can never write zero bytes).
+ *
+ * The |buffer| will always contain text, which may consist of several lines.
+ * The |data| argument points to whatever data was provided by the application
+ * when registering the tracer function.
+ *
+ * The |category| number is given, as well as a |cmd| number, described below.
+ */
+typedef size_t (*OSSL_trace_cb)(const char *buffer, size_t count,
+ int category, int cmd, void *data);
+/*
+ * Possible |cmd| numbers.
+ */
+# define OSSL_TRACE_CTRL_BEGIN 0
+# define OSSL_TRACE_CTRL_WRITE 1
+# define OSSL_TRACE_CTRL_END 2
+
+/*
+ * Enables tracing for the given |category| by creating an internal
+ * trace channel which sends the output to the given |callback|.
+ * If a null pointer is passed as callback, an existing trace channel
+ * is removed and tracing for the category is disabled.
+ *
+ * NOTE: OSSL_trace_set_channel() and OSSL_trace_set_callback() are mutually
+ * exclusive.
+ *
+ * Returns 1 on success and 0 on failure
+ */
+int OSSL_trace_set_callback(int category, OSSL_trace_cb callback, void *data);
+
+/*
+ * TRACE PRODUCERS
+ */
+
+/*
+ * Returns 1 if tracing for the specified category is enabled, otherwise 0
+ */
+int OSSL_trace_enabled(int category);
+
+/*
+ * Wrap a group of tracing output calls. OSSL_trace_begin() locks tracing and
+ * returns the trace channel associated with the given category, or NULL if no
+ * channel is associated with the category. OSSL_trace_end() unlocks tracing.
+ *
+ * Usage:
+ *
+ * BIO *out;
+ * if ((out = OSSL_trace_begin(category)) != NULL) {
+ * ...
+ * BIO_fprintf(out, ...);
+ * ...
+ * OSSL_trace_end(category, out);
+ * }
+ *
+ * See also the convenience macros OSSL_TRACE_BEGIN and OSSL_TRACE_END below.
+ */
+BIO *OSSL_trace_begin(int category);
+void OSSL_trace_end(int category, BIO *channel);
+
+/*
+ * OSSL_TRACE* Convenience Macros
+ */
+
+/*
+ * When the tracing feature is disabled, these macros are defined to
+ * produce dead code, which a good compiler should eliminate.
+ */
+
+/*
+ * OSSL_TRACE_BEGIN, OSSL_TRACE_END - Define a Trace Group
+ *
+ * These two macros can be used to create a block which is executed only
+ * if the corresponding trace category is enabled. Inside this block, a
+ * local variable named |trc_out| is defined, which points to the channel
+ * associated with the given trace category.
+ *
+ * Usage: (using 'TLS' as an example category)
+ *
+ * OSSL_TRACE_BEGIN(TLS) {
+ *
+ * BIO_fprintf(trc_out, ... );
+ *
+ * } OSSL_TRACE_END(TLS);
+ *
+ *
+ * This expands to the following code
+ *
+ * do {
+ * BIO *trc_out = OSSL_trace_begin(OSSL_TRACE_CATEGORY_TLS);
+ * if (trc_out != NULL) {
+ * ...
+ * BIO_fprintf(trc_out, ...);
+ * }
+ * OSSL_trace_end(OSSL_TRACE_CATEGORY_TLS, trc_out);
+ * } while (0);
+ *
+ * The use of the inner '{...}' group and the trailing ';' is enforced
+ * by the definition of the macros in order to make the code look as much
+ * like C code as possible.
+ *
+ * Before returning from inside the trace block, it is necessary to
+ * call OSSL_TRACE_CANCEL(category).
+ */
+
+# if !defined OPENSSL_NO_TRACE && !defined FIPS_MODULE
+
+# define OSSL_TRACE_BEGIN(category) \
+ do { \
+ BIO *trc_out = OSSL_trace_begin(OSSL_TRACE_CATEGORY_##category); \
+ \
+ if (trc_out != NULL)
+
+# define OSSL_TRACE_END(category) \
+ OSSL_trace_end(OSSL_TRACE_CATEGORY_##category, trc_out); \
+ } while (0)
+
+# define OSSL_TRACE_CANCEL(category) \
+ OSSL_trace_end(OSSL_TRACE_CATEGORY_##category, trc_out) \
+
+# else
+
+# define OSSL_TRACE_BEGIN(category) \
+ do { \
+ BIO *trc_out = NULL; \
+ if (0)
+
+# define OSSL_TRACE_END(category) \
+ } while(0)
+
+# define OSSL_TRACE_CANCEL(category) \
+ ((void)0)
+
+# endif
+
+/*
+ * OSSL_TRACE_ENABLED() - Check whether tracing is enabled for |category|
+ *
+ * Usage:
+ *
+ * if (OSSL_TRACE_ENABLED(TLS)) {
+ * ...
+ * }
+ */
+# if !defined OPENSSL_NO_TRACE && !defined FIPS_MODULE
+
+# define OSSL_TRACE_ENABLED(category) \
+ OSSL_trace_enabled(OSSL_TRACE_CATEGORY_##category)
+
+# else
+
+# define OSSL_TRACE_ENABLED(category) (0)
+
+# endif
+
+/*
+ * OSSL_TRACE*() - OneShot Trace Macros
+ *
+ * These macros are intended to produce a simple printf-style trace output.
+ * Unfortunately, C90 macros don't support variable arguments, so the
+ * "vararg" OSSL_TRACEV() macro has a rather weird usage pattern:
+ *
+ * OSSL_TRACEV(category, (trc_out, "format string", ...args...));
+ *
+ * Where 'channel' is the literal symbol of this name, not a variable.
+ * For that reason, it is currently not intended to be used directly,
+ * but only as helper macro for the other oneshot trace macros
+ * OSSL_TRACE(), OSSL_TRACE1(), OSSL_TRACE2(), ...
+ *
+ * Usage:
+ *
+ * OSSL_TRACE(INIT, "Hello world!\n");
+ * OSSL_TRACE1(TLS, "The answer is %d\n", 42);
+ * OSSL_TRACE2(TLS, "The ultimate question to answer %d is '%s'\n",
+ * 42, "What do you get when you multiply six by nine?");
+ */
+
+# if !defined OPENSSL_NO_TRACE && !defined FIPS_MODULE
+
+# define OSSL_TRACEV(category, args) \
+ OSSL_TRACE_BEGIN(category) \
+ BIO_printf args; \
+ OSSL_TRACE_END(category)
+
+# else
+
+# define OSSL_TRACEV(category, args) ((void)0)
+
+# endif
+
+# define OSSL_TRACE(category, text) \
+ OSSL_TRACEV(category, (trc_out, "%s", text))
+
+# define OSSL_TRACE1(category, format, arg1) \
+ OSSL_TRACEV(category, (trc_out, format, arg1))
+# define OSSL_TRACE2(category, format, arg1, arg2) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2))
+# define OSSL_TRACE3(category, format, arg1, arg2, arg3) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2, arg3))
+# define OSSL_TRACE4(category, format, arg1, arg2, arg3, arg4) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2, arg3, arg4))
+# define OSSL_TRACE5(category, format, arg1, arg2, arg3, arg4, arg5) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2, arg3, arg4, arg5))
+# define OSSL_TRACE6(category, format, arg1, arg2, arg3, arg4, arg5, arg6) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2, arg3, arg4, arg5, arg6))
+# define OSSL_TRACE7(category, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7))
+# define OSSL_TRACE8(category, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8))
+# define OSSL_TRACE9(category, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) \
+ OSSL_TRACEV(category, (trc_out, format, arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9))
+
+# ifdef __cplusplus
+}
+# endif
+
+#endif
diff --git a/include/openssl/ts.h b/include/openssl/ts.h
new file mode 100644
index 00000000..5136e4e9
--- /dev/null
+++ b/include/openssl/ts.h
@@ -0,0 +1,503 @@
+/*
+ * Copyright 2006-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_TS_H
+# define OPENSSL_TS_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_TS_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_TS
+# include <openssl/symhacks.h>
+# include <openssl/buffer.h>
+# include <openssl/evp.h>
+# include <openssl/bio.h>
+# include <openssl/asn1.h>
+# include <openssl/safestack.h>
+# include <openssl/rsa.h>
+# include <openssl/dsa.h>
+# include <openssl/dh.h>
+# include <openssl/tserr.h>
+# include <openssl/ess.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# include <openssl/x509.h>
+# include <openssl/x509v3.h>
+
+typedef struct TS_msg_imprint_st TS_MSG_IMPRINT;
+typedef struct TS_req_st TS_REQ;
+typedef struct TS_accuracy_st TS_ACCURACY;
+typedef struct TS_tst_info_st TS_TST_INFO;
+
+/* Possible values for status. */
+# define TS_STATUS_GRANTED 0
+# define TS_STATUS_GRANTED_WITH_MODS 1
+# define TS_STATUS_REJECTION 2
+# define TS_STATUS_WAITING 3
+# define TS_STATUS_REVOCATION_WARNING 4
+# define TS_STATUS_REVOCATION_NOTIFICATION 5
+
+/* Possible values for failure_info. */
+# define TS_INFO_BAD_ALG 0
+# define TS_INFO_BAD_REQUEST 2
+# define TS_INFO_BAD_DATA_FORMAT 5
+# define TS_INFO_TIME_NOT_AVAILABLE 14
+# define TS_INFO_UNACCEPTED_POLICY 15
+# define TS_INFO_UNACCEPTED_EXTENSION 16
+# define TS_INFO_ADD_INFO_NOT_AVAILABLE 17
+# define TS_INFO_SYSTEM_FAILURE 25
+
+
+typedef struct TS_status_info_st TS_STATUS_INFO;
+
+typedef struct TS_resp_st TS_RESP;
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TS_REQ)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(TS_REQ, TS_REQ)
+DECLARE_ASN1_DUP_FUNCTION(TS_REQ)
+
+#ifndef OPENSSL_NO_STDIO
+TS_REQ *d2i_TS_REQ_fp(FILE *fp, TS_REQ **a);
+int i2d_TS_REQ_fp(FILE *fp, const TS_REQ *a);
+#endif
+TS_REQ *d2i_TS_REQ_bio(BIO *fp, TS_REQ **a);
+int i2d_TS_REQ_bio(BIO *fp, const TS_REQ *a);
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TS_MSG_IMPRINT)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(TS_MSG_IMPRINT, TS_MSG_IMPRINT)
+DECLARE_ASN1_DUP_FUNCTION(TS_MSG_IMPRINT)
+
+#ifndef OPENSSL_NO_STDIO
+TS_MSG_IMPRINT *d2i_TS_MSG_IMPRINT_fp(FILE *fp, TS_MSG_IMPRINT **a);
+int i2d_TS_MSG_IMPRINT_fp(FILE *fp, const TS_MSG_IMPRINT *a);
+#endif
+TS_MSG_IMPRINT *d2i_TS_MSG_IMPRINT_bio(BIO *bio, TS_MSG_IMPRINT **a);
+int i2d_TS_MSG_IMPRINT_bio(BIO *bio, const TS_MSG_IMPRINT *a);
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TS_RESP)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(TS_RESP, TS_RESP)
+DECLARE_ASN1_DUP_FUNCTION(TS_RESP)
+
+#ifndef OPENSSL_NO_STDIO
+TS_RESP *d2i_TS_RESP_fp(FILE *fp, TS_RESP **a);
+int i2d_TS_RESP_fp(FILE *fp, const TS_RESP *a);
+#endif
+TS_RESP *d2i_TS_RESP_bio(BIO *bio, TS_RESP **a);
+int i2d_TS_RESP_bio(BIO *bio, const TS_RESP *a);
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TS_STATUS_INFO)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(TS_STATUS_INFO, TS_STATUS_INFO)
+DECLARE_ASN1_DUP_FUNCTION(TS_STATUS_INFO)
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TS_TST_INFO)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(TS_TST_INFO, TS_TST_INFO)
+DECLARE_ASN1_DUP_FUNCTION(TS_TST_INFO)
+TS_TST_INFO *PKCS7_to_TS_TST_INFO(PKCS7 *token);
+
+#ifndef OPENSSL_NO_STDIO
+TS_TST_INFO *d2i_TS_TST_INFO_fp(FILE *fp, TS_TST_INFO **a);
+int i2d_TS_TST_INFO_fp(FILE *fp, const TS_TST_INFO *a);
+#endif
+TS_TST_INFO *d2i_TS_TST_INFO_bio(BIO *bio, TS_TST_INFO **a);
+int i2d_TS_TST_INFO_bio(BIO *bio, const TS_TST_INFO *a);
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TS_ACCURACY)
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(TS_ACCURACY, TS_ACCURACY)
+DECLARE_ASN1_DUP_FUNCTION(TS_ACCURACY)
+
+int TS_REQ_set_version(TS_REQ *a, long version);
+long TS_REQ_get_version(const TS_REQ *a);
+
+int TS_STATUS_INFO_set_status(TS_STATUS_INFO *a, int i);
+const ASN1_INTEGER *TS_STATUS_INFO_get0_status(const TS_STATUS_INFO *a);
+
+const STACK_OF(ASN1_UTF8STRING) *
+TS_STATUS_INFO_get0_text(const TS_STATUS_INFO *a);
+
+const ASN1_BIT_STRING *
+TS_STATUS_INFO_get0_failure_info(const TS_STATUS_INFO *a);
+
+int TS_REQ_set_msg_imprint(TS_REQ *a, TS_MSG_IMPRINT *msg_imprint);
+TS_MSG_IMPRINT *TS_REQ_get_msg_imprint(TS_REQ *a);
+
+int TS_MSG_IMPRINT_set_algo(TS_MSG_IMPRINT *a, X509_ALGOR *alg);
+X509_ALGOR *TS_MSG_IMPRINT_get_algo(TS_MSG_IMPRINT *a);
+
+int TS_MSG_IMPRINT_set_msg(TS_MSG_IMPRINT *a, unsigned char *d, int len);
+ASN1_OCTET_STRING *TS_MSG_IMPRINT_get_msg(TS_MSG_IMPRINT *a);
+
+int TS_REQ_set_policy_id(TS_REQ *a, const ASN1_OBJECT *policy);
+ASN1_OBJECT *TS_REQ_get_policy_id(TS_REQ *a);
+
+int TS_REQ_set_nonce(TS_REQ *a, const ASN1_INTEGER *nonce);
+const ASN1_INTEGER *TS_REQ_get_nonce(const TS_REQ *a);
+
+int TS_REQ_set_cert_req(TS_REQ *a, int cert_req);
+int TS_REQ_get_cert_req(const TS_REQ *a);
+
+STACK_OF(X509_EXTENSION) *TS_REQ_get_exts(TS_REQ *a);
+void TS_REQ_ext_free(TS_REQ *a);
+int TS_REQ_get_ext_count(TS_REQ *a);
+int TS_REQ_get_ext_by_NID(TS_REQ *a, int nid, int lastpos);
+int TS_REQ_get_ext_by_OBJ(TS_REQ *a, const ASN1_OBJECT *obj, int lastpos);
+int TS_REQ_get_ext_by_critical(TS_REQ *a, int crit, int lastpos);
+X509_EXTENSION *TS_REQ_get_ext(TS_REQ *a, int loc);
+X509_EXTENSION *TS_REQ_delete_ext(TS_REQ *a, int loc);
+int TS_REQ_add_ext(TS_REQ *a, X509_EXTENSION *ex, int loc);
+void *TS_REQ_get_ext_d2i(TS_REQ *a, int nid, int *crit, int *idx);
+
+/* Function declarations for TS_REQ defined in ts/ts_req_print.c */
+
+int TS_REQ_print_bio(BIO *bio, TS_REQ *a);
+
+/* Function declarations for TS_RESP defined in ts/ts_resp_utils.c */
+
+int TS_RESP_set_status_info(TS_RESP *a, TS_STATUS_INFO *info);
+TS_STATUS_INFO *TS_RESP_get_status_info(TS_RESP *a);
+
+/* Caller loses ownership of PKCS7 and TS_TST_INFO objects. */
+void TS_RESP_set_tst_info(TS_RESP *a, PKCS7 *p7, TS_TST_INFO *tst_info);
+PKCS7 *TS_RESP_get_token(TS_RESP *a);
+TS_TST_INFO *TS_RESP_get_tst_info(TS_RESP *a);
+
+int TS_TST_INFO_set_version(TS_TST_INFO *a, long version);
+long TS_TST_INFO_get_version(const TS_TST_INFO *a);
+
+int TS_TST_INFO_set_policy_id(TS_TST_INFO *a, ASN1_OBJECT *policy_id);
+ASN1_OBJECT *TS_TST_INFO_get_policy_id(TS_TST_INFO *a);
+
+int TS_TST_INFO_set_msg_imprint(TS_TST_INFO *a, TS_MSG_IMPRINT *msg_imprint);
+TS_MSG_IMPRINT *TS_TST_INFO_get_msg_imprint(TS_TST_INFO *a);
+
+int TS_TST_INFO_set_serial(TS_TST_INFO *a, const ASN1_INTEGER *serial);
+const ASN1_INTEGER *TS_TST_INFO_get_serial(const TS_TST_INFO *a);
+
+int TS_TST_INFO_set_time(TS_TST_INFO *a, const ASN1_GENERALIZEDTIME *gtime);
+const ASN1_GENERALIZEDTIME *TS_TST_INFO_get_time(const TS_TST_INFO *a);
+
+int TS_TST_INFO_set_accuracy(TS_TST_INFO *a, TS_ACCURACY *accuracy);
+TS_ACCURACY *TS_TST_INFO_get_accuracy(TS_TST_INFO *a);
+
+int TS_ACCURACY_set_seconds(TS_ACCURACY *a, const ASN1_INTEGER *seconds);
+const ASN1_INTEGER *TS_ACCURACY_get_seconds(const TS_ACCURACY *a);
+
+int TS_ACCURACY_set_millis(TS_ACCURACY *a, const ASN1_INTEGER *millis);
+const ASN1_INTEGER *TS_ACCURACY_get_millis(const TS_ACCURACY *a);
+
+int TS_ACCURACY_set_micros(TS_ACCURACY *a, const ASN1_INTEGER *micros);
+const ASN1_INTEGER *TS_ACCURACY_get_micros(const TS_ACCURACY *a);
+
+int TS_TST_INFO_set_ordering(TS_TST_INFO *a, int ordering);
+int TS_TST_INFO_get_ordering(const TS_TST_INFO *a);
+
+int TS_TST_INFO_set_nonce(TS_TST_INFO *a, const ASN1_INTEGER *nonce);
+const ASN1_INTEGER *TS_TST_INFO_get_nonce(const TS_TST_INFO *a);
+
+int TS_TST_INFO_set_tsa(TS_TST_INFO *a, GENERAL_NAME *tsa);
+GENERAL_NAME *TS_TST_INFO_get_tsa(TS_TST_INFO *a);
+
+STACK_OF(X509_EXTENSION) *TS_TST_INFO_get_exts(TS_TST_INFO *a);
+void TS_TST_INFO_ext_free(TS_TST_INFO *a);
+int TS_TST_INFO_get_ext_count(TS_TST_INFO *a);
+int TS_TST_INFO_get_ext_by_NID(TS_TST_INFO *a, int nid, int lastpos);
+int TS_TST_INFO_get_ext_by_OBJ(TS_TST_INFO *a, const ASN1_OBJECT *obj,
+ int lastpos);
+int TS_TST_INFO_get_ext_by_critical(TS_TST_INFO *a, int crit, int lastpos);
+X509_EXTENSION *TS_TST_INFO_get_ext(TS_TST_INFO *a, int loc);
+X509_EXTENSION *TS_TST_INFO_delete_ext(TS_TST_INFO *a, int loc);
+int TS_TST_INFO_add_ext(TS_TST_INFO *a, X509_EXTENSION *ex, int loc);
+void *TS_TST_INFO_get_ext_d2i(TS_TST_INFO *a, int nid, int *crit, int *idx);
+
+/*
+ * Declarations related to response generation, defined in ts/ts_resp_sign.c.
+ */
+
+/* Optional flags for response generation. */
+
+/* Don't include the TSA name in response. */
+# define TS_TSA_NAME 0x01
+
+/* Set ordering to true in response. */
+# define TS_ORDERING 0x02
+
+/*
+ * Include the signer certificate and the other specified certificates in
+ * the ESS signing certificate attribute beside the PKCS7 signed data.
+ * Only the signer certificates is included by default.
+ */
+# define TS_ESS_CERT_ID_CHAIN 0x04
+
+/* Forward declaration. */
+struct TS_resp_ctx;
+
+/* This must return a unique number less than 160 bits long. */
+typedef ASN1_INTEGER *(*TS_serial_cb) (struct TS_resp_ctx *, void *);
+
+/*
+ * This must return the seconds and microseconds since Jan 1, 1970 in the sec
+ * and usec variables allocated by the caller. Return non-zero for success
+ * and zero for failure.
+ */
+typedef int (*TS_time_cb) (struct TS_resp_ctx *, void *, long *sec,
+ long *usec);
+
+/*
+ * This must process the given extension. It can modify the TS_TST_INFO
+ * object of the context. Return values: !0 (processed), 0 (error, it must
+ * set the status info/failure info of the response).
+ */
+typedef int (*TS_extension_cb) (struct TS_resp_ctx *, X509_EXTENSION *,
+ void *);
+
+typedef struct TS_resp_ctx TS_RESP_CTX;
+
+/* Creates a response context that can be used for generating responses. */
+TS_RESP_CTX *TS_RESP_CTX_new(void);
+TS_RESP_CTX *TS_RESP_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+void TS_RESP_CTX_free(TS_RESP_CTX *ctx);
+
+/* This parameter must be set. */
+int TS_RESP_CTX_set_signer_cert(TS_RESP_CTX *ctx, X509 *signer);
+
+/* This parameter must be set. */
+int TS_RESP_CTX_set_signer_key(TS_RESP_CTX *ctx, EVP_PKEY *key);
+
+int TS_RESP_CTX_set_signer_digest(TS_RESP_CTX *ctx,
+ const EVP_MD *signer_digest);
+int TS_RESP_CTX_set_ess_cert_id_digest(TS_RESP_CTX *ctx, const EVP_MD *md);
+
+/* This parameter must be set. */
+int TS_RESP_CTX_set_def_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *def_policy);
+
+/* No additional certs are included in the response by default. */
+int TS_RESP_CTX_set_certs(TS_RESP_CTX *ctx, STACK_OF(X509) *certs);
+
+/*
+ * Adds a new acceptable policy, only the default policy is accepted by
+ * default.
+ */
+int TS_RESP_CTX_add_policy(TS_RESP_CTX *ctx, const ASN1_OBJECT *policy);
+
+/*
+ * Adds a new acceptable message digest. Note that no message digests are
+ * accepted by default. The md argument is shared with the caller.
+ */
+int TS_RESP_CTX_add_md(TS_RESP_CTX *ctx, const EVP_MD *md);
+
+/* Accuracy is not included by default. */
+int TS_RESP_CTX_set_accuracy(TS_RESP_CTX *ctx,
+ int secs, int millis, int micros);
+
+/*
+ * Clock precision digits, i.e. the number of decimal digits: '0' means sec,
+ * '3' msec, '6' usec, and so on. Default is 0.
+ */
+int TS_RESP_CTX_set_clock_precision_digits(TS_RESP_CTX *ctx,
+ unsigned clock_precision_digits);
+/* At most we accept usec precision. */
+# define TS_MAX_CLOCK_PRECISION_DIGITS 6
+
+/* Maximum status message length */
+# define TS_MAX_STATUS_LENGTH (1024 * 1024)
+
+/* No flags are set by default. */
+void TS_RESP_CTX_add_flags(TS_RESP_CTX *ctx, int flags);
+
+/* Default callback always returns a constant. */
+void TS_RESP_CTX_set_serial_cb(TS_RESP_CTX *ctx, TS_serial_cb cb, void *data);
+
+/* Default callback uses the gettimeofday() and gmtime() system calls. */
+void TS_RESP_CTX_set_time_cb(TS_RESP_CTX *ctx, TS_time_cb cb, void *data);
+
+/*
+ * Default callback rejects all extensions. The extension callback is called
+ * when the TS_TST_INFO object is already set up and not signed yet.
+ */
+/* FIXME: extension handling is not tested yet. */
+void TS_RESP_CTX_set_extension_cb(TS_RESP_CTX *ctx,
+ TS_extension_cb cb, void *data);
+
+/* The following methods can be used in the callbacks. */
+int TS_RESP_CTX_set_status_info(TS_RESP_CTX *ctx,
+ int status, const char *text);
+
+/* Sets the status info only if it is still TS_STATUS_GRANTED. */
+int TS_RESP_CTX_set_status_info_cond(TS_RESP_CTX *ctx,
+ int status, const char *text);
+
+int TS_RESP_CTX_add_failure_info(TS_RESP_CTX *ctx, int failure);
+
+/* The get methods below can be used in the extension callback. */
+TS_REQ *TS_RESP_CTX_get_request(TS_RESP_CTX *ctx);
+
+TS_TST_INFO *TS_RESP_CTX_get_tst_info(TS_RESP_CTX *ctx);
+
+/*
+ * Creates the signed TS_TST_INFO and puts it in TS_RESP.
+ * In case of errors it sets the status info properly.
+ * Returns NULL only in case of memory allocation/fatal error.
+ */
+TS_RESP *TS_RESP_create_response(TS_RESP_CTX *ctx, BIO *req_bio);
+
+/*
+ * Declarations related to response verification,
+ * they are defined in ts/ts_resp_verify.c.
+ */
+
+int TS_RESP_verify_signature(PKCS7 *token, STACK_OF(X509) *certs,
+ X509_STORE *store, X509 **signer_out);
+
+/* Context structure for the generic verify method. */
+
+/* Verify the signer's certificate and the signature of the response. */
+# define TS_VFY_SIGNATURE (1u << 0)
+/* Verify the version number of the response. */
+# define TS_VFY_VERSION (1u << 1)
+/* Verify if the policy supplied by the user matches the policy of the TSA. */
+# define TS_VFY_POLICY (1u << 2)
+/*
+ * Verify the message imprint provided by the user. This flag should not be
+ * specified with TS_VFY_DATA.
+ */
+# define TS_VFY_IMPRINT (1u << 3)
+/*
+ * Verify the message imprint computed by the verify method from the user
+ * provided data and the MD algorithm of the response. This flag should not
+ * be specified with TS_VFY_IMPRINT.
+ */
+# define TS_VFY_DATA (1u << 4)
+/* Verify the nonce value. */
+# define TS_VFY_NONCE (1u << 5)
+/* Verify if the TSA name field matches the signer certificate. */
+# define TS_VFY_SIGNER (1u << 6)
+/* Verify if the TSA name field equals to the user provided name. */
+# define TS_VFY_TSA_NAME (1u << 7)
+
+/* You can use the following convenience constants. */
+# define TS_VFY_ALL_IMPRINT (TS_VFY_SIGNATURE \
+ | TS_VFY_VERSION \
+ | TS_VFY_POLICY \
+ | TS_VFY_IMPRINT \
+ | TS_VFY_NONCE \
+ | TS_VFY_SIGNER \
+ | TS_VFY_TSA_NAME)
+# define TS_VFY_ALL_DATA (TS_VFY_SIGNATURE \
+ | TS_VFY_VERSION \
+ | TS_VFY_POLICY \
+ | TS_VFY_DATA \
+ | TS_VFY_NONCE \
+ | TS_VFY_SIGNER \
+ | TS_VFY_TSA_NAME)
+
+typedef struct TS_verify_ctx TS_VERIFY_CTX;
+
+int TS_RESP_verify_response(TS_VERIFY_CTX *ctx, TS_RESP *response);
+int TS_RESP_verify_token(TS_VERIFY_CTX *ctx, PKCS7 *token);
+
+/*
+ * Declarations related to response verification context,
+ */
+TS_VERIFY_CTX *TS_VERIFY_CTX_new(void);
+void TS_VERIFY_CTX_init(TS_VERIFY_CTX *ctx);
+void TS_VERIFY_CTX_free(TS_VERIFY_CTX *ctx);
+void TS_VERIFY_CTX_cleanup(TS_VERIFY_CTX *ctx);
+int TS_VERIFY_CTX_set_flags(TS_VERIFY_CTX *ctx, int f);
+int TS_VERIFY_CTX_add_flags(TS_VERIFY_CTX *ctx, int f);
+BIO *TS_VERIFY_CTX_set_data(TS_VERIFY_CTX *ctx, BIO *b);
+unsigned char *TS_VERIFY_CTX_set_imprint(TS_VERIFY_CTX *ctx,
+ unsigned char *hexstr, long len);
+X509_STORE *TS_VERIFY_CTX_set_store(TS_VERIFY_CTX *ctx, X509_STORE *s);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define TS_VERIFY_CTS_set_certs(ctx, cert) TS_VERIFY_CTX_set_certs(ctx,cert)
+# endif
+STACK_OF(X509) *TS_VERIFY_CTX_set_certs(TS_VERIFY_CTX *ctx, STACK_OF(X509) *certs);
+
+/*-
+ * If ctx is NULL, it allocates and returns a new object, otherwise
+ * it returns ctx. It initialises all the members as follows:
+ * flags = TS_VFY_ALL_IMPRINT & ~(TS_VFY_TSA_NAME | TS_VFY_SIGNATURE)
+ * certs = NULL
+ * store = NULL
+ * policy = policy from the request or NULL if absent (in this case
+ * TS_VFY_POLICY is cleared from flags as well)
+ * md_alg = MD algorithm from request
+ * imprint, imprint_len = imprint from request
+ * data = NULL
+ * nonce, nonce_len = nonce from the request or NULL if absent (in this case
+ * TS_VFY_NONCE is cleared from flags as well)
+ * tsa_name = NULL
+ * Important: after calling this method TS_VFY_SIGNATURE should be added!
+ */
+TS_VERIFY_CTX *TS_REQ_to_TS_VERIFY_CTX(TS_REQ *req, TS_VERIFY_CTX *ctx);
+
+/* Function declarations for TS_RESP defined in ts/ts_resp_print.c */
+
+int TS_RESP_print_bio(BIO *bio, TS_RESP *a);
+int TS_STATUS_INFO_print_bio(BIO *bio, TS_STATUS_INFO *a);
+int TS_TST_INFO_print_bio(BIO *bio, TS_TST_INFO *a);
+
+/* Common utility functions defined in ts/ts_lib.c */
+
+int TS_ASN1_INTEGER_print_bio(BIO *bio, const ASN1_INTEGER *num);
+int TS_OBJ_print_bio(BIO *bio, const ASN1_OBJECT *obj);
+int TS_ext_print_bio(BIO *bio, const STACK_OF(X509_EXTENSION) *extensions);
+int TS_X509_ALGOR_print_bio(BIO *bio, const X509_ALGOR *alg);
+int TS_MSG_IMPRINT_print_bio(BIO *bio, TS_MSG_IMPRINT *msg);
+
+/*
+ * Function declarations for handling configuration options, defined in
+ * ts/ts_conf.c
+ */
+
+X509 *TS_CONF_load_cert(const char *file);
+STACK_OF(X509) *TS_CONF_load_certs(const char *file);
+EVP_PKEY *TS_CONF_load_key(const char *file, const char *pass);
+const char *TS_CONF_get_tsa_section(CONF *conf, const char *section);
+int TS_CONF_set_serial(CONF *conf, const char *section, TS_serial_cb cb,
+ TS_RESP_CTX *ctx);
+#ifndef OPENSSL_NO_ENGINE
+int TS_CONF_set_crypto_device(CONF *conf, const char *section,
+ const char *device);
+int TS_CONF_set_default_engine(const char *name);
+#endif
+int TS_CONF_set_signer_cert(CONF *conf, const char *section,
+ const char *cert, TS_RESP_CTX *ctx);
+int TS_CONF_set_certs(CONF *conf, const char *section, const char *certs,
+ TS_RESP_CTX *ctx);
+int TS_CONF_set_signer_key(CONF *conf, const char *section,
+ const char *key, const char *pass,
+ TS_RESP_CTX *ctx);
+int TS_CONF_set_signer_digest(CONF *conf, const char *section,
+ const char *md, TS_RESP_CTX *ctx);
+int TS_CONF_set_def_policy(CONF *conf, const char *section,
+ const char *policy, TS_RESP_CTX *ctx);
+int TS_CONF_set_policies(CONF *conf, const char *section, TS_RESP_CTX *ctx);
+int TS_CONF_set_digests(CONF *conf, const char *section, TS_RESP_CTX *ctx);
+int TS_CONF_set_accuracy(CONF *conf, const char *section, TS_RESP_CTX *ctx);
+int TS_CONF_set_clock_precision_digits(const CONF *conf, const char *section,
+ TS_RESP_CTX *ctx);
+int TS_CONF_set_ordering(CONF *conf, const char *section, TS_RESP_CTX *ctx);
+int TS_CONF_set_tsa_name(CONF *conf, const char *section, TS_RESP_CTX *ctx);
+int TS_CONF_set_ess_cert_id_chain(CONF *conf, const char *section,
+ TS_RESP_CTX *ctx);
+int TS_CONF_set_ess_cert_id_digest(CONF *conf, const char *section,
+ TS_RESP_CTX *ctx);
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+#endif
diff --git a/include/openssl/tserr.h b/include/openssl/tserr.h
new file mode 100644
index 00000000..e1b943e4
--- /dev/null
+++ b/include/openssl/tserr.h
@@ -0,0 +1,67 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_TSERR_H
+# define OPENSSL_TSERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+# ifndef OPENSSL_NO_TS
+
+
+/*
+ * TS reason codes.
+ */
+# define TS_R_BAD_PKCS7_TYPE 132
+# define TS_R_BAD_TYPE 133
+# define TS_R_CANNOT_LOAD_CERT 137
+# define TS_R_CANNOT_LOAD_KEY 138
+# define TS_R_CERTIFICATE_VERIFY_ERROR 100
+# define TS_R_COULD_NOT_SET_ENGINE 127
+# define TS_R_COULD_NOT_SET_TIME 115
+# define TS_R_DETACHED_CONTENT 134
+# define TS_R_ESS_ADD_SIGNING_CERT_ERROR 116
+# define TS_R_ESS_ADD_SIGNING_CERT_V2_ERROR 139
+# define TS_R_ESS_SIGNING_CERTIFICATE_ERROR 101
+# define TS_R_INVALID_NULL_POINTER 102
+# define TS_R_INVALID_SIGNER_CERTIFICATE_PURPOSE 117
+# define TS_R_MESSAGE_IMPRINT_MISMATCH 103
+# define TS_R_NONCE_MISMATCH 104
+# define TS_R_NONCE_NOT_RETURNED 105
+# define TS_R_NO_CONTENT 106
+# define TS_R_NO_TIME_STAMP_TOKEN 107
+# define TS_R_PKCS7_ADD_SIGNATURE_ERROR 118
+# define TS_R_PKCS7_ADD_SIGNED_ATTR_ERROR 119
+# define TS_R_PKCS7_TO_TS_TST_INFO_FAILED 129
+# define TS_R_POLICY_MISMATCH 108
+# define TS_R_PRIVATE_KEY_DOES_NOT_MATCH_CERTIFICATE 120
+# define TS_R_RESPONSE_SETUP_ERROR 121
+# define TS_R_SIGNATURE_FAILURE 109
+# define TS_R_THERE_MUST_BE_ONE_SIGNER 110
+# define TS_R_TIME_SYSCALL_ERROR 122
+# define TS_R_TOKEN_NOT_PRESENT 130
+# define TS_R_TOKEN_PRESENT 131
+# define TS_R_TSA_NAME_MISMATCH 111
+# define TS_R_TSA_UNTRUSTED 112
+# define TS_R_TST_INFO_SETUP_ERROR 123
+# define TS_R_TS_DATASIGN 124
+# define TS_R_UNACCEPTABLE_POLICY 125
+# define TS_R_UNSUPPORTED_MD_ALGORITHM 126
+# define TS_R_UNSUPPORTED_VERSION 113
+# define TS_R_VAR_BAD_VALUE 135
+# define TS_R_VAR_LOOKUP_FAILURE 136
+# define TS_R_WRONG_CONTENT_TYPE 114
+
+# endif
+#endif
diff --git a/include/openssl/txt_db.h b/include/openssl/txt_db.h
new file mode 100644
index 00000000..af169a30
--- /dev/null
+++ b/include/openssl/txt_db.h
@@ -0,0 +1,63 @@
+/*
+ * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_TXT_DB_H
+# define OPENSSL_TXT_DB_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_TXT_DB_H
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/bio.h>
+# include <openssl/safestack.h>
+# include <openssl/lhash.h>
+
+# define DB_ERROR_OK 0
+# define DB_ERROR_MALLOC 1
+# define DB_ERROR_INDEX_CLASH 2
+# define DB_ERROR_INDEX_OUT_OF_RANGE 3
+# define DB_ERROR_NO_INDEX 4
+# define DB_ERROR_INSERT_INDEX_CLASH 5
+# define DB_ERROR_WRONG_NUM_FIELDS 6
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef OPENSSL_STRING *OPENSSL_PSTRING;
+DEFINE_SPECIAL_STACK_OF(OPENSSL_PSTRING, OPENSSL_STRING)
+
+typedef struct txt_db_st {
+ int num_fields;
+ STACK_OF(OPENSSL_PSTRING) *data;
+ LHASH_OF(OPENSSL_STRING) **index;
+ int (**qual) (OPENSSL_STRING *);
+ long error;
+ long arg1;
+ long arg2;
+ OPENSSL_STRING *arg_row;
+} TXT_DB;
+
+TXT_DB *TXT_DB_read(BIO *in, int num);
+long TXT_DB_write(BIO *out, TXT_DB *db);
+int TXT_DB_create_index(TXT_DB *db, int field, int (*qual) (OPENSSL_STRING *),
+ OPENSSL_LH_HASHFUNC hash, OPENSSL_LH_COMPFUNC cmp);
+void TXT_DB_free(TXT_DB *db);
+OPENSSL_STRING *TXT_DB_get_by_index(TXT_DB *db, int idx,
+ OPENSSL_STRING *value);
+int TXT_DB_insert(TXT_DB *db, OPENSSL_STRING *value);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/include/openssl/types.h b/include/openssl/types.h
new file mode 100644
index 00000000..de9f1665
--- /dev/null
+++ b/include/openssl/types.h
@@ -0,0 +1,236 @@
+/*
+ * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_TYPES_H
+# define OPENSSL_TYPES_H
+# pragma once
+
+# include <limits.h>
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/safestack.h>
+# include <openssl/macros.h>
+
+typedef struct ossl_provider_st OSSL_PROVIDER; /* Provider Object */
+
+# ifdef NO_ASN1_TYPEDEFS
+# define ASN1_INTEGER ASN1_STRING
+# define ASN1_ENUMERATED ASN1_STRING
+# define ASN1_BIT_STRING ASN1_STRING
+# define ASN1_OCTET_STRING ASN1_STRING
+# define ASN1_PRINTABLESTRING ASN1_STRING
+# define ASN1_T61STRING ASN1_STRING
+# define ASN1_IA5STRING ASN1_STRING
+# define ASN1_UTCTIME ASN1_STRING
+# define ASN1_GENERALIZEDTIME ASN1_STRING
+# define ASN1_TIME ASN1_STRING
+# define ASN1_GENERALSTRING ASN1_STRING
+# define ASN1_UNIVERSALSTRING ASN1_STRING
+# define ASN1_BMPSTRING ASN1_STRING
+# define ASN1_VISIBLESTRING ASN1_STRING
+# define ASN1_UTF8STRING ASN1_STRING
+# define ASN1_BOOLEAN int
+# define ASN1_NULL int
+# else
+typedef struct asn1_string_st ASN1_INTEGER;
+typedef struct asn1_string_st ASN1_ENUMERATED;
+typedef struct asn1_string_st ASN1_BIT_STRING;
+typedef struct asn1_string_st ASN1_OCTET_STRING;
+typedef struct asn1_string_st ASN1_PRINTABLESTRING;
+typedef struct asn1_string_st ASN1_T61STRING;
+typedef struct asn1_string_st ASN1_IA5STRING;
+typedef struct asn1_string_st ASN1_GENERALSTRING;
+typedef struct asn1_string_st ASN1_UNIVERSALSTRING;
+typedef struct asn1_string_st ASN1_BMPSTRING;
+typedef struct asn1_string_st ASN1_UTCTIME;
+typedef struct asn1_string_st ASN1_TIME;
+typedef struct asn1_string_st ASN1_GENERALIZEDTIME;
+typedef struct asn1_string_st ASN1_VISIBLESTRING;
+typedef struct asn1_string_st ASN1_UTF8STRING;
+typedef struct asn1_string_st ASN1_STRING;
+typedef int ASN1_BOOLEAN;
+typedef int ASN1_NULL;
+# endif
+
+typedef struct asn1_type_st ASN1_TYPE;
+typedef struct asn1_object_st ASN1_OBJECT;
+typedef struct asn1_string_table_st ASN1_STRING_TABLE;
+
+typedef struct ASN1_ITEM_st ASN1_ITEM;
+typedef struct asn1_pctx_st ASN1_PCTX;
+typedef struct asn1_sctx_st ASN1_SCTX;
+
+# ifdef _WIN32
+# undef X509_NAME
+# undef X509_EXTENSIONS
+# undef PKCS7_ISSUER_AND_SERIAL
+# undef PKCS7_SIGNER_INFO
+# undef OCSP_REQUEST
+# undef OCSP_RESPONSE
+# endif
+
+# ifdef BIGNUM
+# undef BIGNUM
+# endif
+
+typedef struct bio_st BIO;
+typedef struct bignum_st BIGNUM;
+typedef struct bignum_ctx BN_CTX;
+typedef struct bn_blinding_st BN_BLINDING;
+typedef struct bn_mont_ctx_st BN_MONT_CTX;
+typedef struct bn_recp_ctx_st BN_RECP_CTX;
+typedef struct bn_gencb_st BN_GENCB;
+
+typedef struct buf_mem_st BUF_MEM;
+
+STACK_OF(BIGNUM);
+STACK_OF(BIGNUM_const);
+
+typedef struct err_state_st ERR_STATE;
+
+typedef struct evp_cipher_st EVP_CIPHER;
+typedef struct evp_cipher_ctx_st EVP_CIPHER_CTX;
+typedef struct evp_md_st EVP_MD;
+typedef struct evp_md_ctx_st EVP_MD_CTX;
+typedef struct evp_mac_st EVP_MAC;
+typedef struct evp_mac_ctx_st EVP_MAC_CTX;
+typedef struct evp_pkey_st EVP_PKEY;
+
+typedef struct evp_pkey_asn1_method_st EVP_PKEY_ASN1_METHOD;
+
+typedef struct evp_pkey_method_st EVP_PKEY_METHOD;
+typedef struct evp_pkey_ctx_st EVP_PKEY_CTX;
+
+typedef struct evp_keymgmt_st EVP_KEYMGMT;
+
+typedef struct evp_kdf_st EVP_KDF;
+typedef struct evp_kdf_ctx_st EVP_KDF_CTX;
+
+typedef struct evp_rand_st EVP_RAND;
+typedef struct evp_rand_ctx_st EVP_RAND_CTX;
+
+typedef struct evp_keyexch_st EVP_KEYEXCH;
+
+typedef struct evp_signature_st EVP_SIGNATURE;
+
+typedef struct evp_asym_cipher_st EVP_ASYM_CIPHER;
+
+typedef struct evp_kem_st EVP_KEM;
+
+typedef struct evp_Encode_Ctx_st EVP_ENCODE_CTX;
+
+typedef struct hmac_ctx_st HMAC_CTX;
+
+typedef struct dh_st DH;
+typedef struct dh_method DH_METHOD;
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef struct dsa_st DSA;
+typedef struct dsa_method DSA_METHOD;
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef struct rsa_st RSA;
+typedef struct rsa_meth_st RSA_METHOD;
+# endif
+typedef struct rsa_pss_params_st RSA_PSS_PARAMS;
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+typedef struct ec_key_st EC_KEY;
+typedef struct ec_key_method_st EC_KEY_METHOD;
+# endif
+
+typedef struct rand_meth_st RAND_METHOD;
+typedef struct rand_drbg_st RAND_DRBG;
+
+typedef struct ssl_dane_st SSL_DANE;
+typedef struct x509_st X509;
+typedef struct X509_algor_st X509_ALGOR;
+typedef struct X509_crl_st X509_CRL;
+typedef struct x509_crl_method_st X509_CRL_METHOD;
+typedef struct x509_revoked_st X509_REVOKED;
+typedef struct X509_name_st X509_NAME;
+typedef struct X509_pubkey_st X509_PUBKEY;
+typedef struct x509_store_st X509_STORE;
+typedef struct x509_store_ctx_st X509_STORE_CTX;
+
+typedef struct x509_object_st X509_OBJECT;
+typedef struct x509_lookup_st X509_LOOKUP;
+typedef struct x509_lookup_method_st X509_LOOKUP_METHOD;
+typedef struct X509_VERIFY_PARAM_st X509_VERIFY_PARAM;
+
+typedef struct x509_sig_info_st X509_SIG_INFO;
+
+typedef struct pkcs8_priv_key_info_st PKCS8_PRIV_KEY_INFO;
+
+typedef struct v3_ext_ctx X509V3_CTX;
+typedef struct conf_st CONF;
+typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS;
+
+typedef struct ui_st UI;
+typedef struct ui_method_st UI_METHOD;
+
+typedef struct engine_st ENGINE;
+typedef struct ssl_st SSL;
+typedef struct ssl_ctx_st SSL_CTX;
+
+typedef struct comp_ctx_st COMP_CTX;
+typedef struct comp_method_st COMP_METHOD;
+
+typedef struct X509_POLICY_NODE_st X509_POLICY_NODE;
+typedef struct X509_POLICY_LEVEL_st X509_POLICY_LEVEL;
+typedef struct X509_POLICY_TREE_st X509_POLICY_TREE;
+typedef struct X509_POLICY_CACHE_st X509_POLICY_CACHE;
+
+typedef struct AUTHORITY_KEYID_st AUTHORITY_KEYID;
+typedef struct DIST_POINT_st DIST_POINT;
+typedef struct ISSUING_DIST_POINT_st ISSUING_DIST_POINT;
+typedef struct NAME_CONSTRAINTS_st NAME_CONSTRAINTS;
+
+typedef struct crypto_ex_data_st CRYPTO_EX_DATA;
+
+typedef struct ossl_http_req_ctx_st OSSL_HTTP_REQ_CTX;
+typedef struct ocsp_response_st OCSP_RESPONSE;
+typedef struct ocsp_responder_id_st OCSP_RESPID;
+
+typedef struct sct_st SCT;
+typedef struct sct_ctx_st SCT_CTX;
+typedef struct ctlog_st CTLOG;
+typedef struct ctlog_store_st CTLOG_STORE;
+typedef struct ct_policy_eval_ctx_st CT_POLICY_EVAL_CTX;
+
+typedef struct ossl_store_info_st OSSL_STORE_INFO;
+typedef struct ossl_store_search_st OSSL_STORE_SEARCH;
+
+typedef struct ossl_lib_ctx_st OSSL_LIB_CTX;
+
+typedef struct ossl_dispatch_st OSSL_DISPATCH;
+typedef struct ossl_item_st OSSL_ITEM;
+typedef struct ossl_algorithm_st OSSL_ALGORITHM;
+typedef struct ossl_param_st OSSL_PARAM;
+typedef struct ossl_param_bld_st OSSL_PARAM_BLD;
+
+typedef int pem_password_cb (char *buf, int size, int rwflag, void *userdata);
+
+typedef struct ossl_encoder_st OSSL_ENCODER;
+typedef struct ossl_encoder_ctx_st OSSL_ENCODER_CTX;
+typedef struct ossl_decoder_st OSSL_DECODER;
+typedef struct ossl_decoder_ctx_st OSSL_DECODER_CTX;
+
+typedef struct ossl_self_test_st OSSL_SELF_TEST;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* OPENSSL_TYPES_H */
diff --git a/include/openssl/ui.h b/include/openssl/ui.h
new file mode 100644
index 00000000..835b0eba
--- /dev/null
+++ b/include/openssl/ui.h
@@ -0,0 +1,407 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\ui.h.in
+ *
+ * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_UI_H
+# define OPENSSL_UI_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_UI_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/crypto.h>
+# endif
+# include <openssl/safestack.h>
+# include <openssl/pem.h>
+# include <openssl/types.h>
+# include <openssl/uierr.h>
+
+/* For compatibility reasons, the macro OPENSSL_NO_UI is currently retained */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifdef OPENSSL_NO_UI_CONSOLE
+# define OPENSSL_NO_UI
+# endif
+# endif
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * All the following functions return -1 or NULL on error and in some cases
+ * (UI_process()) -2 if interrupted or in some other way cancelled. When
+ * everything is fine, they return 0, a positive value or a non-NULL pointer,
+ * all depending on their purpose.
+ */
+
+/* Creators and destructor. */
+UI *UI_new(void);
+UI *UI_new_method(const UI_METHOD *method);
+void UI_free(UI *ui);
+
+/*-
+ The following functions are used to add strings to be printed and prompt
+ strings to prompt for data. The names are UI_{add,dup}_<function>_string
+ and UI_{add,dup}_input_boolean.
+
+ UI_{add,dup}_<function>_string have the following meanings:
+ add add a text or prompt string. The pointers given to these
+ functions are used verbatim, no copying is done.
+ dup make a copy of the text or prompt string, then add the copy
+ to the collection of strings in the user interface.
+ <function>
+ The function is a name for the functionality that the given
+ string shall be used for. It can be one of:
+ input use the string as data prompt.
+ verify use the string as verification prompt. This
+ is used to verify a previous input.
+ info use the string for informational output.
+ error use the string for error output.
+ Honestly, there's currently no difference between info and error for the
+ moment.
+
+ UI_{add,dup}_input_boolean have the same semantics for "add" and "dup",
+ and are typically used when one wants to prompt for a yes/no response.
+
+ All of the functions in this group take a UI and a prompt string.
+ The string input and verify addition functions also take a flag argument,
+ a buffer for the result to end up with, a minimum input size and a maximum
+ input size (the result buffer MUST be large enough to be able to contain
+ the maximum number of characters). Additionally, the verify addition
+ functions takes another buffer to compare the result against.
+ The boolean input functions take an action description string (which should
+ be safe to ignore if the expected user action is obvious, for example with
+ a dialog box with an OK button and a Cancel button), a string of acceptable
+ characters to mean OK and to mean Cancel. The two last strings are checked
+ to make sure they don't have common characters. Additionally, the same
+ flag argument as for the string input is taken, as well as a result buffer.
+ The result buffer is required to be at least one byte long. Depending on
+ the answer, the first character from the OK or the Cancel character strings
+ will be stored in the first byte of the result buffer. No NUL will be
+ added, so the result is *not* a string.
+
+ On success, the all return an index of the added information. That index
+ is useful when retrieving results with UI_get0_result(). */
+int UI_add_input_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize);
+int UI_dup_input_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize);
+int UI_add_verify_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize,
+ const char *test_buf);
+int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize,
+ const char *test_buf);
+int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
+ const char *ok_chars, const char *cancel_chars,
+ int flags, char *result_buf);
+int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
+ const char *ok_chars, const char *cancel_chars,
+ int flags, char *result_buf);
+int UI_add_info_string(UI *ui, const char *text);
+int UI_dup_info_string(UI *ui, const char *text);
+int UI_add_error_string(UI *ui, const char *text);
+int UI_dup_error_string(UI *ui, const char *text);
+
+/* These are the possible flags. They can be or'ed together. */
+/* Use to have echoing of input */
+# define UI_INPUT_FLAG_ECHO 0x01
+/*
+ * Use a default password. Where that password is found is completely up to
+ * the application, it might for example be in the user data set with
+ * UI_add_user_data(). It is not recommended to have more than one input in
+ * each UI being marked with this flag, or the application might get
+ * confused.
+ */
+# define UI_INPUT_FLAG_DEFAULT_PWD 0x02
+
+/*-
+ * The user of these routines may want to define flags of their own. The core
+ * UI won't look at those, but will pass them on to the method routines. They
+ * must use higher bits so they don't get confused with the UI bits above.
+ * UI_INPUT_FLAG_USER_BASE tells which is the lowest bit to use. A good
+ * example of use is this:
+ *
+ * #define MY_UI_FLAG1 (0x01 << UI_INPUT_FLAG_USER_BASE)
+ *
+*/
+# define UI_INPUT_FLAG_USER_BASE 16
+
+/*-
+ * The following function helps construct a prompt.
+ * phrase_desc is a textual short description of the phrase to enter,
+ * for example "pass phrase", and
+ * object_name is the name of the object
+ * (which might be a card name or a file name) or NULL.
+ * The returned string shall always be allocated on the heap with
+ * OPENSSL_malloc(), and need to be free'd with OPENSSL_free().
+ *
+ * If the ui_method doesn't contain a pointer to a user-defined prompt
+ * constructor, a default string is built, looking like this:
+ *
+ * "Enter {phrase_desc} for {object_name}:"
+ *
+ * So, if phrase_desc has the value "pass phrase" and object_name has
+ * the value "foo.key", the resulting string is:
+ *
+ * "Enter pass phrase for foo.key:"
+*/
+char *UI_construct_prompt(UI *ui_method,
+ const char *phrase_desc, const char *object_name);
+
+/*
+ * The following function is used to store a pointer to user-specific data.
+ * Any previous such pointer will be returned and replaced.
+ *
+ * For callback purposes, this function makes a lot more sense than using
+ * ex_data, since the latter requires that different parts of OpenSSL or
+ * applications share the same ex_data index.
+ *
+ * Note that the UI_OpenSSL() method completely ignores the user data. Other
+ * methods may not, however.
+ */
+void *UI_add_user_data(UI *ui, void *user_data);
+/*
+ * Alternatively, this function is used to duplicate the user data.
+ * This uses the duplicator method function. The destroy function will
+ * be used to free the user data in this case.
+ */
+int UI_dup_user_data(UI *ui, void *user_data);
+/* We need a user data retrieving function as well. */
+void *UI_get0_user_data(UI *ui);
+
+/* Return the result associated with a prompt given with the index i. */
+const char *UI_get0_result(UI *ui, int i);
+int UI_get_result_length(UI *ui, int i);
+
+/* When all strings have been added, process the whole thing. */
+int UI_process(UI *ui);
+
+/*
+ * Give a user interface parameterised control commands. This can be used to
+ * send down an integer, a data pointer or a function pointer, as well as be
+ * used to get information from a UI.
+ */
+int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f) (void));
+
+/* The commands */
+/*
+ * Use UI_CONTROL_PRINT_ERRORS with the value 1 to have UI_process print the
+ * OpenSSL error stack before printing any info or added error messages and
+ * before any prompting.
+ */
+# define UI_CTRL_PRINT_ERRORS 1
+/*
+ * Check if a UI_process() is possible to do again with the same instance of
+ * a user interface. This makes UI_ctrl() return 1 if it is redoable, and 0
+ * if not.
+ */
+# define UI_CTRL_IS_REDOABLE 2
+
+/* Some methods may use extra data */
+# define UI_set_app_data(s,arg) UI_set_ex_data(s,0,arg)
+# define UI_get_app_data(s) UI_get_ex_data(s,0)
+
+# define UI_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, l, p, newf, dupf, freef)
+int UI_set_ex_data(UI *r, int idx, void *arg);
+void *UI_get_ex_data(const UI *r, int idx);
+
+/* Use specific methods instead of the built-in one */
+void UI_set_default_method(const UI_METHOD *meth);
+const UI_METHOD *UI_get_default_method(void);
+const UI_METHOD *UI_get_method(UI *ui);
+const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth);
+
+# ifndef OPENSSL_NO_UI_CONSOLE
+
+/* The method with all the built-in thingies */
+UI_METHOD *UI_OpenSSL(void);
+
+# endif
+
+/*
+ * NULL method. Literally does nothing, but may serve as a placeholder
+ * to avoid internal default.
+ */
+const UI_METHOD *UI_null(void);
+
+/* ---------- For method writers ---------- */
+/*-
+ A method contains a number of functions that implement the low level
+ of the User Interface. The functions are:
+
+ an opener This function starts a session, maybe by opening
+ a channel to a tty, or by opening a window.
+ a writer This function is called to write a given string,
+ maybe to the tty, maybe as a field label in a
+ window.
+ a flusher This function is called to flush everything that
+ has been output so far. It can be used to actually
+ display a dialog box after it has been built.
+ a reader This function is called to read a given prompt,
+ maybe from the tty, maybe from a field in a
+ window. Note that it's called with all string
+ structures, not only the prompt ones, so it must
+ check such things itself.
+ a closer This function closes the session, maybe by closing
+ the channel to the tty, or closing the window.
+
+ All these functions are expected to return:
+
+ 0 on error.
+ 1 on success.
+ -1 on out-of-band events, for example if some prompting has
+ been canceled (by pressing Ctrl-C, for example). This is
+ only checked when returned by the flusher or the reader.
+
+ The way this is used, the opener is first called, then the writer for all
+ strings, then the flusher, then the reader for all strings and finally the
+ closer. Note that if you want to prompt from a terminal or other command
+ line interface, the best is to have the reader also write the prompts
+ instead of having the writer do it. If you want to prompt from a dialog
+ box, the writer can be used to build up the contents of the box, and the
+ flusher to actually display the box and run the event loop until all data
+ has been given, after which the reader only grabs the given data and puts
+ them back into the UI strings.
+
+ All method functions take a UI as argument. Additionally, the writer and
+ the reader take a UI_STRING.
+*/
+
+/*
+ * The UI_STRING type is the data structure that contains all the needed info
+ * about a string or a prompt, including test data for a verification prompt.
+ */
+typedef struct ui_string_st UI_STRING;
+
+SKM_DEFINE_STACK_OF_INTERNAL(UI_STRING, UI_STRING, UI_STRING)
+#define sk_UI_STRING_num(sk) OPENSSL_sk_num(ossl_check_const_UI_STRING_sk_type(sk))
+#define sk_UI_STRING_value(sk, idx) ((UI_STRING *)OPENSSL_sk_value(ossl_check_const_UI_STRING_sk_type(sk), (idx)))
+#define sk_UI_STRING_new(cmp) ((STACK_OF(UI_STRING) *)OPENSSL_sk_new(ossl_check_UI_STRING_compfunc_type(cmp)))
+#define sk_UI_STRING_new_null() ((STACK_OF(UI_STRING) *)OPENSSL_sk_new_null())
+#define sk_UI_STRING_new_reserve(cmp, n) ((STACK_OF(UI_STRING) *)OPENSSL_sk_new_reserve(ossl_check_UI_STRING_compfunc_type(cmp), (n)))
+#define sk_UI_STRING_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_UI_STRING_sk_type(sk), (n))
+#define sk_UI_STRING_free(sk) OPENSSL_sk_free(ossl_check_UI_STRING_sk_type(sk))
+#define sk_UI_STRING_zero(sk) OPENSSL_sk_zero(ossl_check_UI_STRING_sk_type(sk))
+#define sk_UI_STRING_delete(sk, i) ((UI_STRING *)OPENSSL_sk_delete(ossl_check_UI_STRING_sk_type(sk), (i)))
+#define sk_UI_STRING_delete_ptr(sk, ptr) ((UI_STRING *)OPENSSL_sk_delete_ptr(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_type(ptr)))
+#define sk_UI_STRING_push(sk, ptr) OPENSSL_sk_push(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_type(ptr))
+#define sk_UI_STRING_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_type(ptr))
+#define sk_UI_STRING_pop(sk) ((UI_STRING *)OPENSSL_sk_pop(ossl_check_UI_STRING_sk_type(sk)))
+#define sk_UI_STRING_shift(sk) ((UI_STRING *)OPENSSL_sk_shift(ossl_check_UI_STRING_sk_type(sk)))
+#define sk_UI_STRING_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_UI_STRING_sk_type(sk),ossl_check_UI_STRING_freefunc_type(freefunc))
+#define sk_UI_STRING_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_type(ptr), (idx))
+#define sk_UI_STRING_set(sk, idx, ptr) ((UI_STRING *)OPENSSL_sk_set(ossl_check_UI_STRING_sk_type(sk), (idx), ossl_check_UI_STRING_type(ptr)))
+#define sk_UI_STRING_find(sk, ptr) OPENSSL_sk_find(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_type(ptr))
+#define sk_UI_STRING_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_type(ptr))
+#define sk_UI_STRING_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_type(ptr), pnum)
+#define sk_UI_STRING_sort(sk) OPENSSL_sk_sort(ossl_check_UI_STRING_sk_type(sk))
+#define sk_UI_STRING_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_UI_STRING_sk_type(sk))
+#define sk_UI_STRING_dup(sk) ((STACK_OF(UI_STRING) *)OPENSSL_sk_dup(ossl_check_const_UI_STRING_sk_type(sk)))
+#define sk_UI_STRING_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(UI_STRING) *)OPENSSL_sk_deep_copy(ossl_check_const_UI_STRING_sk_type(sk), ossl_check_UI_STRING_copyfunc_type(copyfunc), ossl_check_UI_STRING_freefunc_type(freefunc)))
+#define sk_UI_STRING_set_cmp_func(sk, cmp) ((sk_UI_STRING_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_UI_STRING_sk_type(sk), ossl_check_UI_STRING_compfunc_type(cmp)))
+
+
+/*
+ * The different types of strings that are currently supported. This is only
+ * needed by method authors.
+ */
+enum UI_string_types {
+ UIT_NONE = 0,
+ UIT_PROMPT, /* Prompt for a string */
+ UIT_VERIFY, /* Prompt for a string and verify */
+ UIT_BOOLEAN, /* Prompt for a yes/no response */
+ UIT_INFO, /* Send info to the user */
+ UIT_ERROR /* Send an error message to the user */
+};
+
+/* Create and manipulate methods */
+UI_METHOD *UI_create_method(const char *name);
+void UI_destroy_method(UI_METHOD *ui_method);
+int UI_method_set_opener(UI_METHOD *method, int (*opener) (UI *ui));
+int UI_method_set_writer(UI_METHOD *method,
+ int (*writer) (UI *ui, UI_STRING *uis));
+int UI_method_set_flusher(UI_METHOD *method, int (*flusher) (UI *ui));
+int UI_method_set_reader(UI_METHOD *method,
+ int (*reader) (UI *ui, UI_STRING *uis));
+int UI_method_set_closer(UI_METHOD *method, int (*closer) (UI *ui));
+int UI_method_set_data_duplicator(UI_METHOD *method,
+ void *(*duplicator) (UI *ui, void *ui_data),
+ void (*destructor)(UI *ui, void *ui_data));
+int UI_method_set_prompt_constructor(UI_METHOD *method,
+ char *(*prompt_constructor) (UI *ui,
+ const char
+ *phrase_desc,
+ const char
+ *object_name));
+int UI_method_set_ex_data(UI_METHOD *method, int idx, void *data);
+int (*UI_method_get_opener(const UI_METHOD *method)) (UI *);
+int (*UI_method_get_writer(const UI_METHOD *method)) (UI *, UI_STRING *);
+int (*UI_method_get_flusher(const UI_METHOD *method)) (UI *);
+int (*UI_method_get_reader(const UI_METHOD *method)) (UI *, UI_STRING *);
+int (*UI_method_get_closer(const UI_METHOD *method)) (UI *);
+char *(*UI_method_get_prompt_constructor(const UI_METHOD *method))
+ (UI *, const char *, const char *);
+void *(*UI_method_get_data_duplicator(const UI_METHOD *method)) (UI *, void *);
+void (*UI_method_get_data_destructor(const UI_METHOD *method)) (UI *, void *);
+const void *UI_method_get_ex_data(const UI_METHOD *method, int idx);
+
+/*
+ * The following functions are helpers for method writers to access relevant
+ * data from a UI_STRING.
+ */
+
+/* Return type of the UI_STRING */
+enum UI_string_types UI_get_string_type(UI_STRING *uis);
+/* Return input flags of the UI_STRING */
+int UI_get_input_flags(UI_STRING *uis);
+/* Return the actual string to output (the prompt, info or error) */
+const char *UI_get0_output_string(UI_STRING *uis);
+/*
+ * Return the optional action string to output (the boolean prompt
+ * instruction)
+ */
+const char *UI_get0_action_string(UI_STRING *uis);
+/* Return the result of a prompt */
+const char *UI_get0_result_string(UI_STRING *uis);
+int UI_get_result_string_length(UI_STRING *uis);
+/*
+ * Return the string to test the result against. Only useful with verifies.
+ */
+const char *UI_get0_test_string(UI_STRING *uis);
+/* Return the required minimum size of the result */
+int UI_get_result_minsize(UI_STRING *uis);
+/* Return the required maximum size of the result */
+int UI_get_result_maxsize(UI_STRING *uis);
+/* Set the result of a UI_STRING. */
+int UI_set_result(UI *ui, UI_STRING *uis, const char *result);
+int UI_set_result_ex(UI *ui, UI_STRING *uis, const char *result, int len);
+
+/* A couple of popular utility functions */
+int UI_UTIL_read_pw_string(char *buf, int length, const char *prompt,
+ int verify);
+int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt,
+ int verify);
+UI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/ui.h.in b/include/openssl/ui.h.in
new file mode 100644
index 00000000..eb9a580f
--- /dev/null
+++ b/include/openssl/ui.h.in
@@ -0,0 +1,384 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 2001-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_UI_H
+# define OPENSSL_UI_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_UI_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/crypto.h>
+# endif
+# include <openssl/safestack.h>
+# include <openssl/pem.h>
+# include <openssl/types.h>
+# include <openssl/uierr.h>
+
+/* For compatibility reasons, the macro OPENSSL_NO_UI is currently retained */
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifdef OPENSSL_NO_UI_CONSOLE
+# define OPENSSL_NO_UI
+# endif
+# endif
+
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+/*
+ * All the following functions return -1 or NULL on error and in some cases
+ * (UI_process()) -2 if interrupted or in some other way cancelled. When
+ * everything is fine, they return 0, a positive value or a non-NULL pointer,
+ * all depending on their purpose.
+ */
+
+/* Creators and destructor. */
+UI *UI_new(void);
+UI *UI_new_method(const UI_METHOD *method);
+void UI_free(UI *ui);
+
+/*-
+ The following functions are used to add strings to be printed and prompt
+ strings to prompt for data. The names are UI_{add,dup}_<function>_string
+ and UI_{add,dup}_input_boolean.
+
+ UI_{add,dup}_<function>_string have the following meanings:
+ add add a text or prompt string. The pointers given to these
+ functions are used verbatim, no copying is done.
+ dup make a copy of the text or prompt string, then add the copy
+ to the collection of strings in the user interface.
+ <function>
+ The function is a name for the functionality that the given
+ string shall be used for. It can be one of:
+ input use the string as data prompt.
+ verify use the string as verification prompt. This
+ is used to verify a previous input.
+ info use the string for informational output.
+ error use the string for error output.
+ Honestly, there's currently no difference between info and error for the
+ moment.
+
+ UI_{add,dup}_input_boolean have the same semantics for "add" and "dup",
+ and are typically used when one wants to prompt for a yes/no response.
+
+ All of the functions in this group take a UI and a prompt string.
+ The string input and verify addition functions also take a flag argument,
+ a buffer for the result to end up with, a minimum input size and a maximum
+ input size (the result buffer MUST be large enough to be able to contain
+ the maximum number of characters). Additionally, the verify addition
+ functions takes another buffer to compare the result against.
+ The boolean input functions take an action description string (which should
+ be safe to ignore if the expected user action is obvious, for example with
+ a dialog box with an OK button and a Cancel button), a string of acceptable
+ characters to mean OK and to mean Cancel. The two last strings are checked
+ to make sure they don't have common characters. Additionally, the same
+ flag argument as for the string input is taken, as well as a result buffer.
+ The result buffer is required to be at least one byte long. Depending on
+ the answer, the first character from the OK or the Cancel character strings
+ will be stored in the first byte of the result buffer. No NUL will be
+ added, so the result is *not* a string.
+
+ On success, the all return an index of the added information. That index
+ is useful when retrieving results with UI_get0_result(). */
+int UI_add_input_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize);
+int UI_dup_input_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize);
+int UI_add_verify_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize,
+ const char *test_buf);
+int UI_dup_verify_string(UI *ui, const char *prompt, int flags,
+ char *result_buf, int minsize, int maxsize,
+ const char *test_buf);
+int UI_add_input_boolean(UI *ui, const char *prompt, const char *action_desc,
+ const char *ok_chars, const char *cancel_chars,
+ int flags, char *result_buf);
+int UI_dup_input_boolean(UI *ui, const char *prompt, const char *action_desc,
+ const char *ok_chars, const char *cancel_chars,
+ int flags, char *result_buf);
+int UI_add_info_string(UI *ui, const char *text);
+int UI_dup_info_string(UI *ui, const char *text);
+int UI_add_error_string(UI *ui, const char *text);
+int UI_dup_error_string(UI *ui, const char *text);
+
+/* These are the possible flags. They can be or'ed together. */
+/* Use to have echoing of input */
+# define UI_INPUT_FLAG_ECHO 0x01
+/*
+ * Use a default password. Where that password is found is completely up to
+ * the application, it might for example be in the user data set with
+ * UI_add_user_data(). It is not recommended to have more than one input in
+ * each UI being marked with this flag, or the application might get
+ * confused.
+ */
+# define UI_INPUT_FLAG_DEFAULT_PWD 0x02
+
+/*-
+ * The user of these routines may want to define flags of their own. The core
+ * UI won't look at those, but will pass them on to the method routines. They
+ * must use higher bits so they don't get confused with the UI bits above.
+ * UI_INPUT_FLAG_USER_BASE tells which is the lowest bit to use. A good
+ * example of use is this:
+ *
+ * #define MY_UI_FLAG1 (0x01 << UI_INPUT_FLAG_USER_BASE)
+ *
+*/
+# define UI_INPUT_FLAG_USER_BASE 16
+
+/*-
+ * The following function helps construct a prompt.
+ * phrase_desc is a textual short description of the phrase to enter,
+ * for example "pass phrase", and
+ * object_name is the name of the object
+ * (which might be a card name or a file name) or NULL.
+ * The returned string shall always be allocated on the heap with
+ * OPENSSL_malloc(), and need to be free'd with OPENSSL_free().
+ *
+ * If the ui_method doesn't contain a pointer to a user-defined prompt
+ * constructor, a default string is built, looking like this:
+ *
+ * "Enter {phrase_desc} for {object_name}:"
+ *
+ * So, if phrase_desc has the value "pass phrase" and object_name has
+ * the value "foo.key", the resulting string is:
+ *
+ * "Enter pass phrase for foo.key:"
+*/
+char *UI_construct_prompt(UI *ui_method,
+ const char *phrase_desc, const char *object_name);
+
+/*
+ * The following function is used to store a pointer to user-specific data.
+ * Any previous such pointer will be returned and replaced.
+ *
+ * For callback purposes, this function makes a lot more sense than using
+ * ex_data, since the latter requires that different parts of OpenSSL or
+ * applications share the same ex_data index.
+ *
+ * Note that the UI_OpenSSL() method completely ignores the user data. Other
+ * methods may not, however.
+ */
+void *UI_add_user_data(UI *ui, void *user_data);
+/*
+ * Alternatively, this function is used to duplicate the user data.
+ * This uses the duplicator method function. The destroy function will
+ * be used to free the user data in this case.
+ */
+int UI_dup_user_data(UI *ui, void *user_data);
+/* We need a user data retrieving function as well. */
+void *UI_get0_user_data(UI *ui);
+
+/* Return the result associated with a prompt given with the index i. */
+const char *UI_get0_result(UI *ui, int i);
+int UI_get_result_length(UI *ui, int i);
+
+/* When all strings have been added, process the whole thing. */
+int UI_process(UI *ui);
+
+/*
+ * Give a user interface parameterised control commands. This can be used to
+ * send down an integer, a data pointer or a function pointer, as well as be
+ * used to get information from a UI.
+ */
+int UI_ctrl(UI *ui, int cmd, long i, void *p, void (*f) (void));
+
+/* The commands */
+/*
+ * Use UI_CONTROL_PRINT_ERRORS with the value 1 to have UI_process print the
+ * OpenSSL error stack before printing any info or added error messages and
+ * before any prompting.
+ */
+# define UI_CTRL_PRINT_ERRORS 1
+/*
+ * Check if a UI_process() is possible to do again with the same instance of
+ * a user interface. This makes UI_ctrl() return 1 if it is redoable, and 0
+ * if not.
+ */
+# define UI_CTRL_IS_REDOABLE 2
+
+/* Some methods may use extra data */
+# define UI_set_app_data(s,arg) UI_set_ex_data(s,0,arg)
+# define UI_get_app_data(s) UI_get_ex_data(s,0)
+
+# define UI_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_UI, l, p, newf, dupf, freef)
+int UI_set_ex_data(UI *r, int idx, void *arg);
+void *UI_get_ex_data(const UI *r, int idx);
+
+/* Use specific methods instead of the built-in one */
+void UI_set_default_method(const UI_METHOD *meth);
+const UI_METHOD *UI_get_default_method(void);
+const UI_METHOD *UI_get_method(UI *ui);
+const UI_METHOD *UI_set_method(UI *ui, const UI_METHOD *meth);
+
+# ifndef OPENSSL_NO_UI_CONSOLE
+
+/* The method with all the built-in thingies */
+UI_METHOD *UI_OpenSSL(void);
+
+# endif
+
+/*
+ * NULL method. Literally does nothing, but may serve as a placeholder
+ * to avoid internal default.
+ */
+const UI_METHOD *UI_null(void);
+
+/* ---------- For method writers ---------- */
+/*-
+ A method contains a number of functions that implement the low level
+ of the User Interface. The functions are:
+
+ an opener This function starts a session, maybe by opening
+ a channel to a tty, or by opening a window.
+ a writer This function is called to write a given string,
+ maybe to the tty, maybe as a field label in a
+ window.
+ a flusher This function is called to flush everything that
+ has been output so far. It can be used to actually
+ display a dialog box after it has been built.
+ a reader This function is called to read a given prompt,
+ maybe from the tty, maybe from a field in a
+ window. Note that it's called with all string
+ structures, not only the prompt ones, so it must
+ check such things itself.
+ a closer This function closes the session, maybe by closing
+ the channel to the tty, or closing the window.
+
+ All these functions are expected to return:
+
+ 0 on error.
+ 1 on success.
+ -1 on out-of-band events, for example if some prompting has
+ been canceled (by pressing Ctrl-C, for example). This is
+ only checked when returned by the flusher or the reader.
+
+ The way this is used, the opener is first called, then the writer for all
+ strings, then the flusher, then the reader for all strings and finally the
+ closer. Note that if you want to prompt from a terminal or other command
+ line interface, the best is to have the reader also write the prompts
+ instead of having the writer do it. If you want to prompt from a dialog
+ box, the writer can be used to build up the contents of the box, and the
+ flusher to actually display the box and run the event loop until all data
+ has been given, after which the reader only grabs the given data and puts
+ them back into the UI strings.
+
+ All method functions take a UI as argument. Additionally, the writer and
+ the reader take a UI_STRING.
+*/
+
+/*
+ * The UI_STRING type is the data structure that contains all the needed info
+ * about a string or a prompt, including test data for a verification prompt.
+ */
+typedef struct ui_string_st UI_STRING;
+
+{-
+ generate_stack_macros("UI_STRING");
+-}
+
+/*
+ * The different types of strings that are currently supported. This is only
+ * needed by method authors.
+ */
+enum UI_string_types {
+ UIT_NONE = 0,
+ UIT_PROMPT, /* Prompt for a string */
+ UIT_VERIFY, /* Prompt for a string and verify */
+ UIT_BOOLEAN, /* Prompt for a yes/no response */
+ UIT_INFO, /* Send info to the user */
+ UIT_ERROR /* Send an error message to the user */
+};
+
+/* Create and manipulate methods */
+UI_METHOD *UI_create_method(const char *name);
+void UI_destroy_method(UI_METHOD *ui_method);
+int UI_method_set_opener(UI_METHOD *method, int (*opener) (UI *ui));
+int UI_method_set_writer(UI_METHOD *method,
+ int (*writer) (UI *ui, UI_STRING *uis));
+int UI_method_set_flusher(UI_METHOD *method, int (*flusher) (UI *ui));
+int UI_method_set_reader(UI_METHOD *method,
+ int (*reader) (UI *ui, UI_STRING *uis));
+int UI_method_set_closer(UI_METHOD *method, int (*closer) (UI *ui));
+int UI_method_set_data_duplicator(UI_METHOD *method,
+ void *(*duplicator) (UI *ui, void *ui_data),
+ void (*destructor)(UI *ui, void *ui_data));
+int UI_method_set_prompt_constructor(UI_METHOD *method,
+ char *(*prompt_constructor) (UI *ui,
+ const char
+ *phrase_desc,
+ const char
+ *object_name));
+int UI_method_set_ex_data(UI_METHOD *method, int idx, void *data);
+int (*UI_method_get_opener(const UI_METHOD *method)) (UI *);
+int (*UI_method_get_writer(const UI_METHOD *method)) (UI *, UI_STRING *);
+int (*UI_method_get_flusher(const UI_METHOD *method)) (UI *);
+int (*UI_method_get_reader(const UI_METHOD *method)) (UI *, UI_STRING *);
+int (*UI_method_get_closer(const UI_METHOD *method)) (UI *);
+char *(*UI_method_get_prompt_constructor(const UI_METHOD *method))
+ (UI *, const char *, const char *);
+void *(*UI_method_get_data_duplicator(const UI_METHOD *method)) (UI *, void *);
+void (*UI_method_get_data_destructor(const UI_METHOD *method)) (UI *, void *);
+const void *UI_method_get_ex_data(const UI_METHOD *method, int idx);
+
+/*
+ * The following functions are helpers for method writers to access relevant
+ * data from a UI_STRING.
+ */
+
+/* Return type of the UI_STRING */
+enum UI_string_types UI_get_string_type(UI_STRING *uis);
+/* Return input flags of the UI_STRING */
+int UI_get_input_flags(UI_STRING *uis);
+/* Return the actual string to output (the prompt, info or error) */
+const char *UI_get0_output_string(UI_STRING *uis);
+/*
+ * Return the optional action string to output (the boolean prompt
+ * instruction)
+ */
+const char *UI_get0_action_string(UI_STRING *uis);
+/* Return the result of a prompt */
+const char *UI_get0_result_string(UI_STRING *uis);
+int UI_get_result_string_length(UI_STRING *uis);
+/*
+ * Return the string to test the result against. Only useful with verifies.
+ */
+const char *UI_get0_test_string(UI_STRING *uis);
+/* Return the required minimum size of the result */
+int UI_get_result_minsize(UI_STRING *uis);
+/* Return the required maximum size of the result */
+int UI_get_result_maxsize(UI_STRING *uis);
+/* Set the result of a UI_STRING. */
+int UI_set_result(UI *ui, UI_STRING *uis, const char *result);
+int UI_set_result_ex(UI *ui, UI_STRING *uis, const char *result, int len);
+
+/* A couple of popular utility functions */
+int UI_UTIL_read_pw_string(char *buf, int length, const char *prompt,
+ int verify);
+int UI_UTIL_read_pw(char *buf, char *buff, int size, const char *prompt,
+ int verify);
+UI_METHOD *UI_UTIL_wrap_read_pem_callback(pem_password_cb *cb, int rwflag);
+
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/uierr.h b/include/openssl/uierr.h
new file mode 100644
index 00000000..473b04ed
--- /dev/null
+++ b/include/openssl/uierr.h
@@ -0,0 +1,38 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_UIERR_H
+# define OPENSSL_UIERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * UI reason codes.
+ */
+# define UI_R_COMMON_OK_AND_CANCEL_CHARACTERS 104
+# define UI_R_INDEX_TOO_LARGE 102
+# define UI_R_INDEX_TOO_SMALL 103
+# define UI_R_NO_RESULT_BUFFER 105
+# define UI_R_PROCESSING_ERROR 107
+# define UI_R_RESULT_TOO_LARGE 100
+# define UI_R_RESULT_TOO_SMALL 101
+# define UI_R_SYSASSIGN_ERROR 109
+# define UI_R_SYSDASSGN_ERROR 110
+# define UI_R_SYSQIOW_ERROR 111
+# define UI_R_UNKNOWN_CONTROL_COMMAND 106
+# define UI_R_UNKNOWN_TTYGET_ERRNO_VALUE 108
+# define UI_R_USER_DATA_DUPLICATION_UNSUPPORTED 112
+
+#endif
diff --git a/include/openssl/whrlpool.h b/include/openssl/whrlpool.h
new file mode 100644
index 00000000..05ba4632
--- /dev/null
+++ b/include/openssl/whrlpool.h
@@ -0,0 +1,62 @@
+/*
+ * Copyright 2005-2020 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_WHRLPOOL_H
+# define OPENSSL_WHRLPOOL_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_WHRLPOOL_H
+# endif
+
+# include <openssl/opensslconf.h>
+
+# ifndef OPENSSL_NO_WHIRLPOOL
+# include <openssl/e_os2.h>
+# include <stddef.h>
+# ifdef __cplusplus
+extern "C" {
+# endif
+
+# define WHIRLPOOL_DIGEST_LENGTH (512/8)
+
+# if !defined(OPENSSL_NO_DEPRECATED_3_0)
+
+# define WHIRLPOOL_BBLOCK 512
+# define WHIRLPOOL_COUNTER (256/8)
+
+typedef struct {
+ union {
+ unsigned char c[WHIRLPOOL_DIGEST_LENGTH];
+ /* double q is here to ensure 64-bit alignment */
+ double q[WHIRLPOOL_DIGEST_LENGTH / sizeof(double)];
+ } H;
+ unsigned char data[WHIRLPOOL_BBLOCK / 8];
+ unsigned int bitoff;
+ size_t bitlen[WHIRLPOOL_COUNTER / sizeof(size_t)];
+} WHIRLPOOL_CTX;
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 int WHIRLPOOL_Init(WHIRLPOOL_CTX *c);
+OSSL_DEPRECATEDIN_3_0 int WHIRLPOOL_Update(WHIRLPOOL_CTX *c,
+ const void *inp, size_t bytes);
+OSSL_DEPRECATEDIN_3_0 void WHIRLPOOL_BitUpdate(WHIRLPOOL_CTX *c,
+ const void *inp, size_t bits);
+OSSL_DEPRECATEDIN_3_0 int WHIRLPOOL_Final(unsigned char *md, WHIRLPOOL_CTX *c);
+OSSL_DEPRECATEDIN_3_0 unsigned char *WHIRLPOOL(const void *inp, size_t bytes,
+ unsigned char *md);
+# endif
+
+# ifdef __cplusplus
+}
+# endif
+# endif
+
+#endif
diff --git a/include/openssl/x509.h b/include/openssl/x509.h
new file mode 100644
index 00000000..db57a9bf
--- /dev/null
+++ b/include/openssl/x509.h
@@ -0,0 +1,1276 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\x509.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_X509_H
+# define OPENSSL_X509_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_X509_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/types.h>
+# include <openssl/symhacks.h>
+# include <openssl/buffer.h>
+# include <openssl/evp.h>
+# include <openssl/bio.h>
+# include <openssl/asn1.h>
+# include <openssl/safestack.h>
+# include <openssl/ec.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/rsa.h>
+# include <openssl/dsa.h>
+# include <openssl/dh.h>
+# endif
+
+# include <openssl/sha.h>
+# include <openssl/x509err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Needed stacks for types defined in other headers */
+SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME, X509_NAME, X509_NAME)
+#define sk_X509_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_sk_type(sk))
+#define sk_X509_NAME_value(sk, idx) ((X509_NAME *)OPENSSL_sk_value(ossl_check_const_X509_NAME_sk_type(sk), (idx)))
+#define sk_X509_NAME_new(cmp) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new(ossl_check_X509_NAME_compfunc_type(cmp)))
+#define sk_X509_NAME_new_null() ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_null())
+#define sk_X509_NAME_new_reserve(cmp, n) ((STACK_OF(X509_NAME) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_compfunc_type(cmp), (n)))
+#define sk_X509_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_sk_type(sk), (n))
+#define sk_X509_NAME_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_sk_type(sk))
+#define sk_X509_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_sk_type(sk))
+#define sk_X509_NAME_delete(sk, i) ((X509_NAME *)OPENSSL_sk_delete(ossl_check_X509_NAME_sk_type(sk), (i)))
+#define sk_X509_NAME_delete_ptr(sk, ptr) ((X509_NAME *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr)))
+#define sk_X509_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
+#define sk_X509_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
+#define sk_X509_NAME_pop(sk) ((X509_NAME *)OPENSSL_sk_pop(ossl_check_X509_NAME_sk_type(sk)))
+#define sk_X509_NAME_shift(sk) ((X509_NAME *)OPENSSL_sk_shift(ossl_check_X509_NAME_sk_type(sk)))
+#define sk_X509_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_sk_type(sk),ossl_check_X509_NAME_freefunc_type(freefunc))
+#define sk_X509_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), (idx))
+#define sk_X509_NAME_set(sk, idx, ptr) ((X509_NAME *)OPENSSL_sk_set(ossl_check_X509_NAME_sk_type(sk), (idx), ossl_check_X509_NAME_type(ptr)))
+#define sk_X509_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
+#define sk_X509_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr))
+#define sk_X509_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_type(ptr), pnum)
+#define sk_X509_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_sk_type(sk))
+#define sk_X509_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_sk_type(sk))
+#define sk_X509_NAME_dup(sk) ((STACK_OF(X509_NAME) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_sk_type(sk)))
+#define sk_X509_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_sk_type(sk), ossl_check_X509_NAME_copyfunc_type(copyfunc), ossl_check_X509_NAME_freefunc_type(freefunc)))
+#define sk_X509_NAME_set_cmp_func(sk, cmp) ((sk_X509_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_sk_type(sk), ossl_check_X509_NAME_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(X509, X509, X509)
+#define sk_X509_num(sk) OPENSSL_sk_num(ossl_check_const_X509_sk_type(sk))
+#define sk_X509_value(sk, idx) ((X509 *)OPENSSL_sk_value(ossl_check_const_X509_sk_type(sk), (idx)))
+#define sk_X509_new(cmp) ((STACK_OF(X509) *)OPENSSL_sk_new(ossl_check_X509_compfunc_type(cmp)))
+#define sk_X509_new_null() ((STACK_OF(X509) *)OPENSSL_sk_new_null())
+#define sk_X509_new_reserve(cmp, n) ((STACK_OF(X509) *)OPENSSL_sk_new_reserve(ossl_check_X509_compfunc_type(cmp), (n)))
+#define sk_X509_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_sk_type(sk), (n))
+#define sk_X509_free(sk) OPENSSL_sk_free(ossl_check_X509_sk_type(sk))
+#define sk_X509_zero(sk) OPENSSL_sk_zero(ossl_check_X509_sk_type(sk))
+#define sk_X509_delete(sk, i) ((X509 *)OPENSSL_sk_delete(ossl_check_X509_sk_type(sk), (i)))
+#define sk_X509_delete_ptr(sk, ptr) ((X509 *)OPENSSL_sk_delete_ptr(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr)))
+#define sk_X509_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
+#define sk_X509_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
+#define sk_X509_pop(sk) ((X509 *)OPENSSL_sk_pop(ossl_check_X509_sk_type(sk)))
+#define sk_X509_shift(sk) ((X509 *)OPENSSL_sk_shift(ossl_check_X509_sk_type(sk)))
+#define sk_X509_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_sk_type(sk),ossl_check_X509_freefunc_type(freefunc))
+#define sk_X509_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), (idx))
+#define sk_X509_set(sk, idx, ptr) ((X509 *)OPENSSL_sk_set(ossl_check_X509_sk_type(sk), (idx), ossl_check_X509_type(ptr)))
+#define sk_X509_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
+#define sk_X509_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr))
+#define sk_X509_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_sk_type(sk), ossl_check_X509_type(ptr), pnum)
+#define sk_X509_sort(sk) OPENSSL_sk_sort(ossl_check_X509_sk_type(sk))
+#define sk_X509_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_sk_type(sk))
+#define sk_X509_dup(sk) ((STACK_OF(X509) *)OPENSSL_sk_dup(ossl_check_const_X509_sk_type(sk)))
+#define sk_X509_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_sk_type(sk), ossl_check_X509_copyfunc_type(copyfunc), ossl_check_X509_freefunc_type(freefunc)))
+#define sk_X509_set_cmp_func(sk, cmp) ((sk_X509_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_sk_type(sk), ossl_check_X509_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(X509_REVOKED, X509_REVOKED, X509_REVOKED)
+#define sk_X509_REVOKED_num(sk) OPENSSL_sk_num(ossl_check_const_X509_REVOKED_sk_type(sk))
+#define sk_X509_REVOKED_value(sk, idx) ((X509_REVOKED *)OPENSSL_sk_value(ossl_check_const_X509_REVOKED_sk_type(sk), (idx)))
+#define sk_X509_REVOKED_new(cmp) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new(ossl_check_X509_REVOKED_compfunc_type(cmp)))
+#define sk_X509_REVOKED_new_null() ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_null())
+#define sk_X509_REVOKED_new_reserve(cmp, n) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_new_reserve(ossl_check_X509_REVOKED_compfunc_type(cmp), (n)))
+#define sk_X509_REVOKED_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_REVOKED_sk_type(sk), (n))
+#define sk_X509_REVOKED_free(sk) OPENSSL_sk_free(ossl_check_X509_REVOKED_sk_type(sk))
+#define sk_X509_REVOKED_zero(sk) OPENSSL_sk_zero(ossl_check_X509_REVOKED_sk_type(sk))
+#define sk_X509_REVOKED_delete(sk, i) ((X509_REVOKED *)OPENSSL_sk_delete(ossl_check_X509_REVOKED_sk_type(sk), (i)))
+#define sk_X509_REVOKED_delete_ptr(sk, ptr) ((X509_REVOKED *)OPENSSL_sk_delete_ptr(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr)))
+#define sk_X509_REVOKED_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
+#define sk_X509_REVOKED_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
+#define sk_X509_REVOKED_pop(sk) ((X509_REVOKED *)OPENSSL_sk_pop(ossl_check_X509_REVOKED_sk_type(sk)))
+#define sk_X509_REVOKED_shift(sk) ((X509_REVOKED *)OPENSSL_sk_shift(ossl_check_X509_REVOKED_sk_type(sk)))
+#define sk_X509_REVOKED_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_REVOKED_sk_type(sk),ossl_check_X509_REVOKED_freefunc_type(freefunc))
+#define sk_X509_REVOKED_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), (idx))
+#define sk_X509_REVOKED_set(sk, idx, ptr) ((X509_REVOKED *)OPENSSL_sk_set(ossl_check_X509_REVOKED_sk_type(sk), (idx), ossl_check_X509_REVOKED_type(ptr)))
+#define sk_X509_REVOKED_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
+#define sk_X509_REVOKED_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr))
+#define sk_X509_REVOKED_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_type(ptr), pnum)
+#define sk_X509_REVOKED_sort(sk) OPENSSL_sk_sort(ossl_check_X509_REVOKED_sk_type(sk))
+#define sk_X509_REVOKED_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_REVOKED_sk_type(sk))
+#define sk_X509_REVOKED_dup(sk) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_dup(ossl_check_const_X509_REVOKED_sk_type(sk)))
+#define sk_X509_REVOKED_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_REVOKED) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_copyfunc_type(copyfunc), ossl_check_X509_REVOKED_freefunc_type(freefunc)))
+#define sk_X509_REVOKED_set_cmp_func(sk, cmp) ((sk_X509_REVOKED_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_REVOKED_sk_type(sk), ossl_check_X509_REVOKED_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(X509_CRL, X509_CRL, X509_CRL)
+#define sk_X509_CRL_num(sk) OPENSSL_sk_num(ossl_check_const_X509_CRL_sk_type(sk))
+#define sk_X509_CRL_value(sk, idx) ((X509_CRL *)OPENSSL_sk_value(ossl_check_const_X509_CRL_sk_type(sk), (idx)))
+#define sk_X509_CRL_new(cmp) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new(ossl_check_X509_CRL_compfunc_type(cmp)))
+#define sk_X509_CRL_new_null() ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_null())
+#define sk_X509_CRL_new_reserve(cmp, n) ((STACK_OF(X509_CRL) *)OPENSSL_sk_new_reserve(ossl_check_X509_CRL_compfunc_type(cmp), (n)))
+#define sk_X509_CRL_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_CRL_sk_type(sk), (n))
+#define sk_X509_CRL_free(sk) OPENSSL_sk_free(ossl_check_X509_CRL_sk_type(sk))
+#define sk_X509_CRL_zero(sk) OPENSSL_sk_zero(ossl_check_X509_CRL_sk_type(sk))
+#define sk_X509_CRL_delete(sk, i) ((X509_CRL *)OPENSSL_sk_delete(ossl_check_X509_CRL_sk_type(sk), (i)))
+#define sk_X509_CRL_delete_ptr(sk, ptr) ((X509_CRL *)OPENSSL_sk_delete_ptr(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr)))
+#define sk_X509_CRL_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
+#define sk_X509_CRL_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
+#define sk_X509_CRL_pop(sk) ((X509_CRL *)OPENSSL_sk_pop(ossl_check_X509_CRL_sk_type(sk)))
+#define sk_X509_CRL_shift(sk) ((X509_CRL *)OPENSSL_sk_shift(ossl_check_X509_CRL_sk_type(sk)))
+#define sk_X509_CRL_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_CRL_sk_type(sk),ossl_check_X509_CRL_freefunc_type(freefunc))
+#define sk_X509_CRL_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), (idx))
+#define sk_X509_CRL_set(sk, idx, ptr) ((X509_CRL *)OPENSSL_sk_set(ossl_check_X509_CRL_sk_type(sk), (idx), ossl_check_X509_CRL_type(ptr)))
+#define sk_X509_CRL_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
+#define sk_X509_CRL_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr))
+#define sk_X509_CRL_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_type(ptr), pnum)
+#define sk_X509_CRL_sort(sk) OPENSSL_sk_sort(ossl_check_X509_CRL_sk_type(sk))
+#define sk_X509_CRL_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_CRL_sk_type(sk))
+#define sk_X509_CRL_dup(sk) ((STACK_OF(X509_CRL) *)OPENSSL_sk_dup(ossl_check_const_X509_CRL_sk_type(sk)))
+#define sk_X509_CRL_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_CRL) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_CRL_sk_type(sk), ossl_check_X509_CRL_copyfunc_type(copyfunc), ossl_check_X509_CRL_freefunc_type(freefunc)))
+#define sk_X509_CRL_set_cmp_func(sk, cmp) ((sk_X509_CRL_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_CRL_sk_type(sk), ossl_check_X509_CRL_compfunc_type(cmp)))
+
+
+/* Flags for X509_get_signature_info() */
+/* Signature info is valid */
+# define X509_SIG_INFO_VALID 0x1
+/* Signature is suitable for TLS use */
+# define X509_SIG_INFO_TLS 0x2
+
+# define X509_FILETYPE_PEM 1
+# define X509_FILETYPE_ASN1 2
+# define X509_FILETYPE_DEFAULT 3
+
+# define X509v3_KU_DIGITAL_SIGNATURE 0x0080
+# define X509v3_KU_NON_REPUDIATION 0x0040
+# define X509v3_KU_KEY_ENCIPHERMENT 0x0020
+# define X509v3_KU_DATA_ENCIPHERMENT 0x0010
+# define X509v3_KU_KEY_AGREEMENT 0x0008
+# define X509v3_KU_KEY_CERT_SIGN 0x0004
+# define X509v3_KU_CRL_SIGN 0x0002
+# define X509v3_KU_ENCIPHER_ONLY 0x0001
+# define X509v3_KU_DECIPHER_ONLY 0x8000
+# define X509v3_KU_UNDEF 0xffff
+
+struct X509_algor_st {
+ ASN1_OBJECT *algorithm;
+ ASN1_TYPE *parameter;
+} /* X509_ALGOR */ ;
+
+typedef STACK_OF(X509_ALGOR) X509_ALGORS;
+
+typedef struct X509_val_st {
+ ASN1_TIME *notBefore;
+ ASN1_TIME *notAfter;
+} X509_VAL;
+
+typedef struct X509_sig_st X509_SIG;
+
+typedef struct X509_name_entry_st X509_NAME_ENTRY;
+
+SKM_DEFINE_STACK_OF_INTERNAL(X509_NAME_ENTRY, X509_NAME_ENTRY, X509_NAME_ENTRY)
+#define sk_X509_NAME_ENTRY_num(sk) OPENSSL_sk_num(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
+#define sk_X509_NAME_ENTRY_value(sk, idx) ((X509_NAME_ENTRY *)OPENSSL_sk_value(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), (idx)))
+#define sk_X509_NAME_ENTRY_new(cmp) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
+#define sk_X509_NAME_ENTRY_new_null() ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_null())
+#define sk_X509_NAME_ENTRY_new_reserve(cmp, n) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_new_reserve(ossl_check_X509_NAME_ENTRY_compfunc_type(cmp), (n)))
+#define sk_X509_NAME_ENTRY_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_NAME_ENTRY_sk_type(sk), (n))
+#define sk_X509_NAME_ENTRY_free(sk) OPENSSL_sk_free(ossl_check_X509_NAME_ENTRY_sk_type(sk))
+#define sk_X509_NAME_ENTRY_zero(sk) OPENSSL_sk_zero(ossl_check_X509_NAME_ENTRY_sk_type(sk))
+#define sk_X509_NAME_ENTRY_delete(sk, i) ((X509_NAME_ENTRY *)OPENSSL_sk_delete(ossl_check_X509_NAME_ENTRY_sk_type(sk), (i)))
+#define sk_X509_NAME_ENTRY_delete_ptr(sk, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_delete_ptr(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr)))
+#define sk_X509_NAME_ENTRY_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
+#define sk_X509_NAME_ENTRY_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
+#define sk_X509_NAME_ENTRY_pop(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_pop(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
+#define sk_X509_NAME_ENTRY_shift(sk) ((X509_NAME_ENTRY *)OPENSSL_sk_shift(ossl_check_X509_NAME_ENTRY_sk_type(sk)))
+#define sk_X509_NAME_ENTRY_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_NAME_ENTRY_sk_type(sk),ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc))
+#define sk_X509_NAME_ENTRY_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), (idx))
+#define sk_X509_NAME_ENTRY_set(sk, idx, ptr) ((X509_NAME_ENTRY *)OPENSSL_sk_set(ossl_check_X509_NAME_ENTRY_sk_type(sk), (idx), ossl_check_X509_NAME_ENTRY_type(ptr)))
+#define sk_X509_NAME_ENTRY_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
+#define sk_X509_NAME_ENTRY_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr))
+#define sk_X509_NAME_ENTRY_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_type(ptr), pnum)
+#define sk_X509_NAME_ENTRY_sort(sk) OPENSSL_sk_sort(ossl_check_X509_NAME_ENTRY_sk_type(sk))
+#define sk_X509_NAME_ENTRY_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_NAME_ENTRY_sk_type(sk))
+#define sk_X509_NAME_ENTRY_dup(sk) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_dup(ossl_check_const_X509_NAME_ENTRY_sk_type(sk)))
+#define sk_X509_NAME_ENTRY_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_NAME_ENTRY) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_copyfunc_type(copyfunc), ossl_check_X509_NAME_ENTRY_freefunc_type(freefunc)))
+#define sk_X509_NAME_ENTRY_set_cmp_func(sk, cmp) ((sk_X509_NAME_ENTRY_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_NAME_ENTRY_sk_type(sk), ossl_check_X509_NAME_ENTRY_compfunc_type(cmp)))
+
+
+# define X509_EX_V_NETSCAPE_HACK 0x8000
+# define X509_EX_V_INIT 0x0001
+typedef struct X509_extension_st X509_EXTENSION;
+SKM_DEFINE_STACK_OF_INTERNAL(X509_EXTENSION, X509_EXTENSION, X509_EXTENSION)
+#define sk_X509_EXTENSION_num(sk) OPENSSL_sk_num(ossl_check_const_X509_EXTENSION_sk_type(sk))
+#define sk_X509_EXTENSION_value(sk, idx) ((X509_EXTENSION *)OPENSSL_sk_value(ossl_check_const_X509_EXTENSION_sk_type(sk), (idx)))
+#define sk_X509_EXTENSION_new(cmp) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new(ossl_check_X509_EXTENSION_compfunc_type(cmp)))
+#define sk_X509_EXTENSION_new_null() ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_null())
+#define sk_X509_EXTENSION_new_reserve(cmp, n) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_new_reserve(ossl_check_X509_EXTENSION_compfunc_type(cmp), (n)))
+#define sk_X509_EXTENSION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_EXTENSION_sk_type(sk), (n))
+#define sk_X509_EXTENSION_free(sk) OPENSSL_sk_free(ossl_check_X509_EXTENSION_sk_type(sk))
+#define sk_X509_EXTENSION_zero(sk) OPENSSL_sk_zero(ossl_check_X509_EXTENSION_sk_type(sk))
+#define sk_X509_EXTENSION_delete(sk, i) ((X509_EXTENSION *)OPENSSL_sk_delete(ossl_check_X509_EXTENSION_sk_type(sk), (i)))
+#define sk_X509_EXTENSION_delete_ptr(sk, ptr) ((X509_EXTENSION *)OPENSSL_sk_delete_ptr(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr)))
+#define sk_X509_EXTENSION_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
+#define sk_X509_EXTENSION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
+#define sk_X509_EXTENSION_pop(sk) ((X509_EXTENSION *)OPENSSL_sk_pop(ossl_check_X509_EXTENSION_sk_type(sk)))
+#define sk_X509_EXTENSION_shift(sk) ((X509_EXTENSION *)OPENSSL_sk_shift(ossl_check_X509_EXTENSION_sk_type(sk)))
+#define sk_X509_EXTENSION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_EXTENSION_sk_type(sk),ossl_check_X509_EXTENSION_freefunc_type(freefunc))
+#define sk_X509_EXTENSION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), (idx))
+#define sk_X509_EXTENSION_set(sk, idx, ptr) ((X509_EXTENSION *)OPENSSL_sk_set(ossl_check_X509_EXTENSION_sk_type(sk), (idx), ossl_check_X509_EXTENSION_type(ptr)))
+#define sk_X509_EXTENSION_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
+#define sk_X509_EXTENSION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr))
+#define sk_X509_EXTENSION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_type(ptr), pnum)
+#define sk_X509_EXTENSION_sort(sk) OPENSSL_sk_sort(ossl_check_X509_EXTENSION_sk_type(sk))
+#define sk_X509_EXTENSION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_EXTENSION_sk_type(sk))
+#define sk_X509_EXTENSION_dup(sk) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_dup(ossl_check_const_X509_EXTENSION_sk_type(sk)))
+#define sk_X509_EXTENSION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_EXTENSION) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_copyfunc_type(copyfunc), ossl_check_X509_EXTENSION_freefunc_type(freefunc)))
+#define sk_X509_EXTENSION_set_cmp_func(sk, cmp) ((sk_X509_EXTENSION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_EXTENSION_sk_type(sk), ossl_check_X509_EXTENSION_compfunc_type(cmp)))
+
+typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
+typedef struct x509_attributes_st X509_ATTRIBUTE;
+SKM_DEFINE_STACK_OF_INTERNAL(X509_ATTRIBUTE, X509_ATTRIBUTE, X509_ATTRIBUTE)
+#define sk_X509_ATTRIBUTE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
+#define sk_X509_ATTRIBUTE_value(sk, idx) ((X509_ATTRIBUTE *)OPENSSL_sk_value(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), (idx)))
+#define sk_X509_ATTRIBUTE_new(cmp) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
+#define sk_X509_ATTRIBUTE_new_null() ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_null())
+#define sk_X509_ATTRIBUTE_new_reserve(cmp, n) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_new_reserve(ossl_check_X509_ATTRIBUTE_compfunc_type(cmp), (n)))
+#define sk_X509_ATTRIBUTE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_ATTRIBUTE_sk_type(sk), (n))
+#define sk_X509_ATTRIBUTE_free(sk) OPENSSL_sk_free(ossl_check_X509_ATTRIBUTE_sk_type(sk))
+#define sk_X509_ATTRIBUTE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_ATTRIBUTE_sk_type(sk))
+#define sk_X509_ATTRIBUTE_delete(sk, i) ((X509_ATTRIBUTE *)OPENSSL_sk_delete(ossl_check_X509_ATTRIBUTE_sk_type(sk), (i)))
+#define sk_X509_ATTRIBUTE_delete_ptr(sk, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_delete_ptr(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr)))
+#define sk_X509_ATTRIBUTE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
+#define sk_X509_ATTRIBUTE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
+#define sk_X509_ATTRIBUTE_pop(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_pop(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
+#define sk_X509_ATTRIBUTE_shift(sk) ((X509_ATTRIBUTE *)OPENSSL_sk_shift(ossl_check_X509_ATTRIBUTE_sk_type(sk)))
+#define sk_X509_ATTRIBUTE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_ATTRIBUTE_sk_type(sk),ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc))
+#define sk_X509_ATTRIBUTE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), (idx))
+#define sk_X509_ATTRIBUTE_set(sk, idx, ptr) ((X509_ATTRIBUTE *)OPENSSL_sk_set(ossl_check_X509_ATTRIBUTE_sk_type(sk), (idx), ossl_check_X509_ATTRIBUTE_type(ptr)))
+#define sk_X509_ATTRIBUTE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
+#define sk_X509_ATTRIBUTE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr))
+#define sk_X509_ATTRIBUTE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_type(ptr), pnum)
+#define sk_X509_ATTRIBUTE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_ATTRIBUTE_sk_type(sk))
+#define sk_X509_ATTRIBUTE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_ATTRIBUTE_sk_type(sk))
+#define sk_X509_ATTRIBUTE_dup(sk) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_dup(ossl_check_const_X509_ATTRIBUTE_sk_type(sk)))
+#define sk_X509_ATTRIBUTE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_ATTRIBUTE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_copyfunc_type(copyfunc), ossl_check_X509_ATTRIBUTE_freefunc_type(freefunc)))
+#define sk_X509_ATTRIBUTE_set_cmp_func(sk, cmp) ((sk_X509_ATTRIBUTE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_ATTRIBUTE_sk_type(sk), ossl_check_X509_ATTRIBUTE_compfunc_type(cmp)))
+
+typedef struct X509_req_info_st X509_REQ_INFO;
+typedef struct X509_req_st X509_REQ;
+typedef struct x509_cert_aux_st X509_CERT_AUX;
+typedef struct x509_cinf_st X509_CINF;
+
+/* Flags for X509_print_ex() */
+
+# define X509_FLAG_COMPAT 0
+# define X509_FLAG_NO_HEADER 1L
+# define X509_FLAG_NO_VERSION (1L << 1)
+# define X509_FLAG_NO_SERIAL (1L << 2)
+# define X509_FLAG_NO_SIGNAME (1L << 3)
+# define X509_FLAG_NO_ISSUER (1L << 4)
+# define X509_FLAG_NO_VALIDITY (1L << 5)
+# define X509_FLAG_NO_SUBJECT (1L << 6)
+# define X509_FLAG_NO_PUBKEY (1L << 7)
+# define X509_FLAG_NO_EXTENSIONS (1L << 8)
+# define X509_FLAG_NO_SIGDUMP (1L << 9)
+# define X509_FLAG_NO_AUX (1L << 10)
+# define X509_FLAG_NO_ATTRIBUTES (1L << 11)
+# define X509_FLAG_NO_IDS (1L << 12)
+# define X509_FLAG_EXTENSIONS_ONLY_KID (1L << 13)
+
+/* Flags specific to X509_NAME_print_ex() */
+
+/* The field separator information */
+
+# define XN_FLAG_SEP_MASK (0xf << 16)
+
+# define XN_FLAG_COMPAT 0/* Traditional; use old X509_NAME_print */
+# define XN_FLAG_SEP_COMMA_PLUS (1 << 16)/* RFC2253 ,+ */
+# define XN_FLAG_SEP_CPLUS_SPC (2 << 16)/* ,+ spaced: more readable */
+# define XN_FLAG_SEP_SPLUS_SPC (3 << 16)/* ;+ spaced */
+# define XN_FLAG_SEP_MULTILINE (4 << 16)/* One line per field */
+
+# define XN_FLAG_DN_REV (1 << 20)/* Reverse DN order */
+
+/* How the field name is shown */
+
+# define XN_FLAG_FN_MASK (0x3 << 21)
+
+# define XN_FLAG_FN_SN 0/* Object short name */
+# define XN_FLAG_FN_LN (1 << 21)/* Object long name */
+# define XN_FLAG_FN_OID (2 << 21)/* Always use OIDs */
+# define XN_FLAG_FN_NONE (3 << 21)/* No field names */
+
+# define XN_FLAG_SPC_EQ (1 << 23)/* Put spaces round '=' */
+
+/*
+ * This determines if we dump fields we don't recognise: RFC2253 requires
+ * this.
+ */
+
+# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)
+
+# define XN_FLAG_FN_ALIGN (1 << 25)/* Align field names to 20
+ * characters */
+
+/* Complete set of RFC2253 flags */
+
+# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
+ XN_FLAG_SEP_COMMA_PLUS | \
+ XN_FLAG_DN_REV | \
+ XN_FLAG_FN_SN | \
+ XN_FLAG_DUMP_UNKNOWN_FIELDS)
+
+/* readable oneline form */
+
+# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
+ ASN1_STRFLGS_ESC_QUOTE | \
+ XN_FLAG_SEP_CPLUS_SPC | \
+ XN_FLAG_SPC_EQ | \
+ XN_FLAG_FN_SN)
+
+/* readable multiline form */
+
+# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
+ ASN1_STRFLGS_ESC_MSB | \
+ XN_FLAG_SEP_MULTILINE | \
+ XN_FLAG_SPC_EQ | \
+ XN_FLAG_FN_LN | \
+ XN_FLAG_FN_ALIGN)
+
+typedef struct X509_crl_info_st X509_CRL_INFO;
+
+typedef struct private_key_st {
+ int version;
+ /* The PKCS#8 data types */
+ X509_ALGOR *enc_algor;
+ ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
+ /* When decrypted, the following will not be NULL */
+ EVP_PKEY *dec_pkey;
+ /* used to encrypt and decrypt */
+ int key_length;
+ char *key_data;
+ int key_free; /* true if we should auto free key_data */
+ /* expanded version of 'enc_algor' */
+ EVP_CIPHER_INFO cipher;
+} X509_PKEY;
+
+typedef struct X509_info_st {
+ X509 *x509;
+ X509_CRL *crl;
+ X509_PKEY *x_pkey;
+ EVP_CIPHER_INFO enc_cipher;
+ int enc_len;
+ char *enc_data;
+} X509_INFO;
+SKM_DEFINE_STACK_OF_INTERNAL(X509_INFO, X509_INFO, X509_INFO)
+#define sk_X509_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_X509_INFO_sk_type(sk))
+#define sk_X509_INFO_value(sk, idx) ((X509_INFO *)OPENSSL_sk_value(ossl_check_const_X509_INFO_sk_type(sk), (idx)))
+#define sk_X509_INFO_new(cmp) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new(ossl_check_X509_INFO_compfunc_type(cmp)))
+#define sk_X509_INFO_new_null() ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_null())
+#define sk_X509_INFO_new_reserve(cmp, n) ((STACK_OF(X509_INFO) *)OPENSSL_sk_new_reserve(ossl_check_X509_INFO_compfunc_type(cmp), (n)))
+#define sk_X509_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_INFO_sk_type(sk), (n))
+#define sk_X509_INFO_free(sk) OPENSSL_sk_free(ossl_check_X509_INFO_sk_type(sk))
+#define sk_X509_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_X509_INFO_sk_type(sk))
+#define sk_X509_INFO_delete(sk, i) ((X509_INFO *)OPENSSL_sk_delete(ossl_check_X509_INFO_sk_type(sk), (i)))
+#define sk_X509_INFO_delete_ptr(sk, ptr) ((X509_INFO *)OPENSSL_sk_delete_ptr(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr)))
+#define sk_X509_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
+#define sk_X509_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
+#define sk_X509_INFO_pop(sk) ((X509_INFO *)OPENSSL_sk_pop(ossl_check_X509_INFO_sk_type(sk)))
+#define sk_X509_INFO_shift(sk) ((X509_INFO *)OPENSSL_sk_shift(ossl_check_X509_INFO_sk_type(sk)))
+#define sk_X509_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_INFO_sk_type(sk),ossl_check_X509_INFO_freefunc_type(freefunc))
+#define sk_X509_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), (idx))
+#define sk_X509_INFO_set(sk, idx, ptr) ((X509_INFO *)OPENSSL_sk_set(ossl_check_X509_INFO_sk_type(sk), (idx), ossl_check_X509_INFO_type(ptr)))
+#define sk_X509_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
+#define sk_X509_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr))
+#define sk_X509_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_type(ptr), pnum)
+#define sk_X509_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_X509_INFO_sk_type(sk))
+#define sk_X509_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_INFO_sk_type(sk))
+#define sk_X509_INFO_dup(sk) ((STACK_OF(X509_INFO) *)OPENSSL_sk_dup(ossl_check_const_X509_INFO_sk_type(sk)))
+#define sk_X509_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_INFO_sk_type(sk), ossl_check_X509_INFO_copyfunc_type(copyfunc), ossl_check_X509_INFO_freefunc_type(freefunc)))
+#define sk_X509_INFO_set_cmp_func(sk, cmp) ((sk_X509_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_INFO_sk_type(sk), ossl_check_X509_INFO_compfunc_type(cmp)))
+
+
+/*
+ * The next 2 structures and their 8 routines are used to manipulate Netscape's
+ * spki structures - useful if you are writing a CA web page
+ */
+typedef struct Netscape_spkac_st {
+ X509_PUBKEY *pubkey;
+ ASN1_IA5STRING *challenge; /* challenge sent in atlas >= PR2 */
+} NETSCAPE_SPKAC;
+
+typedef struct Netscape_spki_st {
+ NETSCAPE_SPKAC *spkac; /* signed public key and challenge */
+ X509_ALGOR sig_algor;
+ ASN1_BIT_STRING *signature;
+} NETSCAPE_SPKI;
+
+/* Netscape certificate sequence structure */
+typedef struct Netscape_certificate_sequence {
+ ASN1_OBJECT *type;
+ STACK_OF(X509) *certs;
+} NETSCAPE_CERT_SEQUENCE;
+
+/*- Unused (and iv length is wrong)
+typedef struct CBCParameter_st
+ {
+ unsigned char iv[8];
+ } CBC_PARAM;
+*/
+
+/* Password based encryption structure */
+
+typedef struct PBEPARAM_st {
+ ASN1_OCTET_STRING *salt;
+ ASN1_INTEGER *iter;
+} PBEPARAM;
+
+/* Password based encryption V2 structures */
+
+typedef struct PBE2PARAM_st {
+ X509_ALGOR *keyfunc;
+ X509_ALGOR *encryption;
+} PBE2PARAM;
+
+typedef struct PBKDF2PARAM_st {
+/* Usually OCTET STRING but could be anything */
+ ASN1_TYPE *salt;
+ ASN1_INTEGER *iter;
+ ASN1_INTEGER *keylength;
+ X509_ALGOR *prf;
+} PBKDF2PARAM;
+
+#ifndef OPENSSL_NO_SCRYPT
+typedef struct SCRYPT_PARAMS_st {
+ ASN1_OCTET_STRING *salt;
+ ASN1_INTEGER *costParameter;
+ ASN1_INTEGER *blockSize;
+ ASN1_INTEGER *parallelizationParameter;
+ ASN1_INTEGER *keyLength;
+} SCRYPT_PARAMS;
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+# include <openssl/x509_vfy.h>
+# include <openssl/pkcs7.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define X509_EXT_PACK_UNKNOWN 1
+# define X509_EXT_PACK_STRING 2
+
+# define X509_extract_key(x) X509_get_pubkey(x)/*****/
+# define X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
+# define X509_name_cmp(a,b) X509_NAME_cmp((a),(b))
+
+void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
+X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
+ int (*crl_free) (X509_CRL *crl),
+ int (*crl_lookup) (X509_CRL *crl,
+ X509_REVOKED **ret,
+ const
+ ASN1_INTEGER *serial,
+ const
+ X509_NAME *issuer),
+ int (*crl_verify) (X509_CRL *crl,
+ EVP_PKEY *pk));
+void X509_CRL_METHOD_free(X509_CRL_METHOD *m);
+
+void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
+void *X509_CRL_get_meth_data(X509_CRL *crl);
+
+const char *X509_verify_cert_error_string(long n);
+
+int X509_verify(X509 *a, EVP_PKEY *r);
+int X509_self_signed(X509 *cert, int verify_signature);
+
+int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
+int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
+int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);
+
+NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
+char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
+EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
+int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);
+
+int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);
+
+int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
+int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
+ const ASN1_STRING *sig);
+
+int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
+int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
+int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
+int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
+int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
+int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
+int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);
+
+int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+int X509_digest(const X509 *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
+ EVP_MD **md_used, int *md_is_fallback);
+int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+
+X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
+X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# include <openssl/ocsp.h> /* OCSP_REQ_CTX_nbio_d2i */
+# define X509_http_nbio(rctx, pcert) \
+ OCSP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
+# define X509_CRL_http_nbio(rctx, pcrl) \
+ OCSP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
+# endif
+
+# ifndef OPENSSL_NO_STDIO
+X509 *d2i_X509_fp(FILE *fp, X509 **x509);
+int i2d_X509_fp(FILE *fp, const X509 *x509);
+X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
+int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
+X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
+int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
+# endif
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
+# endif /* OPENSSL_NO_EC */
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
+int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
+X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
+int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
+PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
+ PKCS8_PRIV_KEY_INFO **p8inf);
+int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
+int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
+int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
+ const char *propq);
+EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
+int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
+# endif
+
+X509 *d2i_X509_bio(BIO *bp, X509 **x509);
+int i2d_X509_bio(BIO *bp, const X509 *x509);
+X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
+int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
+X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
+int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
+# endif /* OPENSSL_NO_EC */
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
+int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
+X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
+int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
+PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
+ PKCS8_PRIV_KEY_INFO **p8inf);
+int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
+int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
+int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
+ const char *propq);
+EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
+int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);
+
+DECLARE_ASN1_DUP_FUNCTION(X509)
+DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
+DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
+DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
+DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
+DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
+DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
+DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
+int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
+ void *pval);
+void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
+ const void **ppval, const X509_ALGOR *algor);
+void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
+int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
+int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);
+
+DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
+DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
+
+int X509_cmp_time(const ASN1_TIME *s, time_t *t);
+int X509_cmp_current_time(const ASN1_TIME *s);
+int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
+ const ASN1_TIME *start, const ASN1_TIME *end);
+ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
+ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
+ int offset_day, long offset_sec, time_t *t);
+ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);
+
+const char *X509_get_default_cert_area(void);
+const char *X509_get_default_cert_dir(void);
+const char *X509_get_default_cert_file(void);
+const char *X509_get_default_cert_dir_env(void);
+const char *X509_get_default_cert_file_env(void);
+const char *X509_get_default_private_dir(void);
+
+X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
+X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);
+
+DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
+DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
+DECLARE_ASN1_FUNCTIONS(X509_VAL)
+
+DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)
+
+X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
+EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
+EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
+int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
+long X509_get_pathlen(X509 *x);
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
+EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
+ OSSL_LIB_CTX *libctx, const char *propq);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
+# endif
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
+# endif
+# endif
+
+DECLARE_ASN1_FUNCTIONS(X509_SIG)
+void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
+ const ASN1_OCTET_STRING **pdigest);
+void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
+ ASN1_OCTET_STRING **pdigest);
+
+DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
+DECLARE_ASN1_FUNCTIONS(X509_REQ)
+X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
+X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);
+
+DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
+DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)
+
+DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)
+
+DECLARE_ASN1_FUNCTIONS(X509_NAME)
+
+int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);
+
+DECLARE_ASN1_FUNCTIONS(X509_CINF)
+DECLARE_ASN1_FUNCTIONS(X509)
+X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)
+
+#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
+int X509_set_ex_data(X509 *r, int idx, void *arg);
+void *X509_get_ex_data(const X509 *r, int idx);
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)
+
+int i2d_re_X509_tbs(X509 *x, unsigned char **pp);
+
+int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
+ int *secbits, uint32_t *flags);
+void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
+ int secbits, uint32_t flags);
+
+int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
+ uint32_t *flags);
+
+void X509_get0_signature(const ASN1_BIT_STRING **psig,
+ const X509_ALGOR **palg, const X509 *x);
+int X509_get_signature_nid(const X509 *x);
+
+void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
+ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
+void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
+ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);
+
+int X509_alias_set1(X509 *x, const unsigned char *name, int len);
+int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
+unsigned char *X509_alias_get0(X509 *x, int *len);
+unsigned char *X509_keyid_get0(X509 *x, int *len);
+
+DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
+DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
+DECLARE_ASN1_FUNCTIONS(X509_CRL)
+X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
+int X509_CRL_get0_by_serial(X509_CRL *crl,
+ X509_REVOKED **ret, const ASN1_INTEGER *serial);
+int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);
+
+X509_PKEY *X509_PKEY_new(void);
+void X509_PKEY_free(X509_PKEY *a);
+
+DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
+DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
+DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)
+
+X509_INFO *X509_INFO_new(void);
+void X509_INFO_free(X509_INFO *a);
+char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);
+
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
+ ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
+OSSL_DEPRECATEDIN_3_0
+int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
+ unsigned char *md, unsigned int *len);
+OSSL_DEPRECATEDIN_3_0
+int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
+ ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
+ const EVP_MD *type);
+#endif
+int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
+ unsigned char *md, unsigned int *len);
+int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
+ const ASN1_BIT_STRING *signature, const void *data,
+ EVP_PKEY *pkey);
+int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
+ const ASN1_BIT_STRING *signature, const void *data,
+ EVP_MD_CTX *ctx);
+int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
+ ASN1_BIT_STRING *signature, const void *data,
+ EVP_PKEY *pkey, const EVP_MD *md);
+int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
+ X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
+ const void *data, EVP_MD_CTX *ctx);
+
+#define X509_VERSION_1 0
+#define X509_VERSION_2 1
+#define X509_VERSION_3 2
+
+long X509_get_version(const X509 *x);
+int X509_set_version(X509 *x, long version);
+int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
+ASN1_INTEGER *X509_get_serialNumber(X509 *x);
+const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
+int X509_set_issuer_name(X509 *x, const X509_NAME *name);
+X509_NAME *X509_get_issuer_name(const X509 *a);
+int X509_set_subject_name(X509 *x, const X509_NAME *name);
+X509_NAME *X509_get_subject_name(const X509 *a);
+const ASN1_TIME * X509_get0_notBefore(const X509 *x);
+ASN1_TIME *X509_getm_notBefore(const X509 *x);
+int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
+const ASN1_TIME *X509_get0_notAfter(const X509 *x);
+ASN1_TIME *X509_getm_notAfter(const X509 *x);
+int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
+int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
+int X509_up_ref(X509 *x);
+int X509_get_signature_type(const X509 *x);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_get_notBefore X509_getm_notBefore
+# define X509_get_notAfter X509_getm_notAfter
+# define X509_set_notBefore X509_set1_notBefore
+# define X509_set_notAfter X509_set1_notAfter
+#endif
+
+
+/*
+ * This one is only used so that a binary form can output, as in
+ * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
+ */
+X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
+const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
+void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
+ const ASN1_BIT_STRING **psuid);
+const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);
+
+EVP_PKEY *X509_get0_pubkey(const X509 *x);
+EVP_PKEY *X509_get_pubkey(X509 *x);
+ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);
+
+#define X509_REQ_VERSION_1 0
+
+long X509_REQ_get_version(const X509_REQ *req);
+int X509_REQ_set_version(X509_REQ *x, long version);
+X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
+int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
+void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
+ const X509_ALGOR **palg);
+void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
+int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
+int X509_REQ_get_signature_nid(const X509_REQ *req);
+int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
+int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
+EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
+EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
+X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
+int X509_REQ_extension_nid(int nid);
+int *X509_REQ_get_extension_nids(void);
+void X509_REQ_set_extension_nids(int *nids);
+STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
+int X509_REQ_add_extensions_nid(X509_REQ *req,
+ const STACK_OF(X509_EXTENSION) *exts, int nid);
+int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
+int X509_REQ_get_attr_count(const X509_REQ *req);
+int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
+int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
+X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
+int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
+int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
+ const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes, int len);
+int X509_REQ_add1_attr_by_NID(X509_REQ *req,
+ int nid, int type,
+ const unsigned char *bytes, int len);
+int X509_REQ_add1_attr_by_txt(X509_REQ *req,
+ const char *attrname, int type,
+ const unsigned char *bytes, int len);
+
+#define X509_CRL_VERSION_1 0
+#define X509_CRL_VERSION_2 1
+
+int X509_CRL_set_version(X509_CRL *x, long version);
+int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
+int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
+int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
+int X509_CRL_sort(X509_CRL *crl);
+int X509_CRL_up_ref(X509_CRL *crl);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
+# define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
+#endif
+
+long X509_CRL_get_version(const X509_CRL *crl);
+const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
+const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
+OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
+#endif
+X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
+const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
+STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
+void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
+ const X509_ALGOR **palg);
+int X509_CRL_get_signature_nid(const X509_CRL *crl);
+int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);
+
+const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
+int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
+const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
+int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
+const STACK_OF(X509_EXTENSION) *
+X509_REVOKED_get0_extensions(const X509_REVOKED *r);
+
+X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
+ EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);
+
+int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);
+
+int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
+int X509_chain_check_suiteb(int *perror_depth,
+ X509 *x, STACK_OF(X509) *chain,
+ unsigned long flags);
+int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
+STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);
+
+int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
+unsigned long X509_issuer_and_serial_hash(X509 *a);
+
+int X509_issuer_name_cmp(const X509 *a, const X509 *b);
+unsigned long X509_issuer_name_hash(X509 *a);
+
+int X509_subject_name_cmp(const X509 *a, const X509 *b);
+unsigned long X509_subject_name_hash(X509 *x);
+
+# ifndef OPENSSL_NO_MD5
+unsigned long X509_issuer_name_hash_old(X509 *a);
+unsigned long X509_subject_name_hash_old(X509 *x);
+# endif
+
+# define X509_ADD_FLAG_DEFAULT 0
+# define X509_ADD_FLAG_UP_REF 0x1
+# define X509_ADD_FLAG_PREPEND 0x2
+# define X509_ADD_FLAG_NO_DUP 0x4
+# define X509_ADD_FLAG_NO_SS 0x8
+int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
+int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);
+
+int X509_cmp(const X509 *a, const X509 *b);
+int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
+OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
+ const EVP_PKEY *pubkey);
+#endif
+unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
+ const char *propq, int *ok);
+unsigned long X509_NAME_hash_old(const X509_NAME *x);
+
+int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
+int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
+int X509_aux_print(BIO *out, X509 *x, int indent);
+# ifndef OPENSSL_NO_STDIO
+int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
+ unsigned long cflag);
+int X509_print_fp(FILE *bp, X509 *x);
+int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
+int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
+int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
+ unsigned long flags);
+# endif
+
+int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
+int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
+ unsigned long flags);
+int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
+ unsigned long cflag);
+int X509_print(BIO *bp, X509 *x);
+int X509_ocspid_print(BIO *bp, X509 *x);
+int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
+int X509_CRL_print(BIO *bp, X509_CRL *x);
+int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
+ unsigned long cflag);
+int X509_REQ_print(BIO *bp, X509_REQ *req);
+
+int X509_NAME_entry_count(const X509_NAME *name);
+int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
+ char *buf, int len);
+int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
+ char *buf, int len);
+
+/*
+ * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
+ * lastpos, search after that position on.
+ */
+int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
+int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
+X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
+int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
+ int loc, int set);
+int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes, int len, int loc,
+ int set);
+int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
+ const unsigned char *bytes, int len, int loc,
+ int set);
+X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
+ const char *field, int type,
+ const unsigned char *bytes,
+ int len);
+X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
+ int type,
+ const unsigned char *bytes,
+ int len);
+int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
+ const unsigned char *bytes, int len, int loc,
+ int set);
+X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
+ const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes,
+ int len);
+int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
+int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
+ const unsigned char *bytes, int len);
+ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
+ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
+int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);
+
+int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
+ size_t *pderlen);
+
+int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
+int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
+ int nid, int lastpos);
+int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
+ const ASN1_OBJECT *obj, int lastpos);
+int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
+ int crit, int lastpos);
+X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
+X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
+STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
+ X509_EXTENSION *ex, int loc);
+
+int X509_get_ext_count(const X509 *x);
+int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
+int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
+int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
+X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
+X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
+int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
+void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
+int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
+ unsigned long flags);
+
+int X509_CRL_get_ext_count(const X509_CRL *x);
+int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
+int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
+X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
+X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
+int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
+void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
+int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
+ unsigned long flags);
+
+int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
+int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
+int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
+ int lastpos);
+X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
+X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
+int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
+void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
+ int *idx);
+int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
+ unsigned long flags);
+
+X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
+ int nid, int crit,
+ ASN1_OCTET_STRING *data);
+X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
+ const ASN1_OBJECT *obj, int crit,
+ ASN1_OCTET_STRING *data);
+int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
+int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
+int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
+ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
+ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
+int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);
+
+int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
+int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
+ int lastpos);
+int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
+ const ASN1_OBJECT *obj, int lastpos);
+X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
+X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
+ X509_ATTRIBUTE *attr);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
+ **x, const ASN1_OBJECT *obj,
+ int type,
+ const unsigned char *bytes,
+ int len);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
+ **x, int nid, int type,
+ const unsigned char *bytes,
+ int len);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
+ **x, const char *attrname,
+ int type,
+ const unsigned char *bytes,
+ int len);
+void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
+ const ASN1_OBJECT *obj, int lastpos, int type);
+X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
+ int atrtype, const void *data,
+ int len);
+X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
+ const ASN1_OBJECT *obj,
+ int atrtype, const void *data,
+ int len);
+X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
+ const char *atrname, int type,
+ const unsigned char *bytes,
+ int len);
+int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
+int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
+ const void *data, int len);
+void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
+ void *data);
+int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
+ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
+ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);
+
+int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
+int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
+int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
+X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
+int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
+int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
+ const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes, int len);
+int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
+ int nid, int type,
+ const unsigned char *bytes, int len);
+int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
+ const char *attrname, int type,
+ const unsigned char *bytes, int len);
+
+/* lookup a cert from a X509 STACK */
+X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
+ const ASN1_INTEGER *serial);
+X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);
+
+DECLARE_ASN1_FUNCTIONS(PBEPARAM)
+DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
+DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
+#ifndef OPENSSL_NO_SCRYPT
+DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
+#endif
+
+int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
+ const unsigned char *salt, int saltlen);
+int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
+ const unsigned char *salt, int saltlen,
+ OSSL_LIB_CTX *libctx);
+
+X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
+ const unsigned char *salt, int saltlen);
+X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
+ const unsigned char *salt, int saltlen,
+ OSSL_LIB_CTX *libctx);
+
+X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
+ unsigned char *salt, int saltlen);
+X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
+ unsigned char *salt, int saltlen,
+ unsigned char *aiv, int prf_nid);
+X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
+ unsigned char *salt, int saltlen,
+ unsigned char *aiv, int prf_nid,
+ OSSL_LIB_CTX *libctx);
+
+#ifndef OPENSSL_NO_SCRYPT
+X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
+ const unsigned char *salt, int saltlen,
+ unsigned char *aiv, uint64_t N, uint64_t r,
+ uint64_t p);
+#endif
+
+X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
+ int prf_nid, int keylen);
+X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
+ int prf_nid, int keylen,
+ OSSL_LIB_CTX *libctx);
+
+/* PKCS#8 utilities */
+
+DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)
+
+EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
+EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
+ const char *propq);
+PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);
+
+int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
+ int version, int ptype, void *pval,
+ unsigned char *penc, int penclen);
+int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
+ const unsigned char **pk, int *ppklen,
+ const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);
+
+const STACK_OF(X509_ATTRIBUTE) *
+PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
+int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
+int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
+ const unsigned char *bytes, int len);
+int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
+ int type, const unsigned char *bytes, int len);
+
+
+int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
+ int ptype, void *pval,
+ unsigned char *penc, int penclen);
+int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
+ const unsigned char **pk, int *ppklen,
+ X509_ALGOR **pa, const X509_PUBKEY *pub);
+int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/x509.h.in b/include/openssl/x509.h.in
new file mode 100644
index 00000000..b4efbb55
--- /dev/null
+++ b/include/openssl/x509.h.in
@@ -0,0 +1,1082 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_X509_H
+# define OPENSSL_X509_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_X509_H
+# endif
+
+# include <openssl/e_os2.h>
+# include <openssl/types.h>
+# include <openssl/symhacks.h>
+# include <openssl/buffer.h>
+# include <openssl/evp.h>
+# include <openssl/bio.h>
+# include <openssl/asn1.h>
+# include <openssl/safestack.h>
+# include <openssl/ec.h>
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# include <openssl/rsa.h>
+# include <openssl/dsa.h>
+# include <openssl/dh.h>
+# endif
+
+# include <openssl/sha.h>
+# include <openssl/x509err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Needed stacks for types defined in other headers */
+{-
+ generate_stack_macros("X509_NAME")
+ .generate_stack_macros("X509")
+ .generate_stack_macros("X509_REVOKED")
+ .generate_stack_macros("X509_CRL");
+-}
+
+/* Flags for X509_get_signature_info() */
+/* Signature info is valid */
+# define X509_SIG_INFO_VALID 0x1
+/* Signature is suitable for TLS use */
+# define X509_SIG_INFO_TLS 0x2
+
+# define X509_FILETYPE_PEM 1
+# define X509_FILETYPE_ASN1 2
+# define X509_FILETYPE_DEFAULT 3
+
+# define X509v3_KU_DIGITAL_SIGNATURE 0x0080
+# define X509v3_KU_NON_REPUDIATION 0x0040
+# define X509v3_KU_KEY_ENCIPHERMENT 0x0020
+# define X509v3_KU_DATA_ENCIPHERMENT 0x0010
+# define X509v3_KU_KEY_AGREEMENT 0x0008
+# define X509v3_KU_KEY_CERT_SIGN 0x0004
+# define X509v3_KU_CRL_SIGN 0x0002
+# define X509v3_KU_ENCIPHER_ONLY 0x0001
+# define X509v3_KU_DECIPHER_ONLY 0x8000
+# define X509v3_KU_UNDEF 0xffff
+
+struct X509_algor_st {
+ ASN1_OBJECT *algorithm;
+ ASN1_TYPE *parameter;
+} /* X509_ALGOR */ ;
+
+typedef STACK_OF(X509_ALGOR) X509_ALGORS;
+
+typedef struct X509_val_st {
+ ASN1_TIME *notBefore;
+ ASN1_TIME *notAfter;
+} X509_VAL;
+
+typedef struct X509_sig_st X509_SIG;
+
+typedef struct X509_name_entry_st X509_NAME_ENTRY;
+
+{-
+ generate_stack_macros("X509_NAME_ENTRY");
+-}
+
+# define X509_EX_V_NETSCAPE_HACK 0x8000
+# define X509_EX_V_INIT 0x0001
+typedef struct X509_extension_st X509_EXTENSION;
+{-
+ generate_stack_macros("X509_EXTENSION");
+-}
+typedef STACK_OF(X509_EXTENSION) X509_EXTENSIONS;
+typedef struct x509_attributes_st X509_ATTRIBUTE;
+{-
+ generate_stack_macros("X509_ATTRIBUTE");
+-}
+typedef struct X509_req_info_st X509_REQ_INFO;
+typedef struct X509_req_st X509_REQ;
+typedef struct x509_cert_aux_st X509_CERT_AUX;
+typedef struct x509_cinf_st X509_CINF;
+
+/* Flags for X509_print_ex() */
+
+# define X509_FLAG_COMPAT 0
+# define X509_FLAG_NO_HEADER 1L
+# define X509_FLAG_NO_VERSION (1L << 1)
+# define X509_FLAG_NO_SERIAL (1L << 2)
+# define X509_FLAG_NO_SIGNAME (1L << 3)
+# define X509_FLAG_NO_ISSUER (1L << 4)
+# define X509_FLAG_NO_VALIDITY (1L << 5)
+# define X509_FLAG_NO_SUBJECT (1L << 6)
+# define X509_FLAG_NO_PUBKEY (1L << 7)
+# define X509_FLAG_NO_EXTENSIONS (1L << 8)
+# define X509_FLAG_NO_SIGDUMP (1L << 9)
+# define X509_FLAG_NO_AUX (1L << 10)
+# define X509_FLAG_NO_ATTRIBUTES (1L << 11)
+# define X509_FLAG_NO_IDS (1L << 12)
+# define X509_FLAG_EXTENSIONS_ONLY_KID (1L << 13)
+
+/* Flags specific to X509_NAME_print_ex() */
+
+/* The field separator information */
+
+# define XN_FLAG_SEP_MASK (0xf << 16)
+
+# define XN_FLAG_COMPAT 0/* Traditional; use old X509_NAME_print */
+# define XN_FLAG_SEP_COMMA_PLUS (1 << 16)/* RFC2253 ,+ */
+# define XN_FLAG_SEP_CPLUS_SPC (2 << 16)/* ,+ spaced: more readable */
+# define XN_FLAG_SEP_SPLUS_SPC (3 << 16)/* ;+ spaced */
+# define XN_FLAG_SEP_MULTILINE (4 << 16)/* One line per field */
+
+# define XN_FLAG_DN_REV (1 << 20)/* Reverse DN order */
+
+/* How the field name is shown */
+
+# define XN_FLAG_FN_MASK (0x3 << 21)
+
+# define XN_FLAG_FN_SN 0/* Object short name */
+# define XN_FLAG_FN_LN (1 << 21)/* Object long name */
+# define XN_FLAG_FN_OID (2 << 21)/* Always use OIDs */
+# define XN_FLAG_FN_NONE (3 << 21)/* No field names */
+
+# define XN_FLAG_SPC_EQ (1 << 23)/* Put spaces round '=' */
+
+/*
+ * This determines if we dump fields we don't recognise: RFC2253 requires
+ * this.
+ */
+
+# define XN_FLAG_DUMP_UNKNOWN_FIELDS (1 << 24)
+
+# define XN_FLAG_FN_ALIGN (1 << 25)/* Align field names to 20
+ * characters */
+
+/* Complete set of RFC2253 flags */
+
+# define XN_FLAG_RFC2253 (ASN1_STRFLGS_RFC2253 | \
+ XN_FLAG_SEP_COMMA_PLUS | \
+ XN_FLAG_DN_REV | \
+ XN_FLAG_FN_SN | \
+ XN_FLAG_DUMP_UNKNOWN_FIELDS)
+
+/* readable oneline form */
+
+# define XN_FLAG_ONELINE (ASN1_STRFLGS_RFC2253 | \
+ ASN1_STRFLGS_ESC_QUOTE | \
+ XN_FLAG_SEP_CPLUS_SPC | \
+ XN_FLAG_SPC_EQ | \
+ XN_FLAG_FN_SN)
+
+/* readable multiline form */
+
+# define XN_FLAG_MULTILINE (ASN1_STRFLGS_ESC_CTRL | \
+ ASN1_STRFLGS_ESC_MSB | \
+ XN_FLAG_SEP_MULTILINE | \
+ XN_FLAG_SPC_EQ | \
+ XN_FLAG_FN_LN | \
+ XN_FLAG_FN_ALIGN)
+
+typedef struct X509_crl_info_st X509_CRL_INFO;
+
+typedef struct private_key_st {
+ int version;
+ /* The PKCS#8 data types */
+ X509_ALGOR *enc_algor;
+ ASN1_OCTET_STRING *enc_pkey; /* encrypted pub key */
+ /* When decrypted, the following will not be NULL */
+ EVP_PKEY *dec_pkey;
+ /* used to encrypt and decrypt */
+ int key_length;
+ char *key_data;
+ int key_free; /* true if we should auto free key_data */
+ /* expanded version of 'enc_algor' */
+ EVP_CIPHER_INFO cipher;
+} X509_PKEY;
+
+typedef struct X509_info_st {
+ X509 *x509;
+ X509_CRL *crl;
+ X509_PKEY *x_pkey;
+ EVP_CIPHER_INFO enc_cipher;
+ int enc_len;
+ char *enc_data;
+} X509_INFO;
+{-
+ generate_stack_macros("X509_INFO");
+-}
+
+/*
+ * The next 2 structures and their 8 routines are used to manipulate Netscape's
+ * spki structures - useful if you are writing a CA web page
+ */
+typedef struct Netscape_spkac_st {
+ X509_PUBKEY *pubkey;
+ ASN1_IA5STRING *challenge; /* challenge sent in atlas >= PR2 */
+} NETSCAPE_SPKAC;
+
+typedef struct Netscape_spki_st {
+ NETSCAPE_SPKAC *spkac; /* signed public key and challenge */
+ X509_ALGOR sig_algor;
+ ASN1_BIT_STRING *signature;
+} NETSCAPE_SPKI;
+
+/* Netscape certificate sequence structure */
+typedef struct Netscape_certificate_sequence {
+ ASN1_OBJECT *type;
+ STACK_OF(X509) *certs;
+} NETSCAPE_CERT_SEQUENCE;
+
+/*- Unused (and iv length is wrong)
+typedef struct CBCParameter_st
+ {
+ unsigned char iv[8];
+ } CBC_PARAM;
+*/
+
+/* Password based encryption structure */
+
+typedef struct PBEPARAM_st {
+ ASN1_OCTET_STRING *salt;
+ ASN1_INTEGER *iter;
+} PBEPARAM;
+
+/* Password based encryption V2 structures */
+
+typedef struct PBE2PARAM_st {
+ X509_ALGOR *keyfunc;
+ X509_ALGOR *encryption;
+} PBE2PARAM;
+
+typedef struct PBKDF2PARAM_st {
+/* Usually OCTET STRING but could be anything */
+ ASN1_TYPE *salt;
+ ASN1_INTEGER *iter;
+ ASN1_INTEGER *keylength;
+ X509_ALGOR *prf;
+} PBKDF2PARAM;
+
+#ifndef OPENSSL_NO_SCRYPT
+typedef struct SCRYPT_PARAMS_st {
+ ASN1_OCTET_STRING *salt;
+ ASN1_INTEGER *costParameter;
+ ASN1_INTEGER *blockSize;
+ ASN1_INTEGER *parallelizationParameter;
+ ASN1_INTEGER *keyLength;
+} SCRYPT_PARAMS;
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+# include <openssl/x509_vfy.h>
+# include <openssl/pkcs7.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+# define X509_EXT_PACK_UNKNOWN 1
+# define X509_EXT_PACK_STRING 2
+
+# define X509_extract_key(x) X509_get_pubkey(x)/*****/
+# define X509_REQ_extract_key(a) X509_REQ_get_pubkey(a)
+# define X509_name_cmp(a,b) X509_NAME_cmp((a),(b))
+
+void X509_CRL_set_default_method(const X509_CRL_METHOD *meth);
+X509_CRL_METHOD *X509_CRL_METHOD_new(int (*crl_init) (X509_CRL *crl),
+ int (*crl_free) (X509_CRL *crl),
+ int (*crl_lookup) (X509_CRL *crl,
+ X509_REVOKED **ret,
+ const
+ ASN1_INTEGER *serial,
+ const
+ X509_NAME *issuer),
+ int (*crl_verify) (X509_CRL *crl,
+ EVP_PKEY *pk));
+void X509_CRL_METHOD_free(X509_CRL_METHOD *m);
+
+void X509_CRL_set_meth_data(X509_CRL *crl, void *dat);
+void *X509_CRL_get_meth_data(X509_CRL *crl);
+
+const char *X509_verify_cert_error_string(long n);
+
+int X509_verify(X509 *a, EVP_PKEY *r);
+int X509_self_signed(X509 *cert, int verify_signature);
+
+int X509_REQ_verify_ex(X509_REQ *a, EVP_PKEY *r, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int X509_REQ_verify(X509_REQ *a, EVP_PKEY *r);
+int X509_CRL_verify(X509_CRL *a, EVP_PKEY *r);
+int NETSCAPE_SPKI_verify(NETSCAPE_SPKI *a, EVP_PKEY *r);
+
+NETSCAPE_SPKI *NETSCAPE_SPKI_b64_decode(const char *str, int len);
+char *NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *x);
+EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x);
+int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey);
+
+int NETSCAPE_SPKI_print(BIO *out, NETSCAPE_SPKI *spki);
+
+int X509_signature_dump(BIO *bp, const ASN1_STRING *sig, int indent);
+int X509_signature_print(BIO *bp, const X509_ALGOR *alg,
+ const ASN1_STRING *sig);
+
+int X509_sign(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
+int X509_sign_ctx(X509 *x, EVP_MD_CTX *ctx);
+int X509_REQ_sign(X509_REQ *x, EVP_PKEY *pkey, const EVP_MD *md);
+int X509_REQ_sign_ctx(X509_REQ *x, EVP_MD_CTX *ctx);
+int X509_CRL_sign(X509_CRL *x, EVP_PKEY *pkey, const EVP_MD *md);
+int X509_CRL_sign_ctx(X509_CRL *x, EVP_MD_CTX *ctx);
+int NETSCAPE_SPKI_sign(NETSCAPE_SPKI *x, EVP_PKEY *pkey, const EVP_MD *md);
+
+int X509_pubkey_digest(const X509 *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+int X509_digest(const X509 *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+ASN1_OCTET_STRING *X509_digest_sig(const X509 *cert,
+ EVP_MD **md_used, int *md_is_fallback);
+int X509_CRL_digest(const X509_CRL *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+int X509_REQ_digest(const X509_REQ *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+int X509_NAME_digest(const X509_NAME *data, const EVP_MD *type,
+ unsigned char *md, unsigned int *len);
+
+X509 *X509_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
+X509_CRL *X509_CRL_load_http(const char *url, BIO *bio, BIO *rbio, int timeout);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# include <openssl/ocsp.h> /* OCSP_REQ_CTX_nbio_d2i */
+# define X509_http_nbio(rctx, pcert) \
+ OCSP_REQ_CTX_nbio_d2i(rctx, pcert, ASN1_ITEM_rptr(X509))
+# define X509_CRL_http_nbio(rctx, pcrl) \
+ OCSP_REQ_CTX_nbio_d2i(rctx, pcrl, ASN1_ITEM_rptr(X509_CRL))
+# endif
+
+# ifndef OPENSSL_NO_STDIO
+X509 *d2i_X509_fp(FILE *fp, X509 **x509);
+int i2d_X509_fp(FILE *fp, const X509 *x509);
+X509_CRL *d2i_X509_CRL_fp(FILE *fp, X509_CRL **crl);
+int i2d_X509_CRL_fp(FILE *fp, const X509_CRL *crl);
+X509_REQ *d2i_X509_REQ_fp(FILE *fp, X509_REQ **req);
+int i2d_X509_REQ_fp(FILE *fp, const X509_REQ *req);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_fp(FILE *fp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_fp(FILE *fp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_fp(FILE *fp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_fp(FILE *fp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_fp(FILE *fp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_fp(FILE *fp, const RSA *rsa);
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_fp(FILE *fp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_fp(FILE *fp, const DSA *dsa);
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_fp(FILE *fp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_fp(FILE *fp, const DSA *dsa);
+# endif
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_fp(FILE *fp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_fp(FILE *fp, const EC_KEY *eckey);
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_fp(FILE *fp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_fp(FILE *fp, const EC_KEY *eckey);
+# endif /* OPENSSL_NO_EC */
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+X509_SIG *d2i_PKCS8_fp(FILE *fp, X509_SIG **p8);
+int i2d_PKCS8_fp(FILE *fp, const X509_SIG *p8);
+X509_PUBKEY *d2i_X509_PUBKEY_fp(FILE *fp, X509_PUBKEY **xpk);
+int i2d_X509_PUBKEY_fp(FILE *fp, const X509_PUBKEY *xpk);
+PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_fp(FILE *fp,
+ PKCS8_PRIV_KEY_INFO **p8inf);
+int i2d_PKCS8_PRIV_KEY_INFO_fp(FILE *fp, const PKCS8_PRIV_KEY_INFO *p8inf);
+int i2d_PKCS8PrivateKeyInfo_fp(FILE *fp, const EVP_PKEY *key);
+int i2d_PrivateKey_fp(FILE *fp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PrivateKey_ex_fp(FILE *fp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
+ const char *propq);
+EVP_PKEY *d2i_PrivateKey_fp(FILE *fp, EVP_PKEY **a);
+int i2d_PUBKEY_fp(FILE *fp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PUBKEY_fp(FILE *fp, EVP_PKEY **a);
+# endif
+
+X509 *d2i_X509_bio(BIO *bp, X509 **x509);
+int i2d_X509_bio(BIO *bp, const X509 *x509);
+X509_CRL *d2i_X509_CRL_bio(BIO *bp, X509_CRL **crl);
+int i2d_X509_CRL_bio(BIO *bp, const X509_CRL *crl);
+X509_REQ *d2i_X509_REQ_bio(BIO *bp, X509_REQ **req);
+int i2d_X509_REQ_bio(BIO *bp, const X509_REQ *req);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPrivateKey_bio(BIO *bp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPrivateKey_bio(BIO *bp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSAPublicKey_bio(BIO *bp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSAPublicKey_bio(BIO *bp, const RSA *rsa);
+OSSL_DEPRECATEDIN_3_0 RSA *d2i_RSA_PUBKEY_bio(BIO *bp, RSA **rsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_RSA_PUBKEY_bio(BIO *bp, const RSA *rsa);
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSA_PUBKEY_bio(BIO *bp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSA_PUBKEY_bio(BIO *bp, const DSA *dsa);
+OSSL_DEPRECATEDIN_3_0 DSA *d2i_DSAPrivateKey_bio(BIO *bp, DSA **dsa);
+OSSL_DEPRECATEDIN_3_0 int i2d_DSAPrivateKey_bio(BIO *bp, const DSA *dsa);
+# endif
+# endif
+
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_EC_PUBKEY_bio(BIO *bp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_EC_PUBKEY_bio(BIO *bp, const EC_KEY *eckey);
+OSSL_DEPRECATEDIN_3_0 EC_KEY *d2i_ECPrivateKey_bio(BIO *bp, EC_KEY **eckey);
+OSSL_DEPRECATEDIN_3_0 int i2d_ECPrivateKey_bio(BIO *bp, const EC_KEY *eckey);
+# endif /* OPENSSL_NO_EC */
+# endif /* OPENSSL_NO_DEPRECATED_3_0 */
+
+X509_SIG *d2i_PKCS8_bio(BIO *bp, X509_SIG **p8);
+int i2d_PKCS8_bio(BIO *bp, const X509_SIG *p8);
+X509_PUBKEY *d2i_X509_PUBKEY_bio(BIO *bp, X509_PUBKEY **xpk);
+int i2d_X509_PUBKEY_bio(BIO *bp, const X509_PUBKEY *xpk);
+PKCS8_PRIV_KEY_INFO *d2i_PKCS8_PRIV_KEY_INFO_bio(BIO *bp,
+ PKCS8_PRIV_KEY_INFO **p8inf);
+int i2d_PKCS8_PRIV_KEY_INFO_bio(BIO *bp, const PKCS8_PRIV_KEY_INFO *p8inf);
+int i2d_PKCS8PrivateKeyInfo_bio(BIO *bp, const EVP_PKEY *key);
+int i2d_PrivateKey_bio(BIO *bp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PrivateKey_ex_bio(BIO *bp, EVP_PKEY **a, OSSL_LIB_CTX *libctx,
+ const char *propq);
+EVP_PKEY *d2i_PrivateKey_bio(BIO *bp, EVP_PKEY **a);
+int i2d_PUBKEY_bio(BIO *bp, const EVP_PKEY *pkey);
+EVP_PKEY *d2i_PUBKEY_bio(BIO *bp, EVP_PKEY **a);
+
+DECLARE_ASN1_DUP_FUNCTION(X509)
+DECLARE_ASN1_DUP_FUNCTION(X509_ALGOR)
+DECLARE_ASN1_DUP_FUNCTION(X509_ATTRIBUTE)
+DECLARE_ASN1_DUP_FUNCTION(X509_CRL)
+DECLARE_ASN1_DUP_FUNCTION(X509_EXTENSION)
+DECLARE_ASN1_DUP_FUNCTION(X509_PUBKEY)
+DECLARE_ASN1_DUP_FUNCTION(X509_REQ)
+DECLARE_ASN1_DUP_FUNCTION(X509_REVOKED)
+int X509_ALGOR_set0(X509_ALGOR *alg, ASN1_OBJECT *aobj, int ptype,
+ void *pval);
+void X509_ALGOR_get0(const ASN1_OBJECT **paobj, int *pptype,
+ const void **ppval, const X509_ALGOR *algor);
+void X509_ALGOR_set_md(X509_ALGOR *alg, const EVP_MD *md);
+int X509_ALGOR_cmp(const X509_ALGOR *a, const X509_ALGOR *b);
+int X509_ALGOR_copy(X509_ALGOR *dest, const X509_ALGOR *src);
+
+DECLARE_ASN1_DUP_FUNCTION(X509_NAME)
+DECLARE_ASN1_DUP_FUNCTION(X509_NAME_ENTRY)
+
+int X509_cmp_time(const ASN1_TIME *s, time_t *t);
+int X509_cmp_current_time(const ASN1_TIME *s);
+int X509_cmp_timeframe(const X509_VERIFY_PARAM *vpm,
+ const ASN1_TIME *start, const ASN1_TIME *end);
+ASN1_TIME *X509_time_adj(ASN1_TIME *s, long adj, time_t *t);
+ASN1_TIME *X509_time_adj_ex(ASN1_TIME *s,
+ int offset_day, long offset_sec, time_t *t);
+ASN1_TIME *X509_gmtime_adj(ASN1_TIME *s, long adj);
+
+const char *X509_get_default_cert_area(void);
+const char *X509_get_default_cert_dir(void);
+const char *X509_get_default_cert_file(void);
+const char *X509_get_default_cert_dir_env(void);
+const char *X509_get_default_cert_file_env(void);
+const char *X509_get_default_private_dir(void);
+
+X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey, const EVP_MD *md);
+X509 *X509_REQ_to_X509(X509_REQ *r, int days, EVP_PKEY *pkey);
+
+DECLARE_ASN1_FUNCTIONS(X509_ALGOR)
+DECLARE_ASN1_ENCODE_FUNCTIONS(X509_ALGORS, X509_ALGORS, X509_ALGORS)
+DECLARE_ASN1_FUNCTIONS(X509_VAL)
+
+DECLARE_ASN1_FUNCTIONS(X509_PUBKEY)
+
+X509_PUBKEY *X509_PUBKEY_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+int X509_PUBKEY_set(X509_PUBKEY **x, EVP_PKEY *pkey);
+EVP_PKEY *X509_PUBKEY_get0(const X509_PUBKEY *key);
+EVP_PKEY *X509_PUBKEY_get(const X509_PUBKEY *key);
+int X509_get_pubkey_parameters(EVP_PKEY *pkey, STACK_OF(X509) *chain);
+long X509_get_pathlen(X509 *x);
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(EVP_PKEY, PUBKEY)
+EVP_PKEY *d2i_PUBKEY_ex(EVP_PKEY **a, const unsigned char **pp, long length,
+ OSSL_LIB_CTX *libctx, const char *propq);
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,RSA, RSA_PUBKEY)
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_DSA
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0,DSA, DSA_PUBKEY)
+# endif
+# endif
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# ifndef OPENSSL_NO_EC
+DECLARE_ASN1_ENCODE_FUNCTIONS_only_attr(OSSL_DEPRECATEDIN_3_0, EC_KEY, EC_PUBKEY)
+# endif
+# endif
+
+DECLARE_ASN1_FUNCTIONS(X509_SIG)
+void X509_SIG_get0(const X509_SIG *sig, const X509_ALGOR **palg,
+ const ASN1_OCTET_STRING **pdigest);
+void X509_SIG_getm(X509_SIG *sig, X509_ALGOR **palg,
+ ASN1_OCTET_STRING **pdigest);
+
+DECLARE_ASN1_FUNCTIONS(X509_REQ_INFO)
+DECLARE_ASN1_FUNCTIONS(X509_REQ)
+X509_REQ *X509_REQ_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+DECLARE_ASN1_FUNCTIONS(X509_ATTRIBUTE)
+X509_ATTRIBUTE *X509_ATTRIBUTE_create(int nid, int atrtype, void *value);
+
+DECLARE_ASN1_FUNCTIONS(X509_EXTENSION)
+DECLARE_ASN1_ENCODE_FUNCTIONS(X509_EXTENSIONS, X509_EXTENSIONS, X509_EXTENSIONS)
+
+DECLARE_ASN1_FUNCTIONS(X509_NAME_ENTRY)
+
+DECLARE_ASN1_FUNCTIONS(X509_NAME)
+
+int X509_NAME_set(X509_NAME **xn, const X509_NAME *name);
+
+DECLARE_ASN1_FUNCTIONS(X509_CINF)
+DECLARE_ASN1_FUNCTIONS(X509)
+X509 *X509_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+DECLARE_ASN1_FUNCTIONS(X509_CERT_AUX)
+
+#define X509_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509, l, p, newf, dupf, freef)
+int X509_set_ex_data(X509 *r, int idx, void *arg);
+void *X509_get_ex_data(const X509 *r, int idx);
+DECLARE_ASN1_ENCODE_FUNCTIONS_only(X509,X509_AUX)
+
+int i2d_re_X509_tbs(X509 *x, unsigned char **pp);
+
+int X509_SIG_INFO_get(const X509_SIG_INFO *siginf, int *mdnid, int *pknid,
+ int *secbits, uint32_t *flags);
+void X509_SIG_INFO_set(X509_SIG_INFO *siginf, int mdnid, int pknid,
+ int secbits, uint32_t flags);
+
+int X509_get_signature_info(X509 *x, int *mdnid, int *pknid, int *secbits,
+ uint32_t *flags);
+
+void X509_get0_signature(const ASN1_BIT_STRING **psig,
+ const X509_ALGOR **palg, const X509 *x);
+int X509_get_signature_nid(const X509 *x);
+
+void X509_set0_distinguishing_id(X509 *x, ASN1_OCTET_STRING *d_id);
+ASN1_OCTET_STRING *X509_get0_distinguishing_id(X509 *x);
+void X509_REQ_set0_distinguishing_id(X509_REQ *x, ASN1_OCTET_STRING *d_id);
+ASN1_OCTET_STRING *X509_REQ_get0_distinguishing_id(X509_REQ *x);
+
+int X509_alias_set1(X509 *x, const unsigned char *name, int len);
+int X509_keyid_set1(X509 *x, const unsigned char *id, int len);
+unsigned char *X509_alias_get0(X509 *x, int *len);
+unsigned char *X509_keyid_get0(X509 *x, int *len);
+
+DECLARE_ASN1_FUNCTIONS(X509_REVOKED)
+DECLARE_ASN1_FUNCTIONS(X509_CRL_INFO)
+DECLARE_ASN1_FUNCTIONS(X509_CRL)
+X509_CRL *X509_CRL_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+
+int X509_CRL_add0_revoked(X509_CRL *crl, X509_REVOKED *rev);
+int X509_CRL_get0_by_serial(X509_CRL *crl,
+ X509_REVOKED **ret, const ASN1_INTEGER *serial);
+int X509_CRL_get0_by_cert(X509_CRL *crl, X509_REVOKED **ret, X509 *x);
+
+X509_PKEY *X509_PKEY_new(void);
+void X509_PKEY_free(X509_PKEY *a);
+
+DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKI)
+DECLARE_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
+DECLARE_ASN1_FUNCTIONS(NETSCAPE_CERT_SEQUENCE)
+
+X509_INFO *X509_INFO_new(void);
+void X509_INFO_free(X509_INFO *a);
+char *X509_NAME_oneline(const X509_NAME *a, char *buf, int size);
+
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+OSSL_DEPRECATEDIN_3_0
+int ASN1_verify(i2d_of_void *i2d, X509_ALGOR *algor1,
+ ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey);
+OSSL_DEPRECATEDIN_3_0
+int ASN1_digest(i2d_of_void *i2d, const EVP_MD *type, char *data,
+ unsigned char *md, unsigned int *len);
+OSSL_DEPRECATEDIN_3_0
+int ASN1_sign(i2d_of_void *i2d, X509_ALGOR *algor1, X509_ALGOR *algor2,
+ ASN1_BIT_STRING *signature, char *data, EVP_PKEY *pkey,
+ const EVP_MD *type);
+#endif
+int ASN1_item_digest(const ASN1_ITEM *it, const EVP_MD *type, void *data,
+ unsigned char *md, unsigned int *len);
+int ASN1_item_verify(const ASN1_ITEM *it, const X509_ALGOR *alg,
+ const ASN1_BIT_STRING *signature, const void *data,
+ EVP_PKEY *pkey);
+int ASN1_item_verify_ctx(const ASN1_ITEM *it, const X509_ALGOR *alg,
+ const ASN1_BIT_STRING *signature, const void *data,
+ EVP_MD_CTX *ctx);
+int ASN1_item_sign(const ASN1_ITEM *it, X509_ALGOR *algor1, X509_ALGOR *algor2,
+ ASN1_BIT_STRING *signature, const void *data,
+ EVP_PKEY *pkey, const EVP_MD *md);
+int ASN1_item_sign_ctx(const ASN1_ITEM *it, X509_ALGOR *algor1,
+ X509_ALGOR *algor2, ASN1_BIT_STRING *signature,
+ const void *data, EVP_MD_CTX *ctx);
+
+#define X509_VERSION_1 0
+#define X509_VERSION_2 1
+#define X509_VERSION_3 2
+
+long X509_get_version(const X509 *x);
+int X509_set_version(X509 *x, long version);
+int X509_set_serialNumber(X509 *x, ASN1_INTEGER *serial);
+ASN1_INTEGER *X509_get_serialNumber(X509 *x);
+const ASN1_INTEGER *X509_get0_serialNumber(const X509 *x);
+int X509_set_issuer_name(X509 *x, const X509_NAME *name);
+X509_NAME *X509_get_issuer_name(const X509 *a);
+int X509_set_subject_name(X509 *x, const X509_NAME *name);
+X509_NAME *X509_get_subject_name(const X509 *a);
+const ASN1_TIME * X509_get0_notBefore(const X509 *x);
+ASN1_TIME *X509_getm_notBefore(const X509 *x);
+int X509_set1_notBefore(X509 *x, const ASN1_TIME *tm);
+const ASN1_TIME *X509_get0_notAfter(const X509 *x);
+ASN1_TIME *X509_getm_notAfter(const X509 *x);
+int X509_set1_notAfter(X509 *x, const ASN1_TIME *tm);
+int X509_set_pubkey(X509 *x, EVP_PKEY *pkey);
+int X509_up_ref(X509 *x);
+int X509_get_signature_type(const X509 *x);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_get_notBefore X509_getm_notBefore
+# define X509_get_notAfter X509_getm_notAfter
+# define X509_set_notBefore X509_set1_notBefore
+# define X509_set_notAfter X509_set1_notAfter
+#endif
+
+
+/*
+ * This one is only used so that a binary form can output, as in
+ * i2d_X509_PUBKEY(X509_get_X509_PUBKEY(x), &buf)
+ */
+X509_PUBKEY *X509_get_X509_PUBKEY(const X509 *x);
+const STACK_OF(X509_EXTENSION) *X509_get0_extensions(const X509 *x);
+void X509_get0_uids(const X509 *x, const ASN1_BIT_STRING **piuid,
+ const ASN1_BIT_STRING **psuid);
+const X509_ALGOR *X509_get0_tbs_sigalg(const X509 *x);
+
+EVP_PKEY *X509_get0_pubkey(const X509 *x);
+EVP_PKEY *X509_get_pubkey(X509 *x);
+ASN1_BIT_STRING *X509_get0_pubkey_bitstr(const X509 *x);
+
+#define X509_REQ_VERSION_1 0
+
+long X509_REQ_get_version(const X509_REQ *req);
+int X509_REQ_set_version(X509_REQ *x, long version);
+X509_NAME *X509_REQ_get_subject_name(const X509_REQ *req);
+int X509_REQ_set_subject_name(X509_REQ *req, const X509_NAME *name);
+void X509_REQ_get0_signature(const X509_REQ *req, const ASN1_BIT_STRING **psig,
+ const X509_ALGOR **palg);
+void X509_REQ_set0_signature(X509_REQ *req, ASN1_BIT_STRING *psig);
+int X509_REQ_set1_signature_algo(X509_REQ *req, X509_ALGOR *palg);
+int X509_REQ_get_signature_nid(const X509_REQ *req);
+int i2d_re_X509_REQ_tbs(X509_REQ *req, unsigned char **pp);
+int X509_REQ_set_pubkey(X509_REQ *x, EVP_PKEY *pkey);
+EVP_PKEY *X509_REQ_get_pubkey(X509_REQ *req);
+EVP_PKEY *X509_REQ_get0_pubkey(X509_REQ *req);
+X509_PUBKEY *X509_REQ_get_X509_PUBKEY(X509_REQ *req);
+int X509_REQ_extension_nid(int nid);
+int *X509_REQ_get_extension_nids(void);
+void X509_REQ_set_extension_nids(int *nids);
+STACK_OF(X509_EXTENSION) *X509_REQ_get_extensions(X509_REQ *req);
+int X509_REQ_add_extensions_nid(X509_REQ *req,
+ const STACK_OF(X509_EXTENSION) *exts, int nid);
+int X509_REQ_add_extensions(X509_REQ *req, const STACK_OF(X509_EXTENSION) *ext);
+int X509_REQ_get_attr_count(const X509_REQ *req);
+int X509_REQ_get_attr_by_NID(const X509_REQ *req, int nid, int lastpos);
+int X509_REQ_get_attr_by_OBJ(const X509_REQ *req, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_ATTRIBUTE *X509_REQ_get_attr(const X509_REQ *req, int loc);
+X509_ATTRIBUTE *X509_REQ_delete_attr(X509_REQ *req, int loc);
+int X509_REQ_add1_attr(X509_REQ *req, X509_ATTRIBUTE *attr);
+int X509_REQ_add1_attr_by_OBJ(X509_REQ *req,
+ const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes, int len);
+int X509_REQ_add1_attr_by_NID(X509_REQ *req,
+ int nid, int type,
+ const unsigned char *bytes, int len);
+int X509_REQ_add1_attr_by_txt(X509_REQ *req,
+ const char *attrname, int type,
+ const unsigned char *bytes, int len);
+
+#define X509_CRL_VERSION_1 0
+#define X509_CRL_VERSION_2 1
+
+int X509_CRL_set_version(X509_CRL *x, long version);
+int X509_CRL_set_issuer_name(X509_CRL *x, const X509_NAME *name);
+int X509_CRL_set1_lastUpdate(X509_CRL *x, const ASN1_TIME *tm);
+int X509_CRL_set1_nextUpdate(X509_CRL *x, const ASN1_TIME *tm);
+int X509_CRL_sort(X509_CRL *crl);
+int X509_CRL_up_ref(X509_CRL *crl);
+
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_CRL_set_lastUpdate X509_CRL_set1_lastUpdate
+# define X509_CRL_set_nextUpdate X509_CRL_set1_nextUpdate
+#endif
+
+long X509_CRL_get_version(const X509_CRL *crl);
+const ASN1_TIME *X509_CRL_get0_lastUpdate(const X509_CRL *crl);
+const ASN1_TIME *X509_CRL_get0_nextUpdate(const X509_CRL *crl);
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_lastUpdate(X509_CRL *crl);
+OSSL_DEPRECATEDIN_1_1_0 ASN1_TIME *X509_CRL_get_nextUpdate(X509_CRL *crl);
+#endif
+X509_NAME *X509_CRL_get_issuer(const X509_CRL *crl);
+const STACK_OF(X509_EXTENSION) *X509_CRL_get0_extensions(const X509_CRL *crl);
+STACK_OF(X509_REVOKED) *X509_CRL_get_REVOKED(X509_CRL *crl);
+void X509_CRL_get0_signature(const X509_CRL *crl, const ASN1_BIT_STRING **psig,
+ const X509_ALGOR **palg);
+int X509_CRL_get_signature_nid(const X509_CRL *crl);
+int i2d_re_X509_CRL_tbs(X509_CRL *req, unsigned char **pp);
+
+const ASN1_INTEGER *X509_REVOKED_get0_serialNumber(const X509_REVOKED *x);
+int X509_REVOKED_set_serialNumber(X509_REVOKED *x, ASN1_INTEGER *serial);
+const ASN1_TIME *X509_REVOKED_get0_revocationDate(const X509_REVOKED *x);
+int X509_REVOKED_set_revocationDate(X509_REVOKED *r, ASN1_TIME *tm);
+const STACK_OF(X509_EXTENSION) *
+X509_REVOKED_get0_extensions(const X509_REVOKED *r);
+
+X509_CRL *X509_CRL_diff(X509_CRL *base, X509_CRL *newer,
+ EVP_PKEY *skey, const EVP_MD *md, unsigned int flags);
+
+int X509_REQ_check_private_key(X509_REQ *x509, EVP_PKEY *pkey);
+
+int X509_check_private_key(const X509 *x509, const EVP_PKEY *pkey);
+int X509_chain_check_suiteb(int *perror_depth,
+ X509 *x, STACK_OF(X509) *chain,
+ unsigned long flags);
+int X509_CRL_check_suiteb(X509_CRL *crl, EVP_PKEY *pk, unsigned long flags);
+STACK_OF(X509) *X509_chain_up_ref(STACK_OF(X509) *chain);
+
+int X509_issuer_and_serial_cmp(const X509 *a, const X509 *b);
+unsigned long X509_issuer_and_serial_hash(X509 *a);
+
+int X509_issuer_name_cmp(const X509 *a, const X509 *b);
+unsigned long X509_issuer_name_hash(X509 *a);
+
+int X509_subject_name_cmp(const X509 *a, const X509 *b);
+unsigned long X509_subject_name_hash(X509 *x);
+
+# ifndef OPENSSL_NO_MD5
+unsigned long X509_issuer_name_hash_old(X509 *a);
+unsigned long X509_subject_name_hash_old(X509 *x);
+# endif
+
+# define X509_ADD_FLAG_DEFAULT 0
+# define X509_ADD_FLAG_UP_REF 0x1
+# define X509_ADD_FLAG_PREPEND 0x2
+# define X509_ADD_FLAG_NO_DUP 0x4
+# define X509_ADD_FLAG_NO_SS 0x8
+int X509_add_cert(STACK_OF(X509) *sk, X509 *cert, int flags);
+int X509_add_certs(STACK_OF(X509) *sk, STACK_OF(X509) *certs, int flags);
+
+int X509_cmp(const X509 *a, const X509 *b);
+int X509_NAME_cmp(const X509_NAME *a, const X509_NAME *b);
+#ifndef OPENSSL_NO_DEPRECATED_3_0
+# define X509_NAME_hash(x) X509_NAME_hash_ex(x, NULL, NULL, NULL)
+OSSL_DEPRECATEDIN_3_0 int X509_certificate_type(const X509 *x,
+ const EVP_PKEY *pubkey);
+#endif
+unsigned long X509_NAME_hash_ex(const X509_NAME *x, OSSL_LIB_CTX *libctx,
+ const char *propq, int *ok);
+unsigned long X509_NAME_hash_old(const X509_NAME *x);
+
+int X509_CRL_cmp(const X509_CRL *a, const X509_CRL *b);
+int X509_CRL_match(const X509_CRL *a, const X509_CRL *b);
+int X509_aux_print(BIO *out, X509 *x, int indent);
+# ifndef OPENSSL_NO_STDIO
+int X509_print_ex_fp(FILE *bp, X509 *x, unsigned long nmflag,
+ unsigned long cflag);
+int X509_print_fp(FILE *bp, X509 *x);
+int X509_CRL_print_fp(FILE *bp, X509_CRL *x);
+int X509_REQ_print_fp(FILE *bp, X509_REQ *req);
+int X509_NAME_print_ex_fp(FILE *fp, const X509_NAME *nm, int indent,
+ unsigned long flags);
+# endif
+
+int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase);
+int X509_NAME_print_ex(BIO *out, const X509_NAME *nm, int indent,
+ unsigned long flags);
+int X509_print_ex(BIO *bp, X509 *x, unsigned long nmflag,
+ unsigned long cflag);
+int X509_print(BIO *bp, X509 *x);
+int X509_ocspid_print(BIO *bp, X509 *x);
+int X509_CRL_print_ex(BIO *out, X509_CRL *x, unsigned long nmflag);
+int X509_CRL_print(BIO *bp, X509_CRL *x);
+int X509_REQ_print_ex(BIO *bp, X509_REQ *x, unsigned long nmflag,
+ unsigned long cflag);
+int X509_REQ_print(BIO *bp, X509_REQ *req);
+
+int X509_NAME_entry_count(const X509_NAME *name);
+int X509_NAME_get_text_by_NID(const X509_NAME *name, int nid,
+ char *buf, int len);
+int X509_NAME_get_text_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
+ char *buf, int len);
+
+/*
+ * NOTE: you should be passing -1, not 0 as lastpos. The functions that use
+ * lastpos, search after that position on.
+ */
+int X509_NAME_get_index_by_NID(const X509_NAME *name, int nid, int lastpos);
+int X509_NAME_get_index_by_OBJ(const X509_NAME *name, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_NAME_ENTRY *X509_NAME_get_entry(const X509_NAME *name, int loc);
+X509_NAME_ENTRY *X509_NAME_delete_entry(X509_NAME *name, int loc);
+int X509_NAME_add_entry(X509_NAME *name, const X509_NAME_ENTRY *ne,
+ int loc, int set);
+int X509_NAME_add_entry_by_OBJ(X509_NAME *name, const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes, int len, int loc,
+ int set);
+int X509_NAME_add_entry_by_NID(X509_NAME *name, int nid, int type,
+ const unsigned char *bytes, int len, int loc,
+ int set);
+X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_txt(X509_NAME_ENTRY **ne,
+ const char *field, int type,
+ const unsigned char *bytes,
+ int len);
+X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_NID(X509_NAME_ENTRY **ne, int nid,
+ int type,
+ const unsigned char *bytes,
+ int len);
+int X509_NAME_add_entry_by_txt(X509_NAME *name, const char *field, int type,
+ const unsigned char *bytes, int len, int loc,
+ int set);
+X509_NAME_ENTRY *X509_NAME_ENTRY_create_by_OBJ(X509_NAME_ENTRY **ne,
+ const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes,
+ int len);
+int X509_NAME_ENTRY_set_object(X509_NAME_ENTRY *ne, const ASN1_OBJECT *obj);
+int X509_NAME_ENTRY_set_data(X509_NAME_ENTRY *ne, int type,
+ const unsigned char *bytes, int len);
+ASN1_OBJECT *X509_NAME_ENTRY_get_object(const X509_NAME_ENTRY *ne);
+ASN1_STRING * X509_NAME_ENTRY_get_data(const X509_NAME_ENTRY *ne);
+int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne);
+
+int X509_NAME_get0_der(const X509_NAME *nm, const unsigned char **pder,
+ size_t *pderlen);
+
+int X509v3_get_ext_count(const STACK_OF(X509_EXTENSION) *x);
+int X509v3_get_ext_by_NID(const STACK_OF(X509_EXTENSION) *x,
+ int nid, int lastpos);
+int X509v3_get_ext_by_OBJ(const STACK_OF(X509_EXTENSION) *x,
+ const ASN1_OBJECT *obj, int lastpos);
+int X509v3_get_ext_by_critical(const STACK_OF(X509_EXTENSION) *x,
+ int crit, int lastpos);
+X509_EXTENSION *X509v3_get_ext(const STACK_OF(X509_EXTENSION) *x, int loc);
+X509_EXTENSION *X509v3_delete_ext(STACK_OF(X509_EXTENSION) *x, int loc);
+STACK_OF(X509_EXTENSION) *X509v3_add_ext(STACK_OF(X509_EXTENSION) **x,
+ X509_EXTENSION *ex, int loc);
+
+int X509_get_ext_count(const X509 *x);
+int X509_get_ext_by_NID(const X509 *x, int nid, int lastpos);
+int X509_get_ext_by_OBJ(const X509 *x, const ASN1_OBJECT *obj, int lastpos);
+int X509_get_ext_by_critical(const X509 *x, int crit, int lastpos);
+X509_EXTENSION *X509_get_ext(const X509 *x, int loc);
+X509_EXTENSION *X509_delete_ext(X509 *x, int loc);
+int X509_add_ext(X509 *x, X509_EXTENSION *ex, int loc);
+void *X509_get_ext_d2i(const X509 *x, int nid, int *crit, int *idx);
+int X509_add1_ext_i2d(X509 *x, int nid, void *value, int crit,
+ unsigned long flags);
+
+int X509_CRL_get_ext_count(const X509_CRL *x);
+int X509_CRL_get_ext_by_NID(const X509_CRL *x, int nid, int lastpos);
+int X509_CRL_get_ext_by_OBJ(const X509_CRL *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int X509_CRL_get_ext_by_critical(const X509_CRL *x, int crit, int lastpos);
+X509_EXTENSION *X509_CRL_get_ext(const X509_CRL *x, int loc);
+X509_EXTENSION *X509_CRL_delete_ext(X509_CRL *x, int loc);
+int X509_CRL_add_ext(X509_CRL *x, X509_EXTENSION *ex, int loc);
+void *X509_CRL_get_ext_d2i(const X509_CRL *x, int nid, int *crit, int *idx);
+int X509_CRL_add1_ext_i2d(X509_CRL *x, int nid, void *value, int crit,
+ unsigned long flags);
+
+int X509_REVOKED_get_ext_count(const X509_REVOKED *x);
+int X509_REVOKED_get_ext_by_NID(const X509_REVOKED *x, int nid, int lastpos);
+int X509_REVOKED_get_ext_by_OBJ(const X509_REVOKED *x, const ASN1_OBJECT *obj,
+ int lastpos);
+int X509_REVOKED_get_ext_by_critical(const X509_REVOKED *x, int crit,
+ int lastpos);
+X509_EXTENSION *X509_REVOKED_get_ext(const X509_REVOKED *x, int loc);
+X509_EXTENSION *X509_REVOKED_delete_ext(X509_REVOKED *x, int loc);
+int X509_REVOKED_add_ext(X509_REVOKED *x, X509_EXTENSION *ex, int loc);
+void *X509_REVOKED_get_ext_d2i(const X509_REVOKED *x, int nid, int *crit,
+ int *idx);
+int X509_REVOKED_add1_ext_i2d(X509_REVOKED *x, int nid, void *value, int crit,
+ unsigned long flags);
+
+X509_EXTENSION *X509_EXTENSION_create_by_NID(X509_EXTENSION **ex,
+ int nid, int crit,
+ ASN1_OCTET_STRING *data);
+X509_EXTENSION *X509_EXTENSION_create_by_OBJ(X509_EXTENSION **ex,
+ const ASN1_OBJECT *obj, int crit,
+ ASN1_OCTET_STRING *data);
+int X509_EXTENSION_set_object(X509_EXTENSION *ex, const ASN1_OBJECT *obj);
+int X509_EXTENSION_set_critical(X509_EXTENSION *ex, int crit);
+int X509_EXTENSION_set_data(X509_EXTENSION *ex, ASN1_OCTET_STRING *data);
+ASN1_OBJECT *X509_EXTENSION_get_object(X509_EXTENSION *ex);
+ASN1_OCTET_STRING *X509_EXTENSION_get_data(X509_EXTENSION *ne);
+int X509_EXTENSION_get_critical(const X509_EXTENSION *ex);
+
+int X509at_get_attr_count(const STACK_OF(X509_ATTRIBUTE) *x);
+int X509at_get_attr_by_NID(const STACK_OF(X509_ATTRIBUTE) *x, int nid,
+ int lastpos);
+int X509at_get_attr_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *sk,
+ const ASN1_OBJECT *obj, int lastpos);
+X509_ATTRIBUTE *X509at_get_attr(const STACK_OF(X509_ATTRIBUTE) *x, int loc);
+X509_ATTRIBUTE *X509at_delete_attr(STACK_OF(X509_ATTRIBUTE) *x, int loc);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr(STACK_OF(X509_ATTRIBUTE) **x,
+ X509_ATTRIBUTE *attr);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_OBJ(STACK_OF(X509_ATTRIBUTE)
+ **x, const ASN1_OBJECT *obj,
+ int type,
+ const unsigned char *bytes,
+ int len);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_NID(STACK_OF(X509_ATTRIBUTE)
+ **x, int nid, int type,
+ const unsigned char *bytes,
+ int len);
+STACK_OF(X509_ATTRIBUTE) *X509at_add1_attr_by_txt(STACK_OF(X509_ATTRIBUTE)
+ **x, const char *attrname,
+ int type,
+ const unsigned char *bytes,
+ int len);
+void *X509at_get0_data_by_OBJ(const STACK_OF(X509_ATTRIBUTE) *x,
+ const ASN1_OBJECT *obj, int lastpos, int type);
+X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_NID(X509_ATTRIBUTE **attr, int nid,
+ int atrtype, const void *data,
+ int len);
+X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_OBJ(X509_ATTRIBUTE **attr,
+ const ASN1_OBJECT *obj,
+ int atrtype, const void *data,
+ int len);
+X509_ATTRIBUTE *X509_ATTRIBUTE_create_by_txt(X509_ATTRIBUTE **attr,
+ const char *atrname, int type,
+ const unsigned char *bytes,
+ int len);
+int X509_ATTRIBUTE_set1_object(X509_ATTRIBUTE *attr, const ASN1_OBJECT *obj);
+int X509_ATTRIBUTE_set1_data(X509_ATTRIBUTE *attr, int attrtype,
+ const void *data, int len);
+void *X509_ATTRIBUTE_get0_data(X509_ATTRIBUTE *attr, int idx, int atrtype,
+ void *data);
+int X509_ATTRIBUTE_count(const X509_ATTRIBUTE *attr);
+ASN1_OBJECT *X509_ATTRIBUTE_get0_object(X509_ATTRIBUTE *attr);
+ASN1_TYPE *X509_ATTRIBUTE_get0_type(X509_ATTRIBUTE *attr, int idx);
+
+int EVP_PKEY_get_attr_count(const EVP_PKEY *key);
+int EVP_PKEY_get_attr_by_NID(const EVP_PKEY *key, int nid, int lastpos);
+int EVP_PKEY_get_attr_by_OBJ(const EVP_PKEY *key, const ASN1_OBJECT *obj,
+ int lastpos);
+X509_ATTRIBUTE *EVP_PKEY_get_attr(const EVP_PKEY *key, int loc);
+X509_ATTRIBUTE *EVP_PKEY_delete_attr(EVP_PKEY *key, int loc);
+int EVP_PKEY_add1_attr(EVP_PKEY *key, X509_ATTRIBUTE *attr);
+int EVP_PKEY_add1_attr_by_OBJ(EVP_PKEY *key,
+ const ASN1_OBJECT *obj, int type,
+ const unsigned char *bytes, int len);
+int EVP_PKEY_add1_attr_by_NID(EVP_PKEY *key,
+ int nid, int type,
+ const unsigned char *bytes, int len);
+int EVP_PKEY_add1_attr_by_txt(EVP_PKEY *key,
+ const char *attrname, int type,
+ const unsigned char *bytes, int len);
+
+/* lookup a cert from a X509 STACK */
+X509 *X509_find_by_issuer_and_serial(STACK_OF(X509) *sk, const X509_NAME *name,
+ const ASN1_INTEGER *serial);
+X509 *X509_find_by_subject(STACK_OF(X509) *sk, const X509_NAME *name);
+
+DECLARE_ASN1_FUNCTIONS(PBEPARAM)
+DECLARE_ASN1_FUNCTIONS(PBE2PARAM)
+DECLARE_ASN1_FUNCTIONS(PBKDF2PARAM)
+#ifndef OPENSSL_NO_SCRYPT
+DECLARE_ASN1_FUNCTIONS(SCRYPT_PARAMS)
+#endif
+
+int PKCS5_pbe_set0_algor(X509_ALGOR *algor, int alg, int iter,
+ const unsigned char *salt, int saltlen);
+int PKCS5_pbe_set0_algor_ex(X509_ALGOR *algor, int alg, int iter,
+ const unsigned char *salt, int saltlen,
+ OSSL_LIB_CTX *libctx);
+
+X509_ALGOR *PKCS5_pbe_set(int alg, int iter,
+ const unsigned char *salt, int saltlen);
+X509_ALGOR *PKCS5_pbe_set_ex(int alg, int iter,
+ const unsigned char *salt, int saltlen,
+ OSSL_LIB_CTX *libctx);
+
+X509_ALGOR *PKCS5_pbe2_set(const EVP_CIPHER *cipher, int iter,
+ unsigned char *salt, int saltlen);
+X509_ALGOR *PKCS5_pbe2_set_iv(const EVP_CIPHER *cipher, int iter,
+ unsigned char *salt, int saltlen,
+ unsigned char *aiv, int prf_nid);
+X509_ALGOR *PKCS5_pbe2_set_iv_ex(const EVP_CIPHER *cipher, int iter,
+ unsigned char *salt, int saltlen,
+ unsigned char *aiv, int prf_nid,
+ OSSL_LIB_CTX *libctx);
+
+#ifndef OPENSSL_NO_SCRYPT
+X509_ALGOR *PKCS5_pbe2_set_scrypt(const EVP_CIPHER *cipher,
+ const unsigned char *salt, int saltlen,
+ unsigned char *aiv, uint64_t N, uint64_t r,
+ uint64_t p);
+#endif
+
+X509_ALGOR *PKCS5_pbkdf2_set(int iter, unsigned char *salt, int saltlen,
+ int prf_nid, int keylen);
+X509_ALGOR *PKCS5_pbkdf2_set_ex(int iter, unsigned char *salt, int saltlen,
+ int prf_nid, int keylen,
+ OSSL_LIB_CTX *libctx);
+
+/* PKCS#8 utilities */
+
+DECLARE_ASN1_FUNCTIONS(PKCS8_PRIV_KEY_INFO)
+
+EVP_PKEY *EVP_PKCS82PKEY(const PKCS8_PRIV_KEY_INFO *p8);
+EVP_PKEY *EVP_PKCS82PKEY_ex(const PKCS8_PRIV_KEY_INFO *p8, OSSL_LIB_CTX *libctx,
+ const char *propq);
+PKCS8_PRIV_KEY_INFO *EVP_PKEY2PKCS8(const EVP_PKEY *pkey);
+
+int PKCS8_pkey_set0(PKCS8_PRIV_KEY_INFO *priv, ASN1_OBJECT *aobj,
+ int version, int ptype, void *pval,
+ unsigned char *penc, int penclen);
+int PKCS8_pkey_get0(const ASN1_OBJECT **ppkalg,
+ const unsigned char **pk, int *ppklen,
+ const X509_ALGOR **pa, const PKCS8_PRIV_KEY_INFO *p8);
+
+const STACK_OF(X509_ATTRIBUTE) *
+PKCS8_pkey_get0_attrs(const PKCS8_PRIV_KEY_INFO *p8);
+int PKCS8_pkey_add1_attr(PKCS8_PRIV_KEY_INFO *p8, X509_ATTRIBUTE *attr);
+int PKCS8_pkey_add1_attr_by_NID(PKCS8_PRIV_KEY_INFO *p8, int nid, int type,
+ const unsigned char *bytes, int len);
+int PKCS8_pkey_add1_attr_by_OBJ(PKCS8_PRIV_KEY_INFO *p8, const ASN1_OBJECT *obj,
+ int type, const unsigned char *bytes, int len);
+
+
+int X509_PUBKEY_set0_param(X509_PUBKEY *pub, ASN1_OBJECT *aobj,
+ int ptype, void *pval,
+ unsigned char *penc, int penclen);
+int X509_PUBKEY_get0_param(ASN1_OBJECT **ppkalg,
+ const unsigned char **pk, int *ppklen,
+ X509_ALGOR **pa, const X509_PUBKEY *pub);
+int X509_PUBKEY_eq(const X509_PUBKEY *a, const X509_PUBKEY *b);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/x509_vfy.h b/include/openssl/x509_vfy.h
new file mode 100644
index 00000000..e04df0d3
--- /dev/null
+++ b/include/openssl/x509_vfy.h
@@ -0,0 +1,894 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\x509_vfy.h.in
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_X509_VFY_H
+# define OPENSSL_X509_VFY_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_X509_VFY_H
+# endif
+
+/*
+ * Protect against recursion, x509.h and x509_vfy.h each include the other.
+ */
+# ifndef OPENSSL_X509_H
+# include <openssl/x509.h>
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/lhash.h>
+# include <openssl/bio.h>
+# include <openssl/crypto.h>
+# include <openssl/symhacks.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-
+SSL_CTX -> X509_STORE
+ -> X509_LOOKUP
+ ->X509_LOOKUP_METHOD
+ -> X509_LOOKUP
+ ->X509_LOOKUP_METHOD
+
+SSL -> X509_STORE_CTX
+ ->X509_STORE
+
+The X509_STORE holds the tables etc for verification stuff.
+A X509_STORE_CTX is used while validating a single certificate.
+The X509_STORE has X509_LOOKUPs for looking up certs.
+The X509_STORE then calls a function to actually verify the
+certificate chain.
+*/
+
+typedef enum {
+ X509_LU_NONE = 0,
+ X509_LU_X509, X509_LU_CRL
+} X509_LOOKUP_TYPE;
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+#define X509_LU_RETRY -1
+#define X509_LU_FAIL 0
+#endif
+
+SKM_DEFINE_STACK_OF_INTERNAL(X509_LOOKUP, X509_LOOKUP, X509_LOOKUP)
+#define sk_X509_LOOKUP_num(sk) OPENSSL_sk_num(ossl_check_const_X509_LOOKUP_sk_type(sk))
+#define sk_X509_LOOKUP_value(sk, idx) ((X509_LOOKUP *)OPENSSL_sk_value(ossl_check_const_X509_LOOKUP_sk_type(sk), (idx)))
+#define sk_X509_LOOKUP_new(cmp) ((STACK_OF(X509_LOOKUP) *)OPENSSL_sk_new(ossl_check_X509_LOOKUP_compfunc_type(cmp)))
+#define sk_X509_LOOKUP_new_null() ((STACK_OF(X509_LOOKUP) *)OPENSSL_sk_new_null())
+#define sk_X509_LOOKUP_new_reserve(cmp, n) ((STACK_OF(X509_LOOKUP) *)OPENSSL_sk_new_reserve(ossl_check_X509_LOOKUP_compfunc_type(cmp), (n)))
+#define sk_X509_LOOKUP_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_LOOKUP_sk_type(sk), (n))
+#define sk_X509_LOOKUP_free(sk) OPENSSL_sk_free(ossl_check_X509_LOOKUP_sk_type(sk))
+#define sk_X509_LOOKUP_zero(sk) OPENSSL_sk_zero(ossl_check_X509_LOOKUP_sk_type(sk))
+#define sk_X509_LOOKUP_delete(sk, i) ((X509_LOOKUP *)OPENSSL_sk_delete(ossl_check_X509_LOOKUP_sk_type(sk), (i)))
+#define sk_X509_LOOKUP_delete_ptr(sk, ptr) ((X509_LOOKUP *)OPENSSL_sk_delete_ptr(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_type(ptr)))
+#define sk_X509_LOOKUP_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_type(ptr))
+#define sk_X509_LOOKUP_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_type(ptr))
+#define sk_X509_LOOKUP_pop(sk) ((X509_LOOKUP *)OPENSSL_sk_pop(ossl_check_X509_LOOKUP_sk_type(sk)))
+#define sk_X509_LOOKUP_shift(sk) ((X509_LOOKUP *)OPENSSL_sk_shift(ossl_check_X509_LOOKUP_sk_type(sk)))
+#define sk_X509_LOOKUP_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_LOOKUP_sk_type(sk),ossl_check_X509_LOOKUP_freefunc_type(freefunc))
+#define sk_X509_LOOKUP_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_type(ptr), (idx))
+#define sk_X509_LOOKUP_set(sk, idx, ptr) ((X509_LOOKUP *)OPENSSL_sk_set(ossl_check_X509_LOOKUP_sk_type(sk), (idx), ossl_check_X509_LOOKUP_type(ptr)))
+#define sk_X509_LOOKUP_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_type(ptr))
+#define sk_X509_LOOKUP_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_type(ptr))
+#define sk_X509_LOOKUP_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_type(ptr), pnum)
+#define sk_X509_LOOKUP_sort(sk) OPENSSL_sk_sort(ossl_check_X509_LOOKUP_sk_type(sk))
+#define sk_X509_LOOKUP_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_LOOKUP_sk_type(sk))
+#define sk_X509_LOOKUP_dup(sk) ((STACK_OF(X509_LOOKUP) *)OPENSSL_sk_dup(ossl_check_const_X509_LOOKUP_sk_type(sk)))
+#define sk_X509_LOOKUP_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_LOOKUP) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_copyfunc_type(copyfunc), ossl_check_X509_LOOKUP_freefunc_type(freefunc)))
+#define sk_X509_LOOKUP_set_cmp_func(sk, cmp) ((sk_X509_LOOKUP_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_LOOKUP_sk_type(sk), ossl_check_X509_LOOKUP_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(X509_OBJECT, X509_OBJECT, X509_OBJECT)
+#define sk_X509_OBJECT_num(sk) OPENSSL_sk_num(ossl_check_const_X509_OBJECT_sk_type(sk))
+#define sk_X509_OBJECT_value(sk, idx) ((X509_OBJECT *)OPENSSL_sk_value(ossl_check_const_X509_OBJECT_sk_type(sk), (idx)))
+#define sk_X509_OBJECT_new(cmp) ((STACK_OF(X509_OBJECT) *)OPENSSL_sk_new(ossl_check_X509_OBJECT_compfunc_type(cmp)))
+#define sk_X509_OBJECT_new_null() ((STACK_OF(X509_OBJECT) *)OPENSSL_sk_new_null())
+#define sk_X509_OBJECT_new_reserve(cmp, n) ((STACK_OF(X509_OBJECT) *)OPENSSL_sk_new_reserve(ossl_check_X509_OBJECT_compfunc_type(cmp), (n)))
+#define sk_X509_OBJECT_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_OBJECT_sk_type(sk), (n))
+#define sk_X509_OBJECT_free(sk) OPENSSL_sk_free(ossl_check_X509_OBJECT_sk_type(sk))
+#define sk_X509_OBJECT_zero(sk) OPENSSL_sk_zero(ossl_check_X509_OBJECT_sk_type(sk))
+#define sk_X509_OBJECT_delete(sk, i) ((X509_OBJECT *)OPENSSL_sk_delete(ossl_check_X509_OBJECT_sk_type(sk), (i)))
+#define sk_X509_OBJECT_delete_ptr(sk, ptr) ((X509_OBJECT *)OPENSSL_sk_delete_ptr(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_type(ptr)))
+#define sk_X509_OBJECT_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_type(ptr))
+#define sk_X509_OBJECT_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_type(ptr))
+#define sk_X509_OBJECT_pop(sk) ((X509_OBJECT *)OPENSSL_sk_pop(ossl_check_X509_OBJECT_sk_type(sk)))
+#define sk_X509_OBJECT_shift(sk) ((X509_OBJECT *)OPENSSL_sk_shift(ossl_check_X509_OBJECT_sk_type(sk)))
+#define sk_X509_OBJECT_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_OBJECT_sk_type(sk),ossl_check_X509_OBJECT_freefunc_type(freefunc))
+#define sk_X509_OBJECT_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_type(ptr), (idx))
+#define sk_X509_OBJECT_set(sk, idx, ptr) ((X509_OBJECT *)OPENSSL_sk_set(ossl_check_X509_OBJECT_sk_type(sk), (idx), ossl_check_X509_OBJECT_type(ptr)))
+#define sk_X509_OBJECT_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_type(ptr))
+#define sk_X509_OBJECT_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_type(ptr))
+#define sk_X509_OBJECT_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_type(ptr), pnum)
+#define sk_X509_OBJECT_sort(sk) OPENSSL_sk_sort(ossl_check_X509_OBJECT_sk_type(sk))
+#define sk_X509_OBJECT_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_OBJECT_sk_type(sk))
+#define sk_X509_OBJECT_dup(sk) ((STACK_OF(X509_OBJECT) *)OPENSSL_sk_dup(ossl_check_const_X509_OBJECT_sk_type(sk)))
+#define sk_X509_OBJECT_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_OBJECT) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_copyfunc_type(copyfunc), ossl_check_X509_OBJECT_freefunc_type(freefunc)))
+#define sk_X509_OBJECT_set_cmp_func(sk, cmp) ((sk_X509_OBJECT_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_OBJECT_sk_type(sk), ossl_check_X509_OBJECT_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(X509_VERIFY_PARAM, X509_VERIFY_PARAM, X509_VERIFY_PARAM)
+#define sk_X509_VERIFY_PARAM_num(sk) OPENSSL_sk_num(ossl_check_const_X509_VERIFY_PARAM_sk_type(sk))
+#define sk_X509_VERIFY_PARAM_value(sk, idx) ((X509_VERIFY_PARAM *)OPENSSL_sk_value(ossl_check_const_X509_VERIFY_PARAM_sk_type(sk), (idx)))
+#define sk_X509_VERIFY_PARAM_new(cmp) ((STACK_OF(X509_VERIFY_PARAM) *)OPENSSL_sk_new(ossl_check_X509_VERIFY_PARAM_compfunc_type(cmp)))
+#define sk_X509_VERIFY_PARAM_new_null() ((STACK_OF(X509_VERIFY_PARAM) *)OPENSSL_sk_new_null())
+#define sk_X509_VERIFY_PARAM_new_reserve(cmp, n) ((STACK_OF(X509_VERIFY_PARAM) *)OPENSSL_sk_new_reserve(ossl_check_X509_VERIFY_PARAM_compfunc_type(cmp), (n)))
+#define sk_X509_VERIFY_PARAM_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_VERIFY_PARAM_sk_type(sk), (n))
+#define sk_X509_VERIFY_PARAM_free(sk) OPENSSL_sk_free(ossl_check_X509_VERIFY_PARAM_sk_type(sk))
+#define sk_X509_VERIFY_PARAM_zero(sk) OPENSSL_sk_zero(ossl_check_X509_VERIFY_PARAM_sk_type(sk))
+#define sk_X509_VERIFY_PARAM_delete(sk, i) ((X509_VERIFY_PARAM *)OPENSSL_sk_delete(ossl_check_X509_VERIFY_PARAM_sk_type(sk), (i)))
+#define sk_X509_VERIFY_PARAM_delete_ptr(sk, ptr) ((X509_VERIFY_PARAM *)OPENSSL_sk_delete_ptr(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_type(ptr)))
+#define sk_X509_VERIFY_PARAM_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_type(ptr))
+#define sk_X509_VERIFY_PARAM_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_type(ptr))
+#define sk_X509_VERIFY_PARAM_pop(sk) ((X509_VERIFY_PARAM *)OPENSSL_sk_pop(ossl_check_X509_VERIFY_PARAM_sk_type(sk)))
+#define sk_X509_VERIFY_PARAM_shift(sk) ((X509_VERIFY_PARAM *)OPENSSL_sk_shift(ossl_check_X509_VERIFY_PARAM_sk_type(sk)))
+#define sk_X509_VERIFY_PARAM_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_VERIFY_PARAM_sk_type(sk),ossl_check_X509_VERIFY_PARAM_freefunc_type(freefunc))
+#define sk_X509_VERIFY_PARAM_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_type(ptr), (idx))
+#define sk_X509_VERIFY_PARAM_set(sk, idx, ptr) ((X509_VERIFY_PARAM *)OPENSSL_sk_set(ossl_check_X509_VERIFY_PARAM_sk_type(sk), (idx), ossl_check_X509_VERIFY_PARAM_type(ptr)))
+#define sk_X509_VERIFY_PARAM_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_type(ptr))
+#define sk_X509_VERIFY_PARAM_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_type(ptr))
+#define sk_X509_VERIFY_PARAM_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_type(ptr), pnum)
+#define sk_X509_VERIFY_PARAM_sort(sk) OPENSSL_sk_sort(ossl_check_X509_VERIFY_PARAM_sk_type(sk))
+#define sk_X509_VERIFY_PARAM_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_VERIFY_PARAM_sk_type(sk))
+#define sk_X509_VERIFY_PARAM_dup(sk) ((STACK_OF(X509_VERIFY_PARAM) *)OPENSSL_sk_dup(ossl_check_const_X509_VERIFY_PARAM_sk_type(sk)))
+#define sk_X509_VERIFY_PARAM_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_VERIFY_PARAM) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_copyfunc_type(copyfunc), ossl_check_X509_VERIFY_PARAM_freefunc_type(freefunc)))
+#define sk_X509_VERIFY_PARAM_set_cmp_func(sk, cmp) ((sk_X509_VERIFY_PARAM_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_VERIFY_PARAM_sk_type(sk), ossl_check_X509_VERIFY_PARAM_compfunc_type(cmp)))
+
+
+/* This is used for a table of trust checking functions */
+typedef struct x509_trust_st {
+ int trust;
+ int flags;
+ int (*check_trust) (struct x509_trust_st *, X509 *, int);
+ char *name;
+ int arg1;
+ void *arg2;
+} X509_TRUST;
+SKM_DEFINE_STACK_OF_INTERNAL(X509_TRUST, X509_TRUST, X509_TRUST)
+#define sk_X509_TRUST_num(sk) OPENSSL_sk_num(ossl_check_const_X509_TRUST_sk_type(sk))
+#define sk_X509_TRUST_value(sk, idx) ((X509_TRUST *)OPENSSL_sk_value(ossl_check_const_X509_TRUST_sk_type(sk), (idx)))
+#define sk_X509_TRUST_new(cmp) ((STACK_OF(X509_TRUST) *)OPENSSL_sk_new(ossl_check_X509_TRUST_compfunc_type(cmp)))
+#define sk_X509_TRUST_new_null() ((STACK_OF(X509_TRUST) *)OPENSSL_sk_new_null())
+#define sk_X509_TRUST_new_reserve(cmp, n) ((STACK_OF(X509_TRUST) *)OPENSSL_sk_new_reserve(ossl_check_X509_TRUST_compfunc_type(cmp), (n)))
+#define sk_X509_TRUST_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_TRUST_sk_type(sk), (n))
+#define sk_X509_TRUST_free(sk) OPENSSL_sk_free(ossl_check_X509_TRUST_sk_type(sk))
+#define sk_X509_TRUST_zero(sk) OPENSSL_sk_zero(ossl_check_X509_TRUST_sk_type(sk))
+#define sk_X509_TRUST_delete(sk, i) ((X509_TRUST *)OPENSSL_sk_delete(ossl_check_X509_TRUST_sk_type(sk), (i)))
+#define sk_X509_TRUST_delete_ptr(sk, ptr) ((X509_TRUST *)OPENSSL_sk_delete_ptr(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_type(ptr)))
+#define sk_X509_TRUST_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_type(ptr))
+#define sk_X509_TRUST_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_type(ptr))
+#define sk_X509_TRUST_pop(sk) ((X509_TRUST *)OPENSSL_sk_pop(ossl_check_X509_TRUST_sk_type(sk)))
+#define sk_X509_TRUST_shift(sk) ((X509_TRUST *)OPENSSL_sk_shift(ossl_check_X509_TRUST_sk_type(sk)))
+#define sk_X509_TRUST_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_TRUST_sk_type(sk),ossl_check_X509_TRUST_freefunc_type(freefunc))
+#define sk_X509_TRUST_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_type(ptr), (idx))
+#define sk_X509_TRUST_set(sk, idx, ptr) ((X509_TRUST *)OPENSSL_sk_set(ossl_check_X509_TRUST_sk_type(sk), (idx), ossl_check_X509_TRUST_type(ptr)))
+#define sk_X509_TRUST_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_type(ptr))
+#define sk_X509_TRUST_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_type(ptr))
+#define sk_X509_TRUST_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_type(ptr), pnum)
+#define sk_X509_TRUST_sort(sk) OPENSSL_sk_sort(ossl_check_X509_TRUST_sk_type(sk))
+#define sk_X509_TRUST_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_TRUST_sk_type(sk))
+#define sk_X509_TRUST_dup(sk) ((STACK_OF(X509_TRUST) *)OPENSSL_sk_dup(ossl_check_const_X509_TRUST_sk_type(sk)))
+#define sk_X509_TRUST_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_TRUST) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_copyfunc_type(copyfunc), ossl_check_X509_TRUST_freefunc_type(freefunc)))
+#define sk_X509_TRUST_set_cmp_func(sk, cmp) ((sk_X509_TRUST_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_TRUST_sk_type(sk), ossl_check_X509_TRUST_compfunc_type(cmp)))
+
+
+/* standard trust ids */
+# define X509_TRUST_DEFAULT 0 /* Only valid in purpose settings */
+# define X509_TRUST_COMPAT 1
+# define X509_TRUST_SSL_CLIENT 2
+# define X509_TRUST_SSL_SERVER 3
+# define X509_TRUST_EMAIL 4
+# define X509_TRUST_OBJECT_SIGN 5
+# define X509_TRUST_OCSP_SIGN 6
+# define X509_TRUST_OCSP_REQUEST 7
+# define X509_TRUST_TSA 8
+/* Keep these up to date! */
+# define X509_TRUST_MIN 1
+# define X509_TRUST_MAX 8
+
+/* trust_flags values */
+# define X509_TRUST_DYNAMIC (1U << 0)
+# define X509_TRUST_DYNAMIC_NAME (1U << 1)
+/* No compat trust if self-signed, preempts "DO_SS" */
+# define X509_TRUST_NO_SS_COMPAT (1U << 2)
+/* Compat trust if no explicit accepted trust EKUs */
+# define X509_TRUST_DO_SS_COMPAT (1U << 3)
+/* Accept "anyEKU" as a wildcard rejection OID and as a wildcard trust OID */
+# define X509_TRUST_OK_ANY_EKU (1U << 4)
+
+/* check_trust return codes */
+# define X509_TRUST_TRUSTED 1
+# define X509_TRUST_REJECTED 2
+# define X509_TRUST_UNTRUSTED 3
+
+int X509_TRUST_set(int *t, int trust);
+int X509_TRUST_get_count(void);
+X509_TRUST *X509_TRUST_get0(int idx);
+int X509_TRUST_get_by_id(int id);
+int X509_TRUST_add(int id, int flags, int (*ck) (X509_TRUST *, X509 *, int),
+ const char *name, int arg1, void *arg2);
+void X509_TRUST_cleanup(void);
+int X509_TRUST_get_flags(const X509_TRUST *xp);
+char *X509_TRUST_get0_name(const X509_TRUST *xp);
+int X509_TRUST_get_trust(const X509_TRUST *xp);
+
+int X509_trusted(const X509 *x);
+int X509_add1_trust_object(X509 *x, const ASN1_OBJECT *obj);
+int X509_add1_reject_object(X509 *x, const ASN1_OBJECT *obj);
+void X509_trust_clear(X509 *x);
+void X509_reject_clear(X509 *x);
+STACK_OF(ASN1_OBJECT) *X509_get0_trust_objects(X509 *x);
+STACK_OF(ASN1_OBJECT) *X509_get0_reject_objects(X509 *x);
+
+int (*X509_TRUST_set_default(int (*trust) (int, X509 *, int))) (int, X509 *,
+ int);
+int X509_check_trust(X509 *x, int id, int flags);
+
+int X509_verify_cert(X509_STORE_CTX *ctx);
+int X509_STORE_CTX_verify(X509_STORE_CTX *ctx);
+STACK_OF(X509) *X509_build_chain(X509 *target, STACK_OF(X509) *certs,
+ X509_STORE *store, int with_self_signed,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+int X509_STORE_set_depth(X509_STORE *store, int depth);
+
+typedef int (*X509_STORE_CTX_verify_cb)(int, X509_STORE_CTX *);
+int X509_STORE_CTX_print_verify_cb(int ok, X509_STORE_CTX *ctx);
+typedef int (*X509_STORE_CTX_verify_fn)(X509_STORE_CTX *);
+typedef int (*X509_STORE_CTX_get_issuer_fn)(X509 **issuer,
+ X509_STORE_CTX *ctx, X509 *x);
+typedef int (*X509_STORE_CTX_check_issued_fn)(X509_STORE_CTX *ctx,
+ X509 *x, X509 *issuer);
+typedef int (*X509_STORE_CTX_check_revocation_fn)(X509_STORE_CTX *ctx);
+typedef int (*X509_STORE_CTX_get_crl_fn)(X509_STORE_CTX *ctx,
+ X509_CRL **crl, X509 *x);
+typedef int (*X509_STORE_CTX_check_crl_fn)(X509_STORE_CTX *ctx, X509_CRL *crl);
+typedef int (*X509_STORE_CTX_cert_crl_fn)(X509_STORE_CTX *ctx,
+ X509_CRL *crl, X509 *x);
+typedef int (*X509_STORE_CTX_check_policy_fn)(X509_STORE_CTX *ctx);
+typedef STACK_OF(X509)
+ *(*X509_STORE_CTX_lookup_certs_fn)(X509_STORE_CTX *ctx,
+ const X509_NAME *nm);
+typedef STACK_OF(X509_CRL)
+ *(*X509_STORE_CTX_lookup_crls_fn)(const X509_STORE_CTX *ctx,
+ const X509_NAME *nm);
+typedef int (*X509_STORE_CTX_cleanup_fn)(X509_STORE_CTX *ctx);
+
+void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth);
+
+# define X509_STORE_CTX_set_app_data(ctx,data) \
+ X509_STORE_CTX_set_ex_data(ctx,0,data)
+# define X509_STORE_CTX_get_app_data(ctx) \
+ X509_STORE_CTX_get_ex_data(ctx,0)
+
+# define X509_L_FILE_LOAD 1
+# define X509_L_ADD_DIR 2
+# define X509_L_ADD_STORE 3
+# define X509_L_LOAD_STORE 4
+
+# define X509_LOOKUP_load_file(x,name,type) \
+ X509_LOOKUP_ctrl((x),X509_L_FILE_LOAD,(name),(long)(type),NULL)
+
+# define X509_LOOKUP_add_dir(x,name,type) \
+ X509_LOOKUP_ctrl((x),X509_L_ADD_DIR,(name),(long)(type),NULL)
+
+# define X509_LOOKUP_add_store(x,name) \
+ X509_LOOKUP_ctrl((x),X509_L_ADD_STORE,(name),0,NULL)
+
+# define X509_LOOKUP_load_store(x,name) \
+ X509_LOOKUP_ctrl((x),X509_L_LOAD_STORE,(name),0,NULL)
+
+# define X509_LOOKUP_load_file_ex(x, name, type, libctx, propq) \
+X509_LOOKUP_ctrl_ex((x), X509_L_FILE_LOAD, (name), (long)(type), NULL,\
+ (libctx), (propq))
+
+# define X509_LOOKUP_load_store_ex(x, name, libctx, propq) \
+X509_LOOKUP_ctrl_ex((x), X509_L_LOAD_STORE, (name), 0, NULL, \
+ (libctx), (propq))
+
+# define X509_LOOKUP_add_store_ex(x, name, libctx, propq) \
+X509_LOOKUP_ctrl_ex((x), X509_L_ADD_STORE, (name), 0, NULL, \
+ (libctx), (propq))
+
+# define X509_V_OK 0
+# define X509_V_ERR_UNSPECIFIED 1
+# define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2
+# define X509_V_ERR_UNABLE_TO_GET_CRL 3
+# define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4
+# define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5
+# define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6
+# define X509_V_ERR_CERT_SIGNATURE_FAILURE 7
+# define X509_V_ERR_CRL_SIGNATURE_FAILURE 8
+# define X509_V_ERR_CERT_NOT_YET_VALID 9
+# define X509_V_ERR_CERT_HAS_EXPIRED 10
+# define X509_V_ERR_CRL_NOT_YET_VALID 11
+# define X509_V_ERR_CRL_HAS_EXPIRED 12
+# define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13
+# define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14
+# define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15
+# define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16
+# define X509_V_ERR_OUT_OF_MEM 17
+# define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18
+# define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19
+# define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20
+# define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21
+# define X509_V_ERR_CERT_CHAIN_TOO_LONG 22
+# define X509_V_ERR_CERT_REVOKED 23
+# define X509_V_ERR_NO_ISSUER_PUBLIC_KEY 24
+# define X509_V_ERR_PATH_LENGTH_EXCEEDED 25
+# define X509_V_ERR_INVALID_PURPOSE 26
+# define X509_V_ERR_CERT_UNTRUSTED 27
+# define X509_V_ERR_CERT_REJECTED 28
+
+/* These are 'informational' when looking for issuer cert */
+# define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29
+# define X509_V_ERR_AKID_SKID_MISMATCH 30
+# define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31
+# define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32
+# define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33
+# define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34
+# define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35
+# define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36
+# define X509_V_ERR_INVALID_NON_CA 37
+# define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38
+# define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39
+# define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40
+# define X509_V_ERR_INVALID_EXTENSION 41
+# define X509_V_ERR_INVALID_POLICY_EXTENSION 42
+# define X509_V_ERR_NO_EXPLICIT_POLICY 43
+# define X509_V_ERR_DIFFERENT_CRL_SCOPE 44
+# define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45
+# define X509_V_ERR_UNNESTED_RESOURCE 46
+# define X509_V_ERR_PERMITTED_VIOLATION 47
+# define X509_V_ERR_EXCLUDED_VIOLATION 48
+# define X509_V_ERR_SUBTREE_MINMAX 49
+/* The application is not happy */
+# define X509_V_ERR_APPLICATION_VERIFICATION 50
+# define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51
+# define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52
+# define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53
+# define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54
+/* Another issuer check debug option */
+# define X509_V_ERR_PATH_LOOP 55
+/* Suite B mode algorithm violation */
+# define X509_V_ERR_SUITE_B_INVALID_VERSION 56
+# define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57
+# define X509_V_ERR_SUITE_B_INVALID_CURVE 58
+# define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59
+# define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60
+# define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61
+/* Host, email and IP check errors */
+# define X509_V_ERR_HOSTNAME_MISMATCH 62
+# define X509_V_ERR_EMAIL_MISMATCH 63
+# define X509_V_ERR_IP_ADDRESS_MISMATCH 64
+/* DANE TLSA errors */
+# define X509_V_ERR_DANE_NO_MATCH 65
+/* security level errors */
+# define X509_V_ERR_EE_KEY_TOO_SMALL 66
+# define X509_V_ERR_CA_KEY_TOO_SMALL 67
+# define X509_V_ERR_CA_MD_TOO_WEAK 68
+/* Caller error */
+# define X509_V_ERR_INVALID_CALL 69
+/* Issuer lookup error */
+# define X509_V_ERR_STORE_LOOKUP 70
+/* Certificate transparency */
+# define X509_V_ERR_NO_VALID_SCTS 71
+
+# define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72
+/* OCSP status errors */
+# define X509_V_ERR_OCSP_VERIFY_NEEDED 73 /* Need OCSP verification */
+# define X509_V_ERR_OCSP_VERIFY_FAILED 74 /* Couldn't verify cert through OCSP */
+# define X509_V_ERR_OCSP_CERT_UNKNOWN 75 /* Certificate wasn't recognized by the OCSP responder */
+
+# define X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM 76
+# define X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH 77
+
+/* Errors in case a check in X509_V_FLAG_X509_STRICT mode fails */
+# define X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY 78
+# define X509_V_ERR_INVALID_CA 79
+# define X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA 80
+# define X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN 81
+# define X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA 82
+# define X509_V_ERR_ISSUER_NAME_EMPTY 83
+# define X509_V_ERR_SUBJECT_NAME_EMPTY 84
+# define X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER 85
+# define X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER 86
+# define X509_V_ERR_EMPTY_SUBJECT_ALT_NAME 87
+# define X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL 88
+# define X509_V_ERR_CA_BCONS_NOT_CRITICAL 89
+# define X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL 90
+# define X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL 91
+# define X509_V_ERR_CA_CERT_MISSING_KEY_USAGE 92
+# define X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 93
+# define X509_V_ERR_EC_KEY_EXPLICIT_PARAMS 94
+
+/* Certificate verify flags */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_V_FLAG_CB_ISSUER_CHECK 0x0 /* Deprecated */
+# endif
+/* Use check time instead of current time */
+# define X509_V_FLAG_USE_CHECK_TIME 0x2
+/* Lookup CRLs */
+# define X509_V_FLAG_CRL_CHECK 0x4
+/* Lookup CRLs for whole chain */
+# define X509_V_FLAG_CRL_CHECK_ALL 0x8
+/* Ignore unhandled critical extensions */
+# define X509_V_FLAG_IGNORE_CRITICAL 0x10
+/* Disable workarounds for broken certificates */
+# define X509_V_FLAG_X509_STRICT 0x20
+/* Enable proxy certificate validation */
+# define X509_V_FLAG_ALLOW_PROXY_CERTS 0x40
+/* Enable policy checking */
+# define X509_V_FLAG_POLICY_CHECK 0x80
+/* Policy variable require-explicit-policy */
+# define X509_V_FLAG_EXPLICIT_POLICY 0x100
+/* Policy variable inhibit-any-policy */
+# define X509_V_FLAG_INHIBIT_ANY 0x200
+/* Policy variable inhibit-policy-mapping */
+# define X509_V_FLAG_INHIBIT_MAP 0x400
+/* Notify callback that policy is OK */
+# define X509_V_FLAG_NOTIFY_POLICY 0x800
+/* Extended CRL features such as indirect CRLs, alternate CRL signing keys */
+# define X509_V_FLAG_EXTENDED_CRL_SUPPORT 0x1000
+/* Delta CRL support */
+# define X509_V_FLAG_USE_DELTAS 0x2000
+/* Check self-signed CA signature */
+# define X509_V_FLAG_CHECK_SS_SIGNATURE 0x4000
+/* Use trusted store first */
+# define X509_V_FLAG_TRUSTED_FIRST 0x8000
+/* Suite B 128 bit only mode: not normally used */
+# define X509_V_FLAG_SUITEB_128_LOS_ONLY 0x10000
+/* Suite B 192 bit only mode */
+# define X509_V_FLAG_SUITEB_192_LOS 0x20000
+/* Suite B 128 bit mode allowing 192 bit algorithms */
+# define X509_V_FLAG_SUITEB_128_LOS 0x30000
+/* Allow partial chains if at least one certificate is in trusted store */
+# define X509_V_FLAG_PARTIAL_CHAIN 0x80000
+/*
+ * If the initial chain is not trusted, do not attempt to build an alternative
+ * chain. Alternate chain checking was introduced in 1.1.0. Setting this flag
+ * will force the behaviour to match that of previous versions.
+ */
+# define X509_V_FLAG_NO_ALT_CHAINS 0x100000
+/* Do not check certificate/CRL validity against current time */
+# define X509_V_FLAG_NO_CHECK_TIME 0x200000
+
+# define X509_VP_FLAG_DEFAULT 0x1
+# define X509_VP_FLAG_OVERWRITE 0x2
+# define X509_VP_FLAG_RESET_FLAGS 0x4
+# define X509_VP_FLAG_LOCKED 0x8
+# define X509_VP_FLAG_ONCE 0x10
+
+/* Internal use: mask of policy related options */
+# define X509_V_FLAG_POLICY_MASK (X509_V_FLAG_POLICY_CHECK \
+ | X509_V_FLAG_EXPLICIT_POLICY \
+ | X509_V_FLAG_INHIBIT_ANY \
+ | X509_V_FLAG_INHIBIT_MAP)
+
+int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type,
+ const X509_NAME *name);
+X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name);
+X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h,
+ X509_OBJECT *x);
+int X509_OBJECT_up_ref_count(X509_OBJECT *a);
+X509_OBJECT *X509_OBJECT_new(void);
+void X509_OBJECT_free(X509_OBJECT *a);
+X509_LOOKUP_TYPE X509_OBJECT_get_type(const X509_OBJECT *a);
+X509 *X509_OBJECT_get0_X509(const X509_OBJECT *a);
+int X509_OBJECT_set1_X509(X509_OBJECT *a, X509 *obj);
+X509_CRL *X509_OBJECT_get0_X509_CRL(const X509_OBJECT *a);
+int X509_OBJECT_set1_X509_CRL(X509_OBJECT *a, X509_CRL *obj);
+X509_STORE *X509_STORE_new(void);
+void X509_STORE_free(X509_STORE *v);
+int X509_STORE_lock(X509_STORE *ctx);
+int X509_STORE_unlock(X509_STORE *ctx);
+int X509_STORE_up_ref(X509_STORE *v);
+STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(const X509_STORE *v);
+STACK_OF(X509) *X509_STORE_get1_all_certs(X509_STORE *st);
+STACK_OF(X509) *X509_STORE_CTX_get1_certs(X509_STORE_CTX *st,
+ const X509_NAME *nm);
+STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(const X509_STORE_CTX *st,
+ const X509_NAME *nm);
+int X509_STORE_set_flags(X509_STORE *ctx, unsigned long flags);
+int X509_STORE_set_purpose(X509_STORE *ctx, int purpose);
+int X509_STORE_set_trust(X509_STORE *ctx, int trust);
+int X509_STORE_set1_param(X509_STORE *ctx, const X509_VERIFY_PARAM *pm);
+X509_VERIFY_PARAM *X509_STORE_get0_param(const X509_STORE *ctx);
+
+void X509_STORE_set_verify(X509_STORE *ctx, X509_STORE_CTX_verify_fn verify);
+#define X509_STORE_set_verify_func(ctx, func) \
+ X509_STORE_set_verify((ctx),(func))
+void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
+ X509_STORE_CTX_verify_fn verify);
+X509_STORE_CTX_verify_fn X509_STORE_get_verify(const X509_STORE *ctx);
+void X509_STORE_set_verify_cb(X509_STORE *ctx,
+ X509_STORE_CTX_verify_cb verify_cb);
+# define X509_STORE_set_verify_cb_func(ctx,func) \
+ X509_STORE_set_verify_cb((ctx),(func))
+X509_STORE_CTX_verify_cb X509_STORE_get_verify_cb(const X509_STORE *ctx);
+void X509_STORE_set_get_issuer(X509_STORE *ctx,
+ X509_STORE_CTX_get_issuer_fn get_issuer);
+X509_STORE_CTX_get_issuer_fn X509_STORE_get_get_issuer(const X509_STORE *ctx);
+void X509_STORE_set_check_issued(X509_STORE *ctx,
+ X509_STORE_CTX_check_issued_fn check_issued);
+X509_STORE_CTX_check_issued_fn X509_STORE_get_check_issued(const X509_STORE *ctx);
+void X509_STORE_set_check_revocation(X509_STORE *ctx,
+ X509_STORE_CTX_check_revocation_fn check_revocation);
+X509_STORE_CTX_check_revocation_fn
+ X509_STORE_get_check_revocation(const X509_STORE *ctx);
+void X509_STORE_set_get_crl(X509_STORE *ctx,
+ X509_STORE_CTX_get_crl_fn get_crl);
+X509_STORE_CTX_get_crl_fn X509_STORE_get_get_crl(const X509_STORE *ctx);
+void X509_STORE_set_check_crl(X509_STORE *ctx,
+ X509_STORE_CTX_check_crl_fn check_crl);
+X509_STORE_CTX_check_crl_fn X509_STORE_get_check_crl(const X509_STORE *ctx);
+void X509_STORE_set_cert_crl(X509_STORE *ctx,
+ X509_STORE_CTX_cert_crl_fn cert_crl);
+X509_STORE_CTX_cert_crl_fn X509_STORE_get_cert_crl(const X509_STORE *ctx);
+void X509_STORE_set_check_policy(X509_STORE *ctx,
+ X509_STORE_CTX_check_policy_fn check_policy);
+X509_STORE_CTX_check_policy_fn X509_STORE_get_check_policy(const X509_STORE *ctx);
+void X509_STORE_set_lookup_certs(X509_STORE *ctx,
+ X509_STORE_CTX_lookup_certs_fn lookup_certs);
+X509_STORE_CTX_lookup_certs_fn X509_STORE_get_lookup_certs(const X509_STORE *ctx);
+void X509_STORE_set_lookup_crls(X509_STORE *ctx,
+ X509_STORE_CTX_lookup_crls_fn lookup_crls);
+#define X509_STORE_set_lookup_crls_cb(ctx, func) \
+ X509_STORE_set_lookup_crls((ctx), (func))
+X509_STORE_CTX_lookup_crls_fn X509_STORE_get_lookup_crls(const X509_STORE *ctx);
+void X509_STORE_set_cleanup(X509_STORE *ctx,
+ X509_STORE_CTX_cleanup_fn cleanup);
+X509_STORE_CTX_cleanup_fn X509_STORE_get_cleanup(const X509_STORE *ctx);
+
+#define X509_STORE_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE, l, p, newf, dupf, freef)
+int X509_STORE_set_ex_data(X509_STORE *ctx, int idx, void *data);
+void *X509_STORE_get_ex_data(const X509_STORE *ctx, int idx);
+
+X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+X509_STORE_CTX *X509_STORE_CTX_new(void);
+
+int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
+
+void X509_STORE_CTX_free(X509_STORE_CTX *ctx);
+int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *trust_store,
+ X509 *target, STACK_OF(X509) *untrusted);
+void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk);
+void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx);
+
+X509_STORE *X509_STORE_CTX_get0_store(const X509_STORE_CTX *ctx);
+X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx);
+STACK_OF(X509)* X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk);
+void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
+ X509_STORE_CTX_verify_cb verify);
+X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_issued_fn X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_revocation_fn X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_policy_fn X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_lookup_certs_fn X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_lookup_crls_fn X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx);
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_STORE_CTX_get_chain X509_STORE_CTX_get0_chain
+# define X509_STORE_CTX_set_chain X509_STORE_CTX_set0_untrusted
+# define X509_STORE_CTX_trusted_stack X509_STORE_CTX_set0_trusted_stack
+# define X509_STORE_get_by_subject X509_STORE_CTX_get_by_subject
+# define X509_STORE_get1_certs X509_STORE_CTX_get1_certs
+# define X509_STORE_get1_crls X509_STORE_CTX_get1_crls
+/* the following macro is misspelled; use X509_STORE_get1_certs instead */
+# define X509_STORE_get1_cert X509_STORE_CTX_get1_certs
+/* the following macro is misspelled; use X509_STORE_get1_crls instead */
+# define X509_STORE_get1_crl X509_STORE_CTX_get1_crls
+#endif
+
+X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m);
+X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void);
+X509_LOOKUP_METHOD *X509_LOOKUP_file(void);
+X509_LOOKUP_METHOD *X509_LOOKUP_store(void);
+
+typedef int (*X509_LOOKUP_ctrl_fn)(X509_LOOKUP *ctx, int cmd, const char *argc,
+ long argl, char **ret);
+typedef int (*X509_LOOKUP_ctrl_ex_fn)(
+ X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+typedef int (*X509_LOOKUP_get_by_subject_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ X509_OBJECT *ret);
+typedef int (*X509_LOOKUP_get_by_subject_ex_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ X509_OBJECT *ret,
+ OSSL_LIB_CTX *libctx,
+ const char *propq);
+typedef int (*X509_LOOKUP_get_by_issuer_serial_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ const ASN1_INTEGER *serial,
+ X509_OBJECT *ret);
+typedef int (*X509_LOOKUP_get_by_fingerprint_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const unsigned char* bytes,
+ int len,
+ X509_OBJECT *ret);
+typedef int (*X509_LOOKUP_get_by_alias_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const char *str,
+ int len,
+ X509_OBJECT *ret);
+
+X509_LOOKUP_METHOD *X509_LOOKUP_meth_new(const char *name);
+void X509_LOOKUP_meth_free(X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_new_item(X509_LOOKUP_METHOD *method,
+ int (*new_item) (X509_LOOKUP *ctx));
+int (*X509_LOOKUP_meth_get_new_item(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_free(X509_LOOKUP_METHOD *method,
+ void (*free_fn) (X509_LOOKUP *ctx));
+void (*X509_LOOKUP_meth_get_free(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_init(X509_LOOKUP_METHOD *method,
+ int (*init) (X509_LOOKUP *ctx));
+int (*X509_LOOKUP_meth_get_init(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_shutdown(X509_LOOKUP_METHOD *method,
+ int (*shutdown) (X509_LOOKUP *ctx));
+int (*X509_LOOKUP_meth_get_shutdown(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_ctrl(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_ctrl_fn ctrl_fn);
+X509_LOOKUP_ctrl_fn X509_LOOKUP_meth_get_ctrl(const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_subject(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_subject_fn fn);
+X509_LOOKUP_get_by_subject_fn X509_LOOKUP_meth_get_get_by_subject(
+ const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_issuer_serial(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_issuer_serial_fn fn);
+X509_LOOKUP_get_by_issuer_serial_fn X509_LOOKUP_meth_get_get_by_issuer_serial(
+ const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_fingerprint(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_fingerprint_fn fn);
+X509_LOOKUP_get_by_fingerprint_fn X509_LOOKUP_meth_get_get_by_fingerprint(
+ const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_alias(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_alias_fn fn);
+X509_LOOKUP_get_by_alias_fn X509_LOOKUP_meth_get_get_by_alias(
+ const X509_LOOKUP_METHOD *method);
+
+
+int X509_STORE_add_cert(X509_STORE *ctx, X509 *x);
+int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x);
+
+int X509_STORE_CTX_get_by_subject(const X509_STORE_CTX *vs,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name, X509_OBJECT *ret);
+X509_OBJECT *X509_STORE_CTX_get_obj_by_subject(X509_STORE_CTX *vs,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name);
+
+int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc,
+ long argl, char **ret);
+int X509_LOOKUP_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argc, long argl,
+ char **ret, OSSL_LIB_CTX *libctx, const char *propq);
+
+int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type);
+int X509_load_cert_file_ex(X509_LOOKUP *ctx, const char *file, int type,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type);
+int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type);
+int X509_load_cert_crl_file_ex(X509_LOOKUP *ctx, const char *file, int type,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method);
+void X509_LOOKUP_free(X509_LOOKUP *ctx);
+int X509_LOOKUP_init(X509_LOOKUP *ctx);
+int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const X509_NAME *name, X509_OBJECT *ret);
+int X509_LOOKUP_by_subject_ex(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const X509_NAME *name, X509_OBJECT *ret,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ const ASN1_INTEGER *serial,
+ X509_OBJECT *ret);
+int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const unsigned char *bytes, int len,
+ X509_OBJECT *ret);
+int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const char *str, int len, X509_OBJECT *ret);
+int X509_LOOKUP_set_method_data(X509_LOOKUP *ctx, void *data);
+void *X509_LOOKUP_get_method_data(const X509_LOOKUP *ctx);
+X509_STORE *X509_LOOKUP_get_store(const X509_LOOKUP *ctx);
+int X509_LOOKUP_shutdown(X509_LOOKUP *ctx);
+
+int X509_STORE_load_file(X509_STORE *ctx, const char *file);
+int X509_STORE_load_path(X509_STORE *ctx, const char *path);
+int X509_STORE_load_store(X509_STORE *ctx, const char *store);
+int X509_STORE_load_locations(X509_STORE *ctx,
+ const char *file,
+ const char *dir);
+int X509_STORE_set_default_paths(X509_STORE *ctx);
+
+int X509_STORE_load_file_ex(X509_STORE *ctx, const char *file,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_STORE_load_store_ex(X509_STORE *ctx, const char *store,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_STORE_load_locations_ex(X509_STORE *ctx, const char *file,
+ const char *dir, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int X509_STORE_set_default_paths_ex(X509_STORE *ctx, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+#define X509_STORE_CTX_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX, l, p, newf, dupf, freef)
+int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data);
+void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx);
+int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int s);
+int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth);
+X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x);
+X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx);
+X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx);
+STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx);
+STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *target);
+void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *c, STACK_OF(X509) *sk);
+void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk);
+int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose);
+int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust);
+int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
+ int purpose, int trust);
+void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags);
+void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
+ time_t t);
+
+X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx);
+int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx);
+int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx);
+
+X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param);
+int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name);
+
+/*
+ * Bridge opacity barrier between libcrypt and libssl, also needed to support
+ * offline testing in test/danetest.c
+ */
+void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane);
+#define DANE_FLAG_NO_DANE_EE_NAMECHECKS (1L << 0)
+
+/* X509_VERIFY_PARAM functions */
+
+X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void);
+void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *to,
+ const X509_VERIFY_PARAM *from);
+int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to,
+ const X509_VERIFY_PARAM *from);
+int X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name);
+int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param,
+ unsigned long flags);
+int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param,
+ unsigned long flags);
+unsigned long X509_VERIFY_PARAM_get_flags(const X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose);
+int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust);
+void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth);
+void X509_VERIFY_PARAM_set_auth_level(X509_VERIFY_PARAM *param, int auth_level);
+time_t X509_VERIFY_PARAM_get_time(const X509_VERIFY_PARAM *param);
+void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t);
+int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param,
+ ASN1_OBJECT *policy);
+int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
+ STACK_OF(ASN1_OBJECT) *policies);
+
+int X509_VERIFY_PARAM_set_inh_flags(X509_VERIFY_PARAM *param,
+ uint32_t flags);
+uint32_t X509_VERIFY_PARAM_get_inh_flags(const X509_VERIFY_PARAM *param);
+
+char *X509_VERIFY_PARAM_get0_host(X509_VERIFY_PARAM *param, int idx);
+int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
+ const char *name, size_t namelen);
+int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
+ const char *name, size_t namelen);
+void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,
+ unsigned int flags);
+unsigned int X509_VERIFY_PARAM_get_hostflags(const X509_VERIFY_PARAM *param);
+char *X509_VERIFY_PARAM_get0_peername(const X509_VERIFY_PARAM *param);
+void X509_VERIFY_PARAM_move_peername(X509_VERIFY_PARAM *, X509_VERIFY_PARAM *);
+char *X509_VERIFY_PARAM_get0_email(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param,
+ const char *email, size_t emaillen);
+char *X509_VERIFY_PARAM_get1_ip_asc(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param,
+ const unsigned char *ip, size_t iplen);
+int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param,
+ const char *ipasc);
+
+int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_get_auth_level(const X509_VERIFY_PARAM *param);
+const char *X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param);
+
+int X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_get_count(void);
+const X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id);
+const X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name);
+void X509_VERIFY_PARAM_table_cleanup(void);
+
+/* Non positive return values are errors */
+#define X509_PCY_TREE_FAILURE -2 /* Failure to satisfy explicit policy */
+#define X509_PCY_TREE_INVALID -1 /* Inconsistent or invalid extensions */
+#define X509_PCY_TREE_INTERNAL 0 /* Internal error, most likely malloc */
+
+/*
+ * Positive return values form a bit mask, all but the first are internal to
+ * the library and don't appear in results from X509_policy_check().
+ */
+#define X509_PCY_TREE_VALID 1 /* The policy tree is valid */
+#define X509_PCY_TREE_EMPTY 2 /* The policy tree is empty */
+#define X509_PCY_TREE_EXPLICIT 4 /* Explicit policy required */
+
+int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy,
+ STACK_OF(X509) *certs,
+ STACK_OF(ASN1_OBJECT) *policy_oids, unsigned int flags);
+
+void X509_policy_tree_free(X509_POLICY_TREE *tree);
+
+int X509_policy_tree_level_count(const X509_POLICY_TREE *tree);
+X509_POLICY_LEVEL *X509_policy_tree_get0_level(const X509_POLICY_TREE *tree,
+ int i);
+
+STACK_OF(X509_POLICY_NODE)
+ *X509_policy_tree_get0_policies(const X509_POLICY_TREE *tree);
+
+STACK_OF(X509_POLICY_NODE)
+ *X509_policy_tree_get0_user_policies(const X509_POLICY_TREE *tree);
+
+int X509_policy_level_node_count(X509_POLICY_LEVEL *level);
+
+X509_POLICY_NODE *X509_policy_level_get0_node(const X509_POLICY_LEVEL *level,
+ int i);
+
+const ASN1_OBJECT *X509_policy_node_get0_policy(const X509_POLICY_NODE *node);
+
+STACK_OF(POLICYQUALINFO)
+ *X509_policy_node_get0_qualifiers(const X509_POLICY_NODE *node);
+const X509_POLICY_NODE
+ *X509_policy_node_get0_parent(const X509_POLICY_NODE *node);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/x509_vfy.h.in b/include/openssl/x509_vfy.h.in
new file mode 100644
index 00000000..80f18bd7
--- /dev/null
+++ b/include/openssl/x509_vfy.h.in
@@ -0,0 +1,797 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_X509_VFY_H
+# define OPENSSL_X509_VFY_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_X509_VFY_H
+# endif
+
+/*
+ * Protect against recursion, x509.h and x509_vfy.h each include the other.
+ */
+# ifndef OPENSSL_X509_H
+# include <openssl/x509.h>
+# endif
+
+# include <openssl/opensslconf.h>
+# include <openssl/lhash.h>
+# include <openssl/bio.h>
+# include <openssl/crypto.h>
+# include <openssl/symhacks.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*-
+SSL_CTX -> X509_STORE
+ -> X509_LOOKUP
+ ->X509_LOOKUP_METHOD
+ -> X509_LOOKUP
+ ->X509_LOOKUP_METHOD
+
+SSL -> X509_STORE_CTX
+ ->X509_STORE
+
+The X509_STORE holds the tables etc for verification stuff.
+A X509_STORE_CTX is used while validating a single certificate.
+The X509_STORE has X509_LOOKUPs for looking up certs.
+The X509_STORE then calls a function to actually verify the
+certificate chain.
+*/
+
+typedef enum {
+ X509_LU_NONE = 0,
+ X509_LU_X509, X509_LU_CRL
+} X509_LOOKUP_TYPE;
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+#define X509_LU_RETRY -1
+#define X509_LU_FAIL 0
+#endif
+
+{-
+ generate_stack_macros("X509_LOOKUP")
+ .generate_stack_macros("X509_OBJECT")
+ .generate_stack_macros("X509_VERIFY_PARAM");
+-}
+
+/* This is used for a table of trust checking functions */
+typedef struct x509_trust_st {
+ int trust;
+ int flags;
+ int (*check_trust) (struct x509_trust_st *, X509 *, int);
+ char *name;
+ int arg1;
+ void *arg2;
+} X509_TRUST;
+{-
+ generate_stack_macros("X509_TRUST");
+-}
+
+/* standard trust ids */
+# define X509_TRUST_DEFAULT 0 /* Only valid in purpose settings */
+# define X509_TRUST_COMPAT 1
+# define X509_TRUST_SSL_CLIENT 2
+# define X509_TRUST_SSL_SERVER 3
+# define X509_TRUST_EMAIL 4
+# define X509_TRUST_OBJECT_SIGN 5
+# define X509_TRUST_OCSP_SIGN 6
+# define X509_TRUST_OCSP_REQUEST 7
+# define X509_TRUST_TSA 8
+/* Keep these up to date! */
+# define X509_TRUST_MIN 1
+# define X509_TRUST_MAX 8
+
+/* trust_flags values */
+# define X509_TRUST_DYNAMIC (1U << 0)
+# define X509_TRUST_DYNAMIC_NAME (1U << 1)
+/* No compat trust if self-signed, preempts "DO_SS" */
+# define X509_TRUST_NO_SS_COMPAT (1U << 2)
+/* Compat trust if no explicit accepted trust EKUs */
+# define X509_TRUST_DO_SS_COMPAT (1U << 3)
+/* Accept "anyEKU" as a wildcard rejection OID and as a wildcard trust OID */
+# define X509_TRUST_OK_ANY_EKU (1U << 4)
+
+/* check_trust return codes */
+# define X509_TRUST_TRUSTED 1
+# define X509_TRUST_REJECTED 2
+# define X509_TRUST_UNTRUSTED 3
+
+int X509_TRUST_set(int *t, int trust);
+int X509_TRUST_get_count(void);
+X509_TRUST *X509_TRUST_get0(int idx);
+int X509_TRUST_get_by_id(int id);
+int X509_TRUST_add(int id, int flags, int (*ck) (X509_TRUST *, X509 *, int),
+ const char *name, int arg1, void *arg2);
+void X509_TRUST_cleanup(void);
+int X509_TRUST_get_flags(const X509_TRUST *xp);
+char *X509_TRUST_get0_name(const X509_TRUST *xp);
+int X509_TRUST_get_trust(const X509_TRUST *xp);
+
+int X509_trusted(const X509 *x);
+int X509_add1_trust_object(X509 *x, const ASN1_OBJECT *obj);
+int X509_add1_reject_object(X509 *x, const ASN1_OBJECT *obj);
+void X509_trust_clear(X509 *x);
+void X509_reject_clear(X509 *x);
+STACK_OF(ASN1_OBJECT) *X509_get0_trust_objects(X509 *x);
+STACK_OF(ASN1_OBJECT) *X509_get0_reject_objects(X509 *x);
+
+int (*X509_TRUST_set_default(int (*trust) (int, X509 *, int))) (int, X509 *,
+ int);
+int X509_check_trust(X509 *x, int id, int flags);
+
+int X509_verify_cert(X509_STORE_CTX *ctx);
+int X509_STORE_CTX_verify(X509_STORE_CTX *ctx);
+STACK_OF(X509) *X509_build_chain(X509 *target, STACK_OF(X509) *certs,
+ X509_STORE *store, int with_self_signed,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+int X509_STORE_set_depth(X509_STORE *store, int depth);
+
+typedef int (*X509_STORE_CTX_verify_cb)(int, X509_STORE_CTX *);
+int X509_STORE_CTX_print_verify_cb(int ok, X509_STORE_CTX *ctx);
+typedef int (*X509_STORE_CTX_verify_fn)(X509_STORE_CTX *);
+typedef int (*X509_STORE_CTX_get_issuer_fn)(X509 **issuer,
+ X509_STORE_CTX *ctx, X509 *x);
+typedef int (*X509_STORE_CTX_check_issued_fn)(X509_STORE_CTX *ctx,
+ X509 *x, X509 *issuer);
+typedef int (*X509_STORE_CTX_check_revocation_fn)(X509_STORE_CTX *ctx);
+typedef int (*X509_STORE_CTX_get_crl_fn)(X509_STORE_CTX *ctx,
+ X509_CRL **crl, X509 *x);
+typedef int (*X509_STORE_CTX_check_crl_fn)(X509_STORE_CTX *ctx, X509_CRL *crl);
+typedef int (*X509_STORE_CTX_cert_crl_fn)(X509_STORE_CTX *ctx,
+ X509_CRL *crl, X509 *x);
+typedef int (*X509_STORE_CTX_check_policy_fn)(X509_STORE_CTX *ctx);
+typedef STACK_OF(X509)
+ *(*X509_STORE_CTX_lookup_certs_fn)(X509_STORE_CTX *ctx,
+ const X509_NAME *nm);
+typedef STACK_OF(X509_CRL)
+ *(*X509_STORE_CTX_lookup_crls_fn)(const X509_STORE_CTX *ctx,
+ const X509_NAME *nm);
+typedef int (*X509_STORE_CTX_cleanup_fn)(X509_STORE_CTX *ctx);
+
+void X509_STORE_CTX_set_depth(X509_STORE_CTX *ctx, int depth);
+
+# define X509_STORE_CTX_set_app_data(ctx,data) \
+ X509_STORE_CTX_set_ex_data(ctx,0,data)
+# define X509_STORE_CTX_get_app_data(ctx) \
+ X509_STORE_CTX_get_ex_data(ctx,0)
+
+# define X509_L_FILE_LOAD 1
+# define X509_L_ADD_DIR 2
+# define X509_L_ADD_STORE 3
+# define X509_L_LOAD_STORE 4
+
+# define X509_LOOKUP_load_file(x,name,type) \
+ X509_LOOKUP_ctrl((x),X509_L_FILE_LOAD,(name),(long)(type),NULL)
+
+# define X509_LOOKUP_add_dir(x,name,type) \
+ X509_LOOKUP_ctrl((x),X509_L_ADD_DIR,(name),(long)(type),NULL)
+
+# define X509_LOOKUP_add_store(x,name) \
+ X509_LOOKUP_ctrl((x),X509_L_ADD_STORE,(name),0,NULL)
+
+# define X509_LOOKUP_load_store(x,name) \
+ X509_LOOKUP_ctrl((x),X509_L_LOAD_STORE,(name),0,NULL)
+
+# define X509_LOOKUP_load_file_ex(x, name, type, libctx, propq) \
+X509_LOOKUP_ctrl_ex((x), X509_L_FILE_LOAD, (name), (long)(type), NULL,\
+ (libctx), (propq))
+
+# define X509_LOOKUP_load_store_ex(x, name, libctx, propq) \
+X509_LOOKUP_ctrl_ex((x), X509_L_LOAD_STORE, (name), 0, NULL, \
+ (libctx), (propq))
+
+# define X509_LOOKUP_add_store_ex(x, name, libctx, propq) \
+X509_LOOKUP_ctrl_ex((x), X509_L_ADD_STORE, (name), 0, NULL, \
+ (libctx), (propq))
+
+# define X509_V_OK 0
+# define X509_V_ERR_UNSPECIFIED 1
+# define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT 2
+# define X509_V_ERR_UNABLE_TO_GET_CRL 3
+# define X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE 4
+# define X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE 5
+# define X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY 6
+# define X509_V_ERR_CERT_SIGNATURE_FAILURE 7
+# define X509_V_ERR_CRL_SIGNATURE_FAILURE 8
+# define X509_V_ERR_CERT_NOT_YET_VALID 9
+# define X509_V_ERR_CERT_HAS_EXPIRED 10
+# define X509_V_ERR_CRL_NOT_YET_VALID 11
+# define X509_V_ERR_CRL_HAS_EXPIRED 12
+# define X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD 13
+# define X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD 14
+# define X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD 15
+# define X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD 16
+# define X509_V_ERR_OUT_OF_MEM 17
+# define X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT 18
+# define X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN 19
+# define X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY 20
+# define X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE 21
+# define X509_V_ERR_CERT_CHAIN_TOO_LONG 22
+# define X509_V_ERR_CERT_REVOKED 23
+# define X509_V_ERR_NO_ISSUER_PUBLIC_KEY 24
+# define X509_V_ERR_PATH_LENGTH_EXCEEDED 25
+# define X509_V_ERR_INVALID_PURPOSE 26
+# define X509_V_ERR_CERT_UNTRUSTED 27
+# define X509_V_ERR_CERT_REJECTED 28
+
+/* These are 'informational' when looking for issuer cert */
+# define X509_V_ERR_SUBJECT_ISSUER_MISMATCH 29
+# define X509_V_ERR_AKID_SKID_MISMATCH 30
+# define X509_V_ERR_AKID_ISSUER_SERIAL_MISMATCH 31
+# define X509_V_ERR_KEYUSAGE_NO_CERTSIGN 32
+# define X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER 33
+# define X509_V_ERR_UNHANDLED_CRITICAL_EXTENSION 34
+# define X509_V_ERR_KEYUSAGE_NO_CRL_SIGN 35
+# define X509_V_ERR_UNHANDLED_CRITICAL_CRL_EXTENSION 36
+# define X509_V_ERR_INVALID_NON_CA 37
+# define X509_V_ERR_PROXY_PATH_LENGTH_EXCEEDED 38
+# define X509_V_ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE 39
+# define X509_V_ERR_PROXY_CERTIFICATES_NOT_ALLOWED 40
+# define X509_V_ERR_INVALID_EXTENSION 41
+# define X509_V_ERR_INVALID_POLICY_EXTENSION 42
+# define X509_V_ERR_NO_EXPLICIT_POLICY 43
+# define X509_V_ERR_DIFFERENT_CRL_SCOPE 44
+# define X509_V_ERR_UNSUPPORTED_EXTENSION_FEATURE 45
+# define X509_V_ERR_UNNESTED_RESOURCE 46
+# define X509_V_ERR_PERMITTED_VIOLATION 47
+# define X509_V_ERR_EXCLUDED_VIOLATION 48
+# define X509_V_ERR_SUBTREE_MINMAX 49
+/* The application is not happy */
+# define X509_V_ERR_APPLICATION_VERIFICATION 50
+# define X509_V_ERR_UNSUPPORTED_CONSTRAINT_TYPE 51
+# define X509_V_ERR_UNSUPPORTED_CONSTRAINT_SYNTAX 52
+# define X509_V_ERR_UNSUPPORTED_NAME_SYNTAX 53
+# define X509_V_ERR_CRL_PATH_VALIDATION_ERROR 54
+/* Another issuer check debug option */
+# define X509_V_ERR_PATH_LOOP 55
+/* Suite B mode algorithm violation */
+# define X509_V_ERR_SUITE_B_INVALID_VERSION 56
+# define X509_V_ERR_SUITE_B_INVALID_ALGORITHM 57
+# define X509_V_ERR_SUITE_B_INVALID_CURVE 58
+# define X509_V_ERR_SUITE_B_INVALID_SIGNATURE_ALGORITHM 59
+# define X509_V_ERR_SUITE_B_LOS_NOT_ALLOWED 60
+# define X509_V_ERR_SUITE_B_CANNOT_SIGN_P_384_WITH_P_256 61
+/* Host, email and IP check errors */
+# define X509_V_ERR_HOSTNAME_MISMATCH 62
+# define X509_V_ERR_EMAIL_MISMATCH 63
+# define X509_V_ERR_IP_ADDRESS_MISMATCH 64
+/* DANE TLSA errors */
+# define X509_V_ERR_DANE_NO_MATCH 65
+/* security level errors */
+# define X509_V_ERR_EE_KEY_TOO_SMALL 66
+# define X509_V_ERR_CA_KEY_TOO_SMALL 67
+# define X509_V_ERR_CA_MD_TOO_WEAK 68
+/* Caller error */
+# define X509_V_ERR_INVALID_CALL 69
+/* Issuer lookup error */
+# define X509_V_ERR_STORE_LOOKUP 70
+/* Certificate transparency */
+# define X509_V_ERR_NO_VALID_SCTS 71
+
+# define X509_V_ERR_PROXY_SUBJECT_NAME_VIOLATION 72
+/* OCSP status errors */
+# define X509_V_ERR_OCSP_VERIFY_NEEDED 73 /* Need OCSP verification */
+# define X509_V_ERR_OCSP_VERIFY_FAILED 74 /* Couldn't verify cert through OCSP */
+# define X509_V_ERR_OCSP_CERT_UNKNOWN 75 /* Certificate wasn't recognized by the OCSP responder */
+
+# define X509_V_ERR_UNSUPPORTED_SIGNATURE_ALGORITHM 76
+# define X509_V_ERR_SIGNATURE_ALGORITHM_MISMATCH 77
+
+/* Errors in case a check in X509_V_FLAG_X509_STRICT mode fails */
+# define X509_V_ERR_SIGNATURE_ALGORITHM_INCONSISTENCY 78
+# define X509_V_ERR_INVALID_CA 79
+# define X509_V_ERR_PATHLEN_INVALID_FOR_NON_CA 80
+# define X509_V_ERR_PATHLEN_WITHOUT_KU_KEY_CERT_SIGN 81
+# define X509_V_ERR_KU_KEY_CERT_SIGN_INVALID_FOR_NON_CA 82
+# define X509_V_ERR_ISSUER_NAME_EMPTY 83
+# define X509_V_ERR_SUBJECT_NAME_EMPTY 84
+# define X509_V_ERR_MISSING_AUTHORITY_KEY_IDENTIFIER 85
+# define X509_V_ERR_MISSING_SUBJECT_KEY_IDENTIFIER 86
+# define X509_V_ERR_EMPTY_SUBJECT_ALT_NAME 87
+# define X509_V_ERR_EMPTY_SUBJECT_SAN_NOT_CRITICAL 88
+# define X509_V_ERR_CA_BCONS_NOT_CRITICAL 89
+# define X509_V_ERR_AUTHORITY_KEY_IDENTIFIER_CRITICAL 90
+# define X509_V_ERR_SUBJECT_KEY_IDENTIFIER_CRITICAL 91
+# define X509_V_ERR_CA_CERT_MISSING_KEY_USAGE 92
+# define X509_V_ERR_EXTENSIONS_REQUIRE_VERSION_3 93
+# define X509_V_ERR_EC_KEY_EXPLICIT_PARAMS 94
+
+/* Certificate verify flags */
+# ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_V_FLAG_CB_ISSUER_CHECK 0x0 /* Deprecated */
+# endif
+/* Use check time instead of current time */
+# define X509_V_FLAG_USE_CHECK_TIME 0x2
+/* Lookup CRLs */
+# define X509_V_FLAG_CRL_CHECK 0x4
+/* Lookup CRLs for whole chain */
+# define X509_V_FLAG_CRL_CHECK_ALL 0x8
+/* Ignore unhandled critical extensions */
+# define X509_V_FLAG_IGNORE_CRITICAL 0x10
+/* Disable workarounds for broken certificates */
+# define X509_V_FLAG_X509_STRICT 0x20
+/* Enable proxy certificate validation */
+# define X509_V_FLAG_ALLOW_PROXY_CERTS 0x40
+/* Enable policy checking */
+# define X509_V_FLAG_POLICY_CHECK 0x80
+/* Policy variable require-explicit-policy */
+# define X509_V_FLAG_EXPLICIT_POLICY 0x100
+/* Policy variable inhibit-any-policy */
+# define X509_V_FLAG_INHIBIT_ANY 0x200
+/* Policy variable inhibit-policy-mapping */
+# define X509_V_FLAG_INHIBIT_MAP 0x400
+/* Notify callback that policy is OK */
+# define X509_V_FLAG_NOTIFY_POLICY 0x800
+/* Extended CRL features such as indirect CRLs, alternate CRL signing keys */
+# define X509_V_FLAG_EXTENDED_CRL_SUPPORT 0x1000
+/* Delta CRL support */
+# define X509_V_FLAG_USE_DELTAS 0x2000
+/* Check self-signed CA signature */
+# define X509_V_FLAG_CHECK_SS_SIGNATURE 0x4000
+/* Use trusted store first */
+# define X509_V_FLAG_TRUSTED_FIRST 0x8000
+/* Suite B 128 bit only mode: not normally used */
+# define X509_V_FLAG_SUITEB_128_LOS_ONLY 0x10000
+/* Suite B 192 bit only mode */
+# define X509_V_FLAG_SUITEB_192_LOS 0x20000
+/* Suite B 128 bit mode allowing 192 bit algorithms */
+# define X509_V_FLAG_SUITEB_128_LOS 0x30000
+/* Allow partial chains if at least one certificate is in trusted store */
+# define X509_V_FLAG_PARTIAL_CHAIN 0x80000
+/*
+ * If the initial chain is not trusted, do not attempt to build an alternative
+ * chain. Alternate chain checking was introduced in 1.1.0. Setting this flag
+ * will force the behaviour to match that of previous versions.
+ */
+# define X509_V_FLAG_NO_ALT_CHAINS 0x100000
+/* Do not check certificate/CRL validity against current time */
+# define X509_V_FLAG_NO_CHECK_TIME 0x200000
+
+# define X509_VP_FLAG_DEFAULT 0x1
+# define X509_VP_FLAG_OVERWRITE 0x2
+# define X509_VP_FLAG_RESET_FLAGS 0x4
+# define X509_VP_FLAG_LOCKED 0x8
+# define X509_VP_FLAG_ONCE 0x10
+
+/* Internal use: mask of policy related options */
+# define X509_V_FLAG_POLICY_MASK (X509_V_FLAG_POLICY_CHECK \
+ | X509_V_FLAG_EXPLICIT_POLICY \
+ | X509_V_FLAG_INHIBIT_ANY \
+ | X509_V_FLAG_INHIBIT_MAP)
+
+int X509_OBJECT_idx_by_subject(STACK_OF(X509_OBJECT) *h, X509_LOOKUP_TYPE type,
+ const X509_NAME *name);
+X509_OBJECT *X509_OBJECT_retrieve_by_subject(STACK_OF(X509_OBJECT) *h,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name);
+X509_OBJECT *X509_OBJECT_retrieve_match(STACK_OF(X509_OBJECT) *h,
+ X509_OBJECT *x);
+int X509_OBJECT_up_ref_count(X509_OBJECT *a);
+X509_OBJECT *X509_OBJECT_new(void);
+void X509_OBJECT_free(X509_OBJECT *a);
+X509_LOOKUP_TYPE X509_OBJECT_get_type(const X509_OBJECT *a);
+X509 *X509_OBJECT_get0_X509(const X509_OBJECT *a);
+int X509_OBJECT_set1_X509(X509_OBJECT *a, X509 *obj);
+X509_CRL *X509_OBJECT_get0_X509_CRL(const X509_OBJECT *a);
+int X509_OBJECT_set1_X509_CRL(X509_OBJECT *a, X509_CRL *obj);
+X509_STORE *X509_STORE_new(void);
+void X509_STORE_free(X509_STORE *v);
+int X509_STORE_lock(X509_STORE *ctx);
+int X509_STORE_unlock(X509_STORE *ctx);
+int X509_STORE_up_ref(X509_STORE *v);
+STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(const X509_STORE *v);
+STACK_OF(X509) *X509_STORE_get1_all_certs(X509_STORE *st);
+STACK_OF(X509) *X509_STORE_CTX_get1_certs(X509_STORE_CTX *st,
+ const X509_NAME *nm);
+STACK_OF(X509_CRL) *X509_STORE_CTX_get1_crls(const X509_STORE_CTX *st,
+ const X509_NAME *nm);
+int X509_STORE_set_flags(X509_STORE *ctx, unsigned long flags);
+int X509_STORE_set_purpose(X509_STORE *ctx, int purpose);
+int X509_STORE_set_trust(X509_STORE *ctx, int trust);
+int X509_STORE_set1_param(X509_STORE *ctx, const X509_VERIFY_PARAM *pm);
+X509_VERIFY_PARAM *X509_STORE_get0_param(const X509_STORE *ctx);
+
+void X509_STORE_set_verify(X509_STORE *ctx, X509_STORE_CTX_verify_fn verify);
+#define X509_STORE_set_verify_func(ctx, func) \
+ X509_STORE_set_verify((ctx),(func))
+void X509_STORE_CTX_set_verify(X509_STORE_CTX *ctx,
+ X509_STORE_CTX_verify_fn verify);
+X509_STORE_CTX_verify_fn X509_STORE_get_verify(const X509_STORE *ctx);
+void X509_STORE_set_verify_cb(X509_STORE *ctx,
+ X509_STORE_CTX_verify_cb verify_cb);
+# define X509_STORE_set_verify_cb_func(ctx,func) \
+ X509_STORE_set_verify_cb((ctx),(func))
+X509_STORE_CTX_verify_cb X509_STORE_get_verify_cb(const X509_STORE *ctx);
+void X509_STORE_set_get_issuer(X509_STORE *ctx,
+ X509_STORE_CTX_get_issuer_fn get_issuer);
+X509_STORE_CTX_get_issuer_fn X509_STORE_get_get_issuer(const X509_STORE *ctx);
+void X509_STORE_set_check_issued(X509_STORE *ctx,
+ X509_STORE_CTX_check_issued_fn check_issued);
+X509_STORE_CTX_check_issued_fn X509_STORE_get_check_issued(const X509_STORE *ctx);
+void X509_STORE_set_check_revocation(X509_STORE *ctx,
+ X509_STORE_CTX_check_revocation_fn check_revocation);
+X509_STORE_CTX_check_revocation_fn
+ X509_STORE_get_check_revocation(const X509_STORE *ctx);
+void X509_STORE_set_get_crl(X509_STORE *ctx,
+ X509_STORE_CTX_get_crl_fn get_crl);
+X509_STORE_CTX_get_crl_fn X509_STORE_get_get_crl(const X509_STORE *ctx);
+void X509_STORE_set_check_crl(X509_STORE *ctx,
+ X509_STORE_CTX_check_crl_fn check_crl);
+X509_STORE_CTX_check_crl_fn X509_STORE_get_check_crl(const X509_STORE *ctx);
+void X509_STORE_set_cert_crl(X509_STORE *ctx,
+ X509_STORE_CTX_cert_crl_fn cert_crl);
+X509_STORE_CTX_cert_crl_fn X509_STORE_get_cert_crl(const X509_STORE *ctx);
+void X509_STORE_set_check_policy(X509_STORE *ctx,
+ X509_STORE_CTX_check_policy_fn check_policy);
+X509_STORE_CTX_check_policy_fn X509_STORE_get_check_policy(const X509_STORE *ctx);
+void X509_STORE_set_lookup_certs(X509_STORE *ctx,
+ X509_STORE_CTX_lookup_certs_fn lookup_certs);
+X509_STORE_CTX_lookup_certs_fn X509_STORE_get_lookup_certs(const X509_STORE *ctx);
+void X509_STORE_set_lookup_crls(X509_STORE *ctx,
+ X509_STORE_CTX_lookup_crls_fn lookup_crls);
+#define X509_STORE_set_lookup_crls_cb(ctx, func) \
+ X509_STORE_set_lookup_crls((ctx), (func))
+X509_STORE_CTX_lookup_crls_fn X509_STORE_get_lookup_crls(const X509_STORE *ctx);
+void X509_STORE_set_cleanup(X509_STORE *ctx,
+ X509_STORE_CTX_cleanup_fn cleanup);
+X509_STORE_CTX_cleanup_fn X509_STORE_get_cleanup(const X509_STORE *ctx);
+
+#define X509_STORE_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE, l, p, newf, dupf, freef)
+int X509_STORE_set_ex_data(X509_STORE *ctx, int idx, void *data);
+void *X509_STORE_get_ex_data(const X509_STORE *ctx, int idx);
+
+X509_STORE_CTX *X509_STORE_CTX_new_ex(OSSL_LIB_CTX *libctx, const char *propq);
+X509_STORE_CTX *X509_STORE_CTX_new(void);
+
+int X509_STORE_CTX_get1_issuer(X509 **issuer, X509_STORE_CTX *ctx, X509 *x);
+
+void X509_STORE_CTX_free(X509_STORE_CTX *ctx);
+int X509_STORE_CTX_init(X509_STORE_CTX *ctx, X509_STORE *trust_store,
+ X509 *target, STACK_OF(X509) *untrusted);
+void X509_STORE_CTX_set0_trusted_stack(X509_STORE_CTX *ctx, STACK_OF(X509) *sk);
+void X509_STORE_CTX_cleanup(X509_STORE_CTX *ctx);
+
+X509_STORE *X509_STORE_CTX_get0_store(const X509_STORE_CTX *ctx);
+X509 *X509_STORE_CTX_get0_cert(const X509_STORE_CTX *ctx);
+STACK_OF(X509)* X509_STORE_CTX_get0_untrusted(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set0_untrusted(X509_STORE_CTX *ctx, STACK_OF(X509) *sk);
+void X509_STORE_CTX_set_verify_cb(X509_STORE_CTX *ctx,
+ X509_STORE_CTX_verify_cb verify);
+X509_STORE_CTX_verify_cb X509_STORE_CTX_get_verify_cb(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_verify_fn X509_STORE_CTX_get_verify(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_get_issuer_fn X509_STORE_CTX_get_get_issuer(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_issued_fn X509_STORE_CTX_get_check_issued(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_revocation_fn X509_STORE_CTX_get_check_revocation(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_get_crl_fn X509_STORE_CTX_get_get_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_crl_fn X509_STORE_CTX_get_check_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_cert_crl_fn X509_STORE_CTX_get_cert_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_check_policy_fn X509_STORE_CTX_get_check_policy(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_lookup_certs_fn X509_STORE_CTX_get_lookup_certs(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_lookup_crls_fn X509_STORE_CTX_get_lookup_crls(const X509_STORE_CTX *ctx);
+X509_STORE_CTX_cleanup_fn X509_STORE_CTX_get_cleanup(const X509_STORE_CTX *ctx);
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+# define X509_STORE_CTX_get_chain X509_STORE_CTX_get0_chain
+# define X509_STORE_CTX_set_chain X509_STORE_CTX_set0_untrusted
+# define X509_STORE_CTX_trusted_stack X509_STORE_CTX_set0_trusted_stack
+# define X509_STORE_get_by_subject X509_STORE_CTX_get_by_subject
+# define X509_STORE_get1_certs X509_STORE_CTX_get1_certs
+# define X509_STORE_get1_crls X509_STORE_CTX_get1_crls
+/* the following macro is misspelled; use X509_STORE_get1_certs instead */
+# define X509_STORE_get1_cert X509_STORE_CTX_get1_certs
+/* the following macro is misspelled; use X509_STORE_get1_crls instead */
+# define X509_STORE_get1_crl X509_STORE_CTX_get1_crls
+#endif
+
+X509_LOOKUP *X509_STORE_add_lookup(X509_STORE *v, X509_LOOKUP_METHOD *m);
+X509_LOOKUP_METHOD *X509_LOOKUP_hash_dir(void);
+X509_LOOKUP_METHOD *X509_LOOKUP_file(void);
+X509_LOOKUP_METHOD *X509_LOOKUP_store(void);
+
+typedef int (*X509_LOOKUP_ctrl_fn)(X509_LOOKUP *ctx, int cmd, const char *argc,
+ long argl, char **ret);
+typedef int (*X509_LOOKUP_ctrl_ex_fn)(
+ X509_LOOKUP *ctx, int cmd, const char *argc, long argl, char **ret,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+typedef int (*X509_LOOKUP_get_by_subject_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ X509_OBJECT *ret);
+typedef int (*X509_LOOKUP_get_by_subject_ex_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ X509_OBJECT *ret,
+ OSSL_LIB_CTX *libctx,
+ const char *propq);
+typedef int (*X509_LOOKUP_get_by_issuer_serial_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ const ASN1_INTEGER *serial,
+ X509_OBJECT *ret);
+typedef int (*X509_LOOKUP_get_by_fingerprint_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const unsigned char* bytes,
+ int len,
+ X509_OBJECT *ret);
+typedef int (*X509_LOOKUP_get_by_alias_fn)(X509_LOOKUP *ctx,
+ X509_LOOKUP_TYPE type,
+ const char *str,
+ int len,
+ X509_OBJECT *ret);
+
+X509_LOOKUP_METHOD *X509_LOOKUP_meth_new(const char *name);
+void X509_LOOKUP_meth_free(X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_new_item(X509_LOOKUP_METHOD *method,
+ int (*new_item) (X509_LOOKUP *ctx));
+int (*X509_LOOKUP_meth_get_new_item(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_free(X509_LOOKUP_METHOD *method,
+ void (*free_fn) (X509_LOOKUP *ctx));
+void (*X509_LOOKUP_meth_get_free(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_init(X509_LOOKUP_METHOD *method,
+ int (*init) (X509_LOOKUP *ctx));
+int (*X509_LOOKUP_meth_get_init(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_shutdown(X509_LOOKUP_METHOD *method,
+ int (*shutdown) (X509_LOOKUP *ctx));
+int (*X509_LOOKUP_meth_get_shutdown(const X509_LOOKUP_METHOD* method))
+ (X509_LOOKUP *ctx);
+
+int X509_LOOKUP_meth_set_ctrl(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_ctrl_fn ctrl_fn);
+X509_LOOKUP_ctrl_fn X509_LOOKUP_meth_get_ctrl(const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_subject(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_subject_fn fn);
+X509_LOOKUP_get_by_subject_fn X509_LOOKUP_meth_get_get_by_subject(
+ const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_issuer_serial(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_issuer_serial_fn fn);
+X509_LOOKUP_get_by_issuer_serial_fn X509_LOOKUP_meth_get_get_by_issuer_serial(
+ const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_fingerprint(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_fingerprint_fn fn);
+X509_LOOKUP_get_by_fingerprint_fn X509_LOOKUP_meth_get_get_by_fingerprint(
+ const X509_LOOKUP_METHOD *method);
+
+int X509_LOOKUP_meth_set_get_by_alias(X509_LOOKUP_METHOD *method,
+ X509_LOOKUP_get_by_alias_fn fn);
+X509_LOOKUP_get_by_alias_fn X509_LOOKUP_meth_get_get_by_alias(
+ const X509_LOOKUP_METHOD *method);
+
+
+int X509_STORE_add_cert(X509_STORE *ctx, X509 *x);
+int X509_STORE_add_crl(X509_STORE *ctx, X509_CRL *x);
+
+int X509_STORE_CTX_get_by_subject(const X509_STORE_CTX *vs,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name, X509_OBJECT *ret);
+X509_OBJECT *X509_STORE_CTX_get_obj_by_subject(X509_STORE_CTX *vs,
+ X509_LOOKUP_TYPE type,
+ const X509_NAME *name);
+
+int X509_LOOKUP_ctrl(X509_LOOKUP *ctx, int cmd, const char *argc,
+ long argl, char **ret);
+int X509_LOOKUP_ctrl_ex(X509_LOOKUP *ctx, int cmd, const char *argc, long argl,
+ char **ret, OSSL_LIB_CTX *libctx, const char *propq);
+
+int X509_load_cert_file(X509_LOOKUP *ctx, const char *file, int type);
+int X509_load_cert_file_ex(X509_LOOKUP *ctx, const char *file, int type,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_load_crl_file(X509_LOOKUP *ctx, const char *file, int type);
+int X509_load_cert_crl_file(X509_LOOKUP *ctx, const char *file, int type);
+int X509_load_cert_crl_file_ex(X509_LOOKUP *ctx, const char *file, int type,
+ OSSL_LIB_CTX *libctx, const char *propq);
+
+X509_LOOKUP *X509_LOOKUP_new(X509_LOOKUP_METHOD *method);
+void X509_LOOKUP_free(X509_LOOKUP *ctx);
+int X509_LOOKUP_init(X509_LOOKUP *ctx);
+int X509_LOOKUP_by_subject(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const X509_NAME *name, X509_OBJECT *ret);
+int X509_LOOKUP_by_subject_ex(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const X509_NAME *name, X509_OBJECT *ret,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_LOOKUP_by_issuer_serial(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const X509_NAME *name,
+ const ASN1_INTEGER *serial,
+ X509_OBJECT *ret);
+int X509_LOOKUP_by_fingerprint(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const unsigned char *bytes, int len,
+ X509_OBJECT *ret);
+int X509_LOOKUP_by_alias(X509_LOOKUP *ctx, X509_LOOKUP_TYPE type,
+ const char *str, int len, X509_OBJECT *ret);
+int X509_LOOKUP_set_method_data(X509_LOOKUP *ctx, void *data);
+void *X509_LOOKUP_get_method_data(const X509_LOOKUP *ctx);
+X509_STORE *X509_LOOKUP_get_store(const X509_LOOKUP *ctx);
+int X509_LOOKUP_shutdown(X509_LOOKUP *ctx);
+
+int X509_STORE_load_file(X509_STORE *ctx, const char *file);
+int X509_STORE_load_path(X509_STORE *ctx, const char *path);
+int X509_STORE_load_store(X509_STORE *ctx, const char *store);
+int X509_STORE_load_locations(X509_STORE *ctx,
+ const char *file,
+ const char *dir);
+int X509_STORE_set_default_paths(X509_STORE *ctx);
+
+int X509_STORE_load_file_ex(X509_STORE *ctx, const char *file,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_STORE_load_store_ex(X509_STORE *ctx, const char *store,
+ OSSL_LIB_CTX *libctx, const char *propq);
+int X509_STORE_load_locations_ex(X509_STORE *ctx, const char *file,
+ const char *dir, OSSL_LIB_CTX *libctx,
+ const char *propq);
+int X509_STORE_set_default_paths_ex(X509_STORE *ctx, OSSL_LIB_CTX *libctx,
+ const char *propq);
+
+#define X509_STORE_CTX_get_ex_new_index(l, p, newf, dupf, freef) \
+ CRYPTO_get_ex_new_index(CRYPTO_EX_INDEX_X509_STORE_CTX, l, p, newf, dupf, freef)
+int X509_STORE_CTX_set_ex_data(X509_STORE_CTX *ctx, int idx, void *data);
+void *X509_STORE_CTX_get_ex_data(const X509_STORE_CTX *ctx, int idx);
+int X509_STORE_CTX_get_error(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_error(X509_STORE_CTX *ctx, int s);
+int X509_STORE_CTX_get_error_depth(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_error_depth(X509_STORE_CTX *ctx, int depth);
+X509 *X509_STORE_CTX_get_current_cert(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_current_cert(X509_STORE_CTX *ctx, X509 *x);
+X509 *X509_STORE_CTX_get0_current_issuer(const X509_STORE_CTX *ctx);
+X509_CRL *X509_STORE_CTX_get0_current_crl(const X509_STORE_CTX *ctx);
+X509_STORE_CTX *X509_STORE_CTX_get0_parent_ctx(const X509_STORE_CTX *ctx);
+STACK_OF(X509) *X509_STORE_CTX_get0_chain(const X509_STORE_CTX *ctx);
+STACK_OF(X509) *X509_STORE_CTX_get1_chain(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set_cert(X509_STORE_CTX *ctx, X509 *target);
+void X509_STORE_CTX_set0_verified_chain(X509_STORE_CTX *c, STACK_OF(X509) *sk);
+void X509_STORE_CTX_set0_crls(X509_STORE_CTX *ctx, STACK_OF(X509_CRL) *sk);
+int X509_STORE_CTX_set_purpose(X509_STORE_CTX *ctx, int purpose);
+int X509_STORE_CTX_set_trust(X509_STORE_CTX *ctx, int trust);
+int X509_STORE_CTX_purpose_inherit(X509_STORE_CTX *ctx, int def_purpose,
+ int purpose, int trust);
+void X509_STORE_CTX_set_flags(X509_STORE_CTX *ctx, unsigned long flags);
+void X509_STORE_CTX_set_time(X509_STORE_CTX *ctx, unsigned long flags,
+ time_t t);
+
+X509_POLICY_TREE *X509_STORE_CTX_get0_policy_tree(const X509_STORE_CTX *ctx);
+int X509_STORE_CTX_get_explicit_policy(const X509_STORE_CTX *ctx);
+int X509_STORE_CTX_get_num_untrusted(const X509_STORE_CTX *ctx);
+
+X509_VERIFY_PARAM *X509_STORE_CTX_get0_param(const X509_STORE_CTX *ctx);
+void X509_STORE_CTX_set0_param(X509_STORE_CTX *ctx, X509_VERIFY_PARAM *param);
+int X509_STORE_CTX_set_default(X509_STORE_CTX *ctx, const char *name);
+
+/*
+ * Bridge opacity barrier between libcrypt and libssl, also needed to support
+ * offline testing in test/danetest.c
+ */
+void X509_STORE_CTX_set0_dane(X509_STORE_CTX *ctx, SSL_DANE *dane);
+#define DANE_FLAG_NO_DANE_EE_NAMECHECKS (1L << 0)
+
+/* X509_VERIFY_PARAM functions */
+
+X509_VERIFY_PARAM *X509_VERIFY_PARAM_new(void);
+void X509_VERIFY_PARAM_free(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_inherit(X509_VERIFY_PARAM *to,
+ const X509_VERIFY_PARAM *from);
+int X509_VERIFY_PARAM_set1(X509_VERIFY_PARAM *to,
+ const X509_VERIFY_PARAM *from);
+int X509_VERIFY_PARAM_set1_name(X509_VERIFY_PARAM *param, const char *name);
+int X509_VERIFY_PARAM_set_flags(X509_VERIFY_PARAM *param,
+ unsigned long flags);
+int X509_VERIFY_PARAM_clear_flags(X509_VERIFY_PARAM *param,
+ unsigned long flags);
+unsigned long X509_VERIFY_PARAM_get_flags(const X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_set_purpose(X509_VERIFY_PARAM *param, int purpose);
+int X509_VERIFY_PARAM_set_trust(X509_VERIFY_PARAM *param, int trust);
+void X509_VERIFY_PARAM_set_depth(X509_VERIFY_PARAM *param, int depth);
+void X509_VERIFY_PARAM_set_auth_level(X509_VERIFY_PARAM *param, int auth_level);
+time_t X509_VERIFY_PARAM_get_time(const X509_VERIFY_PARAM *param);
+void X509_VERIFY_PARAM_set_time(X509_VERIFY_PARAM *param, time_t t);
+int X509_VERIFY_PARAM_add0_policy(X509_VERIFY_PARAM *param,
+ ASN1_OBJECT *policy);
+int X509_VERIFY_PARAM_set1_policies(X509_VERIFY_PARAM *param,
+ STACK_OF(ASN1_OBJECT) *policies);
+
+int X509_VERIFY_PARAM_set_inh_flags(X509_VERIFY_PARAM *param,
+ uint32_t flags);
+uint32_t X509_VERIFY_PARAM_get_inh_flags(const X509_VERIFY_PARAM *param);
+
+char *X509_VERIFY_PARAM_get0_host(X509_VERIFY_PARAM *param, int idx);
+int X509_VERIFY_PARAM_set1_host(X509_VERIFY_PARAM *param,
+ const char *name, size_t namelen);
+int X509_VERIFY_PARAM_add1_host(X509_VERIFY_PARAM *param,
+ const char *name, size_t namelen);
+void X509_VERIFY_PARAM_set_hostflags(X509_VERIFY_PARAM *param,
+ unsigned int flags);
+unsigned int X509_VERIFY_PARAM_get_hostflags(const X509_VERIFY_PARAM *param);
+char *X509_VERIFY_PARAM_get0_peername(const X509_VERIFY_PARAM *param);
+void X509_VERIFY_PARAM_move_peername(X509_VERIFY_PARAM *, X509_VERIFY_PARAM *);
+char *X509_VERIFY_PARAM_get0_email(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_set1_email(X509_VERIFY_PARAM *param,
+ const char *email, size_t emaillen);
+char *X509_VERIFY_PARAM_get1_ip_asc(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_set1_ip(X509_VERIFY_PARAM *param,
+ const unsigned char *ip, size_t iplen);
+int X509_VERIFY_PARAM_set1_ip_asc(X509_VERIFY_PARAM *param,
+ const char *ipasc);
+
+int X509_VERIFY_PARAM_get_depth(const X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_get_auth_level(const X509_VERIFY_PARAM *param);
+const char *X509_VERIFY_PARAM_get0_name(const X509_VERIFY_PARAM *param);
+
+int X509_VERIFY_PARAM_add0_table(X509_VERIFY_PARAM *param);
+int X509_VERIFY_PARAM_get_count(void);
+const X509_VERIFY_PARAM *X509_VERIFY_PARAM_get0(int id);
+const X509_VERIFY_PARAM *X509_VERIFY_PARAM_lookup(const char *name);
+void X509_VERIFY_PARAM_table_cleanup(void);
+
+/* Non positive return values are errors */
+#define X509_PCY_TREE_FAILURE -2 /* Failure to satisfy explicit policy */
+#define X509_PCY_TREE_INVALID -1 /* Inconsistent or invalid extensions */
+#define X509_PCY_TREE_INTERNAL 0 /* Internal error, most likely malloc */
+
+/*
+ * Positive return values form a bit mask, all but the first are internal to
+ * the library and don't appear in results from X509_policy_check().
+ */
+#define X509_PCY_TREE_VALID 1 /* The policy tree is valid */
+#define X509_PCY_TREE_EMPTY 2 /* The policy tree is empty */
+#define X509_PCY_TREE_EXPLICIT 4 /* Explicit policy required */
+
+int X509_policy_check(X509_POLICY_TREE **ptree, int *pexplicit_policy,
+ STACK_OF(X509) *certs,
+ STACK_OF(ASN1_OBJECT) *policy_oids, unsigned int flags);
+
+void X509_policy_tree_free(X509_POLICY_TREE *tree);
+
+int X509_policy_tree_level_count(const X509_POLICY_TREE *tree);
+X509_POLICY_LEVEL *X509_policy_tree_get0_level(const X509_POLICY_TREE *tree,
+ int i);
+
+STACK_OF(X509_POLICY_NODE)
+ *X509_policy_tree_get0_policies(const X509_POLICY_TREE *tree);
+
+STACK_OF(X509_POLICY_NODE)
+ *X509_policy_tree_get0_user_policies(const X509_POLICY_TREE *tree);
+
+int X509_policy_level_node_count(X509_POLICY_LEVEL *level);
+
+X509_POLICY_NODE *X509_policy_level_get0_node(const X509_POLICY_LEVEL *level,
+ int i);
+
+const ASN1_OBJECT *X509_policy_node_get0_policy(const X509_POLICY_NODE *node);
+
+STACK_OF(POLICYQUALINFO)
+ *X509_policy_node_get0_qualifiers(const X509_POLICY_NODE *node);
+const X509_POLICY_NODE
+ *X509_policy_node_get0_parent(const X509_POLICY_NODE *node);
+
+#ifdef __cplusplus
+}
+#endif
+#endif
diff --git a/include/openssl/x509err.h b/include/openssl/x509err.h
new file mode 100644
index 00000000..a56facd4
--- /dev/null
+++ b/include/openssl/x509err.h
@@ -0,0 +1,68 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_X509ERR_H
+# define OPENSSL_X509ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * X509 reason codes.
+ */
+# define X509_R_AKID_MISMATCH 110
+# define X509_R_BAD_SELECTOR 133
+# define X509_R_BAD_X509_FILETYPE 100
+# define X509_R_BASE64_DECODE_ERROR 118
+# define X509_R_CANT_CHECK_DH_KEY 114
+# define X509_R_CERTIFICATE_VERIFICATION_FAILED 139
+# define X509_R_CERT_ALREADY_IN_HASH_TABLE 101
+# define X509_R_CRL_ALREADY_DELTA 127
+# define X509_R_CRL_VERIFY_FAILURE 131
+# define X509_R_ERROR_GETTING_MD_BY_NID 141
+# define X509_R_ERROR_USING_SIGINF_SET 142
+# define X509_R_IDP_MISMATCH 128
+# define X509_R_INVALID_ATTRIBUTES 138
+# define X509_R_INVALID_DIRECTORY 113
+# define X509_R_INVALID_DISTPOINT 143
+# define X509_R_INVALID_FIELD_NAME 119
+# define X509_R_INVALID_TRUST 123
+# define X509_R_ISSUER_MISMATCH 129
+# define X509_R_KEY_TYPE_MISMATCH 115
+# define X509_R_KEY_VALUES_MISMATCH 116
+# define X509_R_LOADING_CERT_DIR 103
+# define X509_R_LOADING_DEFAULTS 104
+# define X509_R_METHOD_NOT_SUPPORTED 124
+# define X509_R_NAME_TOO_LONG 134
+# define X509_R_NEWER_CRL_NOT_NEWER 132
+# define X509_R_NO_CERTIFICATE_FOUND 135
+# define X509_R_NO_CERTIFICATE_OR_CRL_FOUND 136
+# define X509_R_NO_CERT_SET_FOR_US_TO_VERIFY 105
+# define X509_R_NO_CRL_FOUND 137
+# define X509_R_NO_CRL_NUMBER 130
+# define X509_R_PUBLIC_KEY_DECODE_ERROR 125
+# define X509_R_PUBLIC_KEY_ENCODE_ERROR 126
+# define X509_R_SHOULD_RETRY 106
+# define X509_R_UNABLE_TO_FIND_PARAMETERS_IN_CHAIN 107
+# define X509_R_UNABLE_TO_GET_CERTS_PUBLIC_KEY 108
+# define X509_R_UNKNOWN_KEY_TYPE 117
+# define X509_R_UNKNOWN_NID 109
+# define X509_R_UNKNOWN_PURPOSE_ID 121
+# define X509_R_UNKNOWN_SIGID_ALGS 144
+# define X509_R_UNKNOWN_TRUST_ID 120
+# define X509_R_UNSUPPORTED_ALGORITHM 111
+# define X509_R_WRONG_LOOKUP_TYPE 112
+# define X509_R_WRONG_TYPE 122
+
+#endif
diff --git a/include/openssl/x509v3.h b/include/openssl/x509v3.h
new file mode 100644
index 00000000..78c390b3
--- /dev/null
+++ b/include/openssl/x509v3.h
@@ -0,0 +1,1450 @@
+/*
+ * WARNING: do not edit!
+ * Generated by makefile from include\openssl\x509v3.h.in
+ *
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+
+
+#ifndef OPENSSL_X509V3_H
+# define OPENSSL_X509V3_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_X509V3_H
+# endif
+
+# include <openssl/bio.h>
+# include <openssl/x509.h>
+# include <openssl/conf.h>
+# include <openssl/x509v3err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Forward reference */
+struct v3_ext_method;
+struct v3_ext_ctx;
+
+/* Useful typedefs */
+
+typedef void *(*X509V3_EXT_NEW)(void);
+typedef void (*X509V3_EXT_FREE) (void *);
+typedef void *(*X509V3_EXT_D2I)(void *, const unsigned char **, long);
+typedef int (*X509V3_EXT_I2D) (const void *, unsigned char **);
+typedef STACK_OF(CONF_VALUE) *
+ (*X509V3_EXT_I2V) (const struct v3_ext_method *method, void *ext,
+ STACK_OF(CONF_VALUE) *extlist);
+typedef void *(*X509V3_EXT_V2I)(const struct v3_ext_method *method,
+ struct v3_ext_ctx *ctx,
+ STACK_OF(CONF_VALUE) *values);
+typedef char *(*X509V3_EXT_I2S)(const struct v3_ext_method *method,
+ void *ext);
+typedef void *(*X509V3_EXT_S2I)(const struct v3_ext_method *method,
+ struct v3_ext_ctx *ctx, const char *str);
+typedef int (*X509V3_EXT_I2R) (const struct v3_ext_method *method, void *ext,
+ BIO *out, int indent);
+typedef void *(*X509V3_EXT_R2I)(const struct v3_ext_method *method,
+ struct v3_ext_ctx *ctx, const char *str);
+
+/* V3 extension structure */
+
+struct v3_ext_method {
+ int ext_nid;
+ int ext_flags;
+/* If this is set the following four fields are ignored */
+ ASN1_ITEM_EXP *it;
+/* Old style ASN1 calls */
+ X509V3_EXT_NEW ext_new;
+ X509V3_EXT_FREE ext_free;
+ X509V3_EXT_D2I d2i;
+ X509V3_EXT_I2D i2d;
+/* The following pair is used for string extensions */
+ X509V3_EXT_I2S i2s;
+ X509V3_EXT_S2I s2i;
+/* The following pair is used for multi-valued extensions */
+ X509V3_EXT_I2V i2v;
+ X509V3_EXT_V2I v2i;
+/* The following are used for raw extensions */
+ X509V3_EXT_I2R i2r;
+ X509V3_EXT_R2I r2i;
+ void *usr_data; /* Any extension specific data */
+};
+
+typedef struct X509V3_CONF_METHOD_st {
+ char *(*get_string) (void *db, const char *section, const char *value);
+ STACK_OF(CONF_VALUE) *(*get_section) (void *db, const char *section);
+ void (*free_string) (void *db, char *string);
+ void (*free_section) (void *db, STACK_OF(CONF_VALUE) *section);
+} X509V3_CONF_METHOD;
+
+/* Context specific info for producing X509 v3 extensions*/
+struct v3_ext_ctx {
+# define X509V3_CTX_TEST 0x1
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define CTX_TEST X509V3_CTX_TEST
+# endif
+# define X509V3_CTX_REPLACE 0x2
+ int flags;
+ X509 *issuer_cert;
+ X509 *subject_cert;
+ X509_REQ *subject_req;
+ X509_CRL *crl;
+ X509V3_CONF_METHOD *db_meth;
+ void *db;
+ EVP_PKEY *issuer_pkey;
+/* Maybe more here */
+};
+
+typedef struct v3_ext_method X509V3_EXT_METHOD;
+
+SKM_DEFINE_STACK_OF_INTERNAL(X509V3_EXT_METHOD, X509V3_EXT_METHOD, X509V3_EXT_METHOD)
+#define sk_X509V3_EXT_METHOD_num(sk) OPENSSL_sk_num(ossl_check_const_X509V3_EXT_METHOD_sk_type(sk))
+#define sk_X509V3_EXT_METHOD_value(sk, idx) ((X509V3_EXT_METHOD *)OPENSSL_sk_value(ossl_check_const_X509V3_EXT_METHOD_sk_type(sk), (idx)))
+#define sk_X509V3_EXT_METHOD_new(cmp) ((STACK_OF(X509V3_EXT_METHOD) *)OPENSSL_sk_new(ossl_check_X509V3_EXT_METHOD_compfunc_type(cmp)))
+#define sk_X509V3_EXT_METHOD_new_null() ((STACK_OF(X509V3_EXT_METHOD) *)OPENSSL_sk_new_null())
+#define sk_X509V3_EXT_METHOD_new_reserve(cmp, n) ((STACK_OF(X509V3_EXT_METHOD) *)OPENSSL_sk_new_reserve(ossl_check_X509V3_EXT_METHOD_compfunc_type(cmp), (n)))
+#define sk_X509V3_EXT_METHOD_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509V3_EXT_METHOD_sk_type(sk), (n))
+#define sk_X509V3_EXT_METHOD_free(sk) OPENSSL_sk_free(ossl_check_X509V3_EXT_METHOD_sk_type(sk))
+#define sk_X509V3_EXT_METHOD_zero(sk) OPENSSL_sk_zero(ossl_check_X509V3_EXT_METHOD_sk_type(sk))
+#define sk_X509V3_EXT_METHOD_delete(sk, i) ((X509V3_EXT_METHOD *)OPENSSL_sk_delete(ossl_check_X509V3_EXT_METHOD_sk_type(sk), (i)))
+#define sk_X509V3_EXT_METHOD_delete_ptr(sk, ptr) ((X509V3_EXT_METHOD *)OPENSSL_sk_delete_ptr(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_type(ptr)))
+#define sk_X509V3_EXT_METHOD_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_type(ptr))
+#define sk_X509V3_EXT_METHOD_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_type(ptr))
+#define sk_X509V3_EXT_METHOD_pop(sk) ((X509V3_EXT_METHOD *)OPENSSL_sk_pop(ossl_check_X509V3_EXT_METHOD_sk_type(sk)))
+#define sk_X509V3_EXT_METHOD_shift(sk) ((X509V3_EXT_METHOD *)OPENSSL_sk_shift(ossl_check_X509V3_EXT_METHOD_sk_type(sk)))
+#define sk_X509V3_EXT_METHOD_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509V3_EXT_METHOD_sk_type(sk),ossl_check_X509V3_EXT_METHOD_freefunc_type(freefunc))
+#define sk_X509V3_EXT_METHOD_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_type(ptr), (idx))
+#define sk_X509V3_EXT_METHOD_set(sk, idx, ptr) ((X509V3_EXT_METHOD *)OPENSSL_sk_set(ossl_check_X509V3_EXT_METHOD_sk_type(sk), (idx), ossl_check_X509V3_EXT_METHOD_type(ptr)))
+#define sk_X509V3_EXT_METHOD_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_type(ptr))
+#define sk_X509V3_EXT_METHOD_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_type(ptr))
+#define sk_X509V3_EXT_METHOD_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_type(ptr), pnum)
+#define sk_X509V3_EXT_METHOD_sort(sk) OPENSSL_sk_sort(ossl_check_X509V3_EXT_METHOD_sk_type(sk))
+#define sk_X509V3_EXT_METHOD_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509V3_EXT_METHOD_sk_type(sk))
+#define sk_X509V3_EXT_METHOD_dup(sk) ((STACK_OF(X509V3_EXT_METHOD) *)OPENSSL_sk_dup(ossl_check_const_X509V3_EXT_METHOD_sk_type(sk)))
+#define sk_X509V3_EXT_METHOD_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509V3_EXT_METHOD) *)OPENSSL_sk_deep_copy(ossl_check_const_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_copyfunc_type(copyfunc), ossl_check_X509V3_EXT_METHOD_freefunc_type(freefunc)))
+#define sk_X509V3_EXT_METHOD_set_cmp_func(sk, cmp) ((sk_X509V3_EXT_METHOD_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509V3_EXT_METHOD_sk_type(sk), ossl_check_X509V3_EXT_METHOD_compfunc_type(cmp)))
+
+
+/* ext_flags values */
+# define X509V3_EXT_DYNAMIC 0x1
+# define X509V3_EXT_CTX_DEP 0x2
+# define X509V3_EXT_MULTILINE 0x4
+
+typedef BIT_STRING_BITNAME ENUMERATED_NAMES;
+
+typedef struct BASIC_CONSTRAINTS_st {
+ int ca;
+ ASN1_INTEGER *pathlen;
+} BASIC_CONSTRAINTS;
+
+typedef struct PKEY_USAGE_PERIOD_st {
+ ASN1_GENERALIZEDTIME *notBefore;
+ ASN1_GENERALIZEDTIME *notAfter;
+} PKEY_USAGE_PERIOD;
+
+typedef struct otherName_st {
+ ASN1_OBJECT *type_id;
+ ASN1_TYPE *value;
+} OTHERNAME;
+
+typedef struct EDIPartyName_st {
+ ASN1_STRING *nameAssigner;
+ ASN1_STRING *partyName;
+} EDIPARTYNAME;
+
+typedef struct GENERAL_NAME_st {
+# define GEN_OTHERNAME 0
+# define GEN_EMAIL 1
+# define GEN_DNS 2
+# define GEN_X400 3
+# define GEN_DIRNAME 4
+# define GEN_EDIPARTY 5
+# define GEN_URI 6
+# define GEN_IPADD 7
+# define GEN_RID 8
+ int type;
+ union {
+ char *ptr;
+ OTHERNAME *otherName; /* otherName */
+ ASN1_IA5STRING *rfc822Name;
+ ASN1_IA5STRING *dNSName;
+ ASN1_TYPE *x400Address;
+ X509_NAME *directoryName;
+ EDIPARTYNAME *ediPartyName;
+ ASN1_IA5STRING *uniformResourceIdentifier;
+ ASN1_OCTET_STRING *iPAddress;
+ ASN1_OBJECT *registeredID;
+ /* Old names */
+ ASN1_OCTET_STRING *ip; /* iPAddress */
+ X509_NAME *dirn; /* dirn */
+ ASN1_IA5STRING *ia5; /* rfc822Name, dNSName,
+ * uniformResourceIdentifier */
+ ASN1_OBJECT *rid; /* registeredID */
+ ASN1_TYPE *other; /* x400Address */
+ } d;
+} GENERAL_NAME;
+
+typedef struct ACCESS_DESCRIPTION_st {
+ ASN1_OBJECT *method;
+ GENERAL_NAME *location;
+} ACCESS_DESCRIPTION;
+
+SKM_DEFINE_STACK_OF_INTERNAL(ACCESS_DESCRIPTION, ACCESS_DESCRIPTION, ACCESS_DESCRIPTION)
+#define sk_ACCESS_DESCRIPTION_num(sk) OPENSSL_sk_num(ossl_check_const_ACCESS_DESCRIPTION_sk_type(sk))
+#define sk_ACCESS_DESCRIPTION_value(sk, idx) ((ACCESS_DESCRIPTION *)OPENSSL_sk_value(ossl_check_const_ACCESS_DESCRIPTION_sk_type(sk), (idx)))
+#define sk_ACCESS_DESCRIPTION_new(cmp) ((STACK_OF(ACCESS_DESCRIPTION) *)OPENSSL_sk_new(ossl_check_ACCESS_DESCRIPTION_compfunc_type(cmp)))
+#define sk_ACCESS_DESCRIPTION_new_null() ((STACK_OF(ACCESS_DESCRIPTION) *)OPENSSL_sk_new_null())
+#define sk_ACCESS_DESCRIPTION_new_reserve(cmp, n) ((STACK_OF(ACCESS_DESCRIPTION) *)OPENSSL_sk_new_reserve(ossl_check_ACCESS_DESCRIPTION_compfunc_type(cmp), (n)))
+#define sk_ACCESS_DESCRIPTION_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), (n))
+#define sk_ACCESS_DESCRIPTION_free(sk) OPENSSL_sk_free(ossl_check_ACCESS_DESCRIPTION_sk_type(sk))
+#define sk_ACCESS_DESCRIPTION_zero(sk) OPENSSL_sk_zero(ossl_check_ACCESS_DESCRIPTION_sk_type(sk))
+#define sk_ACCESS_DESCRIPTION_delete(sk, i) ((ACCESS_DESCRIPTION *)OPENSSL_sk_delete(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), (i)))
+#define sk_ACCESS_DESCRIPTION_delete_ptr(sk, ptr) ((ACCESS_DESCRIPTION *)OPENSSL_sk_delete_ptr(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_type(ptr)))
+#define sk_ACCESS_DESCRIPTION_push(sk, ptr) OPENSSL_sk_push(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_type(ptr))
+#define sk_ACCESS_DESCRIPTION_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_type(ptr))
+#define sk_ACCESS_DESCRIPTION_pop(sk) ((ACCESS_DESCRIPTION *)OPENSSL_sk_pop(ossl_check_ACCESS_DESCRIPTION_sk_type(sk)))
+#define sk_ACCESS_DESCRIPTION_shift(sk) ((ACCESS_DESCRIPTION *)OPENSSL_sk_shift(ossl_check_ACCESS_DESCRIPTION_sk_type(sk)))
+#define sk_ACCESS_DESCRIPTION_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ACCESS_DESCRIPTION_sk_type(sk),ossl_check_ACCESS_DESCRIPTION_freefunc_type(freefunc))
+#define sk_ACCESS_DESCRIPTION_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_type(ptr), (idx))
+#define sk_ACCESS_DESCRIPTION_set(sk, idx, ptr) ((ACCESS_DESCRIPTION *)OPENSSL_sk_set(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), (idx), ossl_check_ACCESS_DESCRIPTION_type(ptr)))
+#define sk_ACCESS_DESCRIPTION_find(sk, ptr) OPENSSL_sk_find(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_type(ptr))
+#define sk_ACCESS_DESCRIPTION_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_type(ptr))
+#define sk_ACCESS_DESCRIPTION_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_type(ptr), pnum)
+#define sk_ACCESS_DESCRIPTION_sort(sk) OPENSSL_sk_sort(ossl_check_ACCESS_DESCRIPTION_sk_type(sk))
+#define sk_ACCESS_DESCRIPTION_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ACCESS_DESCRIPTION_sk_type(sk))
+#define sk_ACCESS_DESCRIPTION_dup(sk) ((STACK_OF(ACCESS_DESCRIPTION) *)OPENSSL_sk_dup(ossl_check_const_ACCESS_DESCRIPTION_sk_type(sk)))
+#define sk_ACCESS_DESCRIPTION_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ACCESS_DESCRIPTION) *)OPENSSL_sk_deep_copy(ossl_check_const_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_copyfunc_type(copyfunc), ossl_check_ACCESS_DESCRIPTION_freefunc_type(freefunc)))
+#define sk_ACCESS_DESCRIPTION_set_cmp_func(sk, cmp) ((sk_ACCESS_DESCRIPTION_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ACCESS_DESCRIPTION_sk_type(sk), ossl_check_ACCESS_DESCRIPTION_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(GENERAL_NAME, GENERAL_NAME, GENERAL_NAME)
+#define sk_GENERAL_NAME_num(sk) OPENSSL_sk_num(ossl_check_const_GENERAL_NAME_sk_type(sk))
+#define sk_GENERAL_NAME_value(sk, idx) ((GENERAL_NAME *)OPENSSL_sk_value(ossl_check_const_GENERAL_NAME_sk_type(sk), (idx)))
+#define sk_GENERAL_NAME_new(cmp) ((STACK_OF(GENERAL_NAME) *)OPENSSL_sk_new(ossl_check_GENERAL_NAME_compfunc_type(cmp)))
+#define sk_GENERAL_NAME_new_null() ((STACK_OF(GENERAL_NAME) *)OPENSSL_sk_new_null())
+#define sk_GENERAL_NAME_new_reserve(cmp, n) ((STACK_OF(GENERAL_NAME) *)OPENSSL_sk_new_reserve(ossl_check_GENERAL_NAME_compfunc_type(cmp), (n)))
+#define sk_GENERAL_NAME_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_GENERAL_NAME_sk_type(sk), (n))
+#define sk_GENERAL_NAME_free(sk) OPENSSL_sk_free(ossl_check_GENERAL_NAME_sk_type(sk))
+#define sk_GENERAL_NAME_zero(sk) OPENSSL_sk_zero(ossl_check_GENERAL_NAME_sk_type(sk))
+#define sk_GENERAL_NAME_delete(sk, i) ((GENERAL_NAME *)OPENSSL_sk_delete(ossl_check_GENERAL_NAME_sk_type(sk), (i)))
+#define sk_GENERAL_NAME_delete_ptr(sk, ptr) ((GENERAL_NAME *)OPENSSL_sk_delete_ptr(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_type(ptr)))
+#define sk_GENERAL_NAME_push(sk, ptr) OPENSSL_sk_push(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_type(ptr))
+#define sk_GENERAL_NAME_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_type(ptr))
+#define sk_GENERAL_NAME_pop(sk) ((GENERAL_NAME *)OPENSSL_sk_pop(ossl_check_GENERAL_NAME_sk_type(sk)))
+#define sk_GENERAL_NAME_shift(sk) ((GENERAL_NAME *)OPENSSL_sk_shift(ossl_check_GENERAL_NAME_sk_type(sk)))
+#define sk_GENERAL_NAME_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_GENERAL_NAME_sk_type(sk),ossl_check_GENERAL_NAME_freefunc_type(freefunc))
+#define sk_GENERAL_NAME_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_type(ptr), (idx))
+#define sk_GENERAL_NAME_set(sk, idx, ptr) ((GENERAL_NAME *)OPENSSL_sk_set(ossl_check_GENERAL_NAME_sk_type(sk), (idx), ossl_check_GENERAL_NAME_type(ptr)))
+#define sk_GENERAL_NAME_find(sk, ptr) OPENSSL_sk_find(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_type(ptr))
+#define sk_GENERAL_NAME_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_type(ptr))
+#define sk_GENERAL_NAME_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_type(ptr), pnum)
+#define sk_GENERAL_NAME_sort(sk) OPENSSL_sk_sort(ossl_check_GENERAL_NAME_sk_type(sk))
+#define sk_GENERAL_NAME_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_GENERAL_NAME_sk_type(sk))
+#define sk_GENERAL_NAME_dup(sk) ((STACK_OF(GENERAL_NAME) *)OPENSSL_sk_dup(ossl_check_const_GENERAL_NAME_sk_type(sk)))
+#define sk_GENERAL_NAME_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(GENERAL_NAME) *)OPENSSL_sk_deep_copy(ossl_check_const_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_copyfunc_type(copyfunc), ossl_check_GENERAL_NAME_freefunc_type(freefunc)))
+#define sk_GENERAL_NAME_set_cmp_func(sk, cmp) ((sk_GENERAL_NAME_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_GENERAL_NAME_sk_type(sk), ossl_check_GENERAL_NAME_compfunc_type(cmp)))
+
+
+typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS;
+typedef STACK_OF(ASN1_OBJECT) EXTENDED_KEY_USAGE;
+typedef STACK_OF(ASN1_INTEGER) TLS_FEATURE;
+typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES;
+
+SKM_DEFINE_STACK_OF_INTERNAL(GENERAL_NAMES, GENERAL_NAMES, GENERAL_NAMES)
+#define sk_GENERAL_NAMES_num(sk) OPENSSL_sk_num(ossl_check_const_GENERAL_NAMES_sk_type(sk))
+#define sk_GENERAL_NAMES_value(sk, idx) ((GENERAL_NAMES *)OPENSSL_sk_value(ossl_check_const_GENERAL_NAMES_sk_type(sk), (idx)))
+#define sk_GENERAL_NAMES_new(cmp) ((STACK_OF(GENERAL_NAMES) *)OPENSSL_sk_new(ossl_check_GENERAL_NAMES_compfunc_type(cmp)))
+#define sk_GENERAL_NAMES_new_null() ((STACK_OF(GENERAL_NAMES) *)OPENSSL_sk_new_null())
+#define sk_GENERAL_NAMES_new_reserve(cmp, n) ((STACK_OF(GENERAL_NAMES) *)OPENSSL_sk_new_reserve(ossl_check_GENERAL_NAMES_compfunc_type(cmp), (n)))
+#define sk_GENERAL_NAMES_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_GENERAL_NAMES_sk_type(sk), (n))
+#define sk_GENERAL_NAMES_free(sk) OPENSSL_sk_free(ossl_check_GENERAL_NAMES_sk_type(sk))
+#define sk_GENERAL_NAMES_zero(sk) OPENSSL_sk_zero(ossl_check_GENERAL_NAMES_sk_type(sk))
+#define sk_GENERAL_NAMES_delete(sk, i) ((GENERAL_NAMES *)OPENSSL_sk_delete(ossl_check_GENERAL_NAMES_sk_type(sk), (i)))
+#define sk_GENERAL_NAMES_delete_ptr(sk, ptr) ((GENERAL_NAMES *)OPENSSL_sk_delete_ptr(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_type(ptr)))
+#define sk_GENERAL_NAMES_push(sk, ptr) OPENSSL_sk_push(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_type(ptr))
+#define sk_GENERAL_NAMES_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_type(ptr))
+#define sk_GENERAL_NAMES_pop(sk) ((GENERAL_NAMES *)OPENSSL_sk_pop(ossl_check_GENERAL_NAMES_sk_type(sk)))
+#define sk_GENERAL_NAMES_shift(sk) ((GENERAL_NAMES *)OPENSSL_sk_shift(ossl_check_GENERAL_NAMES_sk_type(sk)))
+#define sk_GENERAL_NAMES_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_GENERAL_NAMES_sk_type(sk),ossl_check_GENERAL_NAMES_freefunc_type(freefunc))
+#define sk_GENERAL_NAMES_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_type(ptr), (idx))
+#define sk_GENERAL_NAMES_set(sk, idx, ptr) ((GENERAL_NAMES *)OPENSSL_sk_set(ossl_check_GENERAL_NAMES_sk_type(sk), (idx), ossl_check_GENERAL_NAMES_type(ptr)))
+#define sk_GENERAL_NAMES_find(sk, ptr) OPENSSL_sk_find(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_type(ptr))
+#define sk_GENERAL_NAMES_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_type(ptr))
+#define sk_GENERAL_NAMES_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_type(ptr), pnum)
+#define sk_GENERAL_NAMES_sort(sk) OPENSSL_sk_sort(ossl_check_GENERAL_NAMES_sk_type(sk))
+#define sk_GENERAL_NAMES_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_GENERAL_NAMES_sk_type(sk))
+#define sk_GENERAL_NAMES_dup(sk) ((STACK_OF(GENERAL_NAMES) *)OPENSSL_sk_dup(ossl_check_const_GENERAL_NAMES_sk_type(sk)))
+#define sk_GENERAL_NAMES_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(GENERAL_NAMES) *)OPENSSL_sk_deep_copy(ossl_check_const_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_copyfunc_type(copyfunc), ossl_check_GENERAL_NAMES_freefunc_type(freefunc)))
+#define sk_GENERAL_NAMES_set_cmp_func(sk, cmp) ((sk_GENERAL_NAMES_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_GENERAL_NAMES_sk_type(sk), ossl_check_GENERAL_NAMES_compfunc_type(cmp)))
+
+
+typedef struct DIST_POINT_NAME_st {
+ int type;
+ union {
+ GENERAL_NAMES *fullname;
+ STACK_OF(X509_NAME_ENTRY) *relativename;
+ } name;
+/* If relativename then this contains the full distribution point name */
+ X509_NAME *dpname;
+} DIST_POINT_NAME;
+/* All existing reasons */
+# define CRLDP_ALL_REASONS 0x807f
+
+# define CRL_REASON_NONE -1
+# define CRL_REASON_UNSPECIFIED 0
+# define CRL_REASON_KEY_COMPROMISE 1
+# define CRL_REASON_CA_COMPROMISE 2
+# define CRL_REASON_AFFILIATION_CHANGED 3
+# define CRL_REASON_SUPERSEDED 4
+# define CRL_REASON_CESSATION_OF_OPERATION 5
+# define CRL_REASON_CERTIFICATE_HOLD 6
+# define CRL_REASON_REMOVE_FROM_CRL 8
+# define CRL_REASON_PRIVILEGE_WITHDRAWN 9
+# define CRL_REASON_AA_COMPROMISE 10
+
+struct DIST_POINT_st {
+ DIST_POINT_NAME *distpoint;
+ ASN1_BIT_STRING *reasons;
+ GENERAL_NAMES *CRLissuer;
+ int dp_reasons;
+};
+
+SKM_DEFINE_STACK_OF_INTERNAL(DIST_POINT, DIST_POINT, DIST_POINT)
+#define sk_DIST_POINT_num(sk) OPENSSL_sk_num(ossl_check_const_DIST_POINT_sk_type(sk))
+#define sk_DIST_POINT_value(sk, idx) ((DIST_POINT *)OPENSSL_sk_value(ossl_check_const_DIST_POINT_sk_type(sk), (idx)))
+#define sk_DIST_POINT_new(cmp) ((STACK_OF(DIST_POINT) *)OPENSSL_sk_new(ossl_check_DIST_POINT_compfunc_type(cmp)))
+#define sk_DIST_POINT_new_null() ((STACK_OF(DIST_POINT) *)OPENSSL_sk_new_null())
+#define sk_DIST_POINT_new_reserve(cmp, n) ((STACK_OF(DIST_POINT) *)OPENSSL_sk_new_reserve(ossl_check_DIST_POINT_compfunc_type(cmp), (n)))
+#define sk_DIST_POINT_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_DIST_POINT_sk_type(sk), (n))
+#define sk_DIST_POINT_free(sk) OPENSSL_sk_free(ossl_check_DIST_POINT_sk_type(sk))
+#define sk_DIST_POINT_zero(sk) OPENSSL_sk_zero(ossl_check_DIST_POINT_sk_type(sk))
+#define sk_DIST_POINT_delete(sk, i) ((DIST_POINT *)OPENSSL_sk_delete(ossl_check_DIST_POINT_sk_type(sk), (i)))
+#define sk_DIST_POINT_delete_ptr(sk, ptr) ((DIST_POINT *)OPENSSL_sk_delete_ptr(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_type(ptr)))
+#define sk_DIST_POINT_push(sk, ptr) OPENSSL_sk_push(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_type(ptr))
+#define sk_DIST_POINT_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_type(ptr))
+#define sk_DIST_POINT_pop(sk) ((DIST_POINT *)OPENSSL_sk_pop(ossl_check_DIST_POINT_sk_type(sk)))
+#define sk_DIST_POINT_shift(sk) ((DIST_POINT *)OPENSSL_sk_shift(ossl_check_DIST_POINT_sk_type(sk)))
+#define sk_DIST_POINT_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_DIST_POINT_sk_type(sk),ossl_check_DIST_POINT_freefunc_type(freefunc))
+#define sk_DIST_POINT_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_type(ptr), (idx))
+#define sk_DIST_POINT_set(sk, idx, ptr) ((DIST_POINT *)OPENSSL_sk_set(ossl_check_DIST_POINT_sk_type(sk), (idx), ossl_check_DIST_POINT_type(ptr)))
+#define sk_DIST_POINT_find(sk, ptr) OPENSSL_sk_find(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_type(ptr))
+#define sk_DIST_POINT_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_type(ptr))
+#define sk_DIST_POINT_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_type(ptr), pnum)
+#define sk_DIST_POINT_sort(sk) OPENSSL_sk_sort(ossl_check_DIST_POINT_sk_type(sk))
+#define sk_DIST_POINT_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_DIST_POINT_sk_type(sk))
+#define sk_DIST_POINT_dup(sk) ((STACK_OF(DIST_POINT) *)OPENSSL_sk_dup(ossl_check_const_DIST_POINT_sk_type(sk)))
+#define sk_DIST_POINT_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(DIST_POINT) *)OPENSSL_sk_deep_copy(ossl_check_const_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_copyfunc_type(copyfunc), ossl_check_DIST_POINT_freefunc_type(freefunc)))
+#define sk_DIST_POINT_set_cmp_func(sk, cmp) ((sk_DIST_POINT_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_DIST_POINT_sk_type(sk), ossl_check_DIST_POINT_compfunc_type(cmp)))
+
+
+typedef STACK_OF(DIST_POINT) CRL_DIST_POINTS;
+
+struct AUTHORITY_KEYID_st {
+ ASN1_OCTET_STRING *keyid;
+ GENERAL_NAMES *issuer;
+ ASN1_INTEGER *serial;
+};
+
+/* Strong extranet structures */
+
+typedef struct SXNET_ID_st {
+ ASN1_INTEGER *zone;
+ ASN1_OCTET_STRING *user;
+} SXNETID;
+
+SKM_DEFINE_STACK_OF_INTERNAL(SXNETID, SXNETID, SXNETID)
+#define sk_SXNETID_num(sk) OPENSSL_sk_num(ossl_check_const_SXNETID_sk_type(sk))
+#define sk_SXNETID_value(sk, idx) ((SXNETID *)OPENSSL_sk_value(ossl_check_const_SXNETID_sk_type(sk), (idx)))
+#define sk_SXNETID_new(cmp) ((STACK_OF(SXNETID) *)OPENSSL_sk_new(ossl_check_SXNETID_compfunc_type(cmp)))
+#define sk_SXNETID_new_null() ((STACK_OF(SXNETID) *)OPENSSL_sk_new_null())
+#define sk_SXNETID_new_reserve(cmp, n) ((STACK_OF(SXNETID) *)OPENSSL_sk_new_reserve(ossl_check_SXNETID_compfunc_type(cmp), (n)))
+#define sk_SXNETID_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_SXNETID_sk_type(sk), (n))
+#define sk_SXNETID_free(sk) OPENSSL_sk_free(ossl_check_SXNETID_sk_type(sk))
+#define sk_SXNETID_zero(sk) OPENSSL_sk_zero(ossl_check_SXNETID_sk_type(sk))
+#define sk_SXNETID_delete(sk, i) ((SXNETID *)OPENSSL_sk_delete(ossl_check_SXNETID_sk_type(sk), (i)))
+#define sk_SXNETID_delete_ptr(sk, ptr) ((SXNETID *)OPENSSL_sk_delete_ptr(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_type(ptr)))
+#define sk_SXNETID_push(sk, ptr) OPENSSL_sk_push(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_type(ptr))
+#define sk_SXNETID_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_type(ptr))
+#define sk_SXNETID_pop(sk) ((SXNETID *)OPENSSL_sk_pop(ossl_check_SXNETID_sk_type(sk)))
+#define sk_SXNETID_shift(sk) ((SXNETID *)OPENSSL_sk_shift(ossl_check_SXNETID_sk_type(sk)))
+#define sk_SXNETID_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_SXNETID_sk_type(sk),ossl_check_SXNETID_freefunc_type(freefunc))
+#define sk_SXNETID_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_type(ptr), (idx))
+#define sk_SXNETID_set(sk, idx, ptr) ((SXNETID *)OPENSSL_sk_set(ossl_check_SXNETID_sk_type(sk), (idx), ossl_check_SXNETID_type(ptr)))
+#define sk_SXNETID_find(sk, ptr) OPENSSL_sk_find(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_type(ptr))
+#define sk_SXNETID_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_type(ptr))
+#define sk_SXNETID_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_type(ptr), pnum)
+#define sk_SXNETID_sort(sk) OPENSSL_sk_sort(ossl_check_SXNETID_sk_type(sk))
+#define sk_SXNETID_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_SXNETID_sk_type(sk))
+#define sk_SXNETID_dup(sk) ((STACK_OF(SXNETID) *)OPENSSL_sk_dup(ossl_check_const_SXNETID_sk_type(sk)))
+#define sk_SXNETID_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(SXNETID) *)OPENSSL_sk_deep_copy(ossl_check_const_SXNETID_sk_type(sk), ossl_check_SXNETID_copyfunc_type(copyfunc), ossl_check_SXNETID_freefunc_type(freefunc)))
+#define sk_SXNETID_set_cmp_func(sk, cmp) ((sk_SXNETID_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_SXNETID_sk_type(sk), ossl_check_SXNETID_compfunc_type(cmp)))
+
+
+
+typedef struct SXNET_st {
+ ASN1_INTEGER *version;
+ STACK_OF(SXNETID) *ids;
+} SXNET;
+
+typedef struct ISSUER_SIGN_TOOL_st {
+ ASN1_UTF8STRING *signTool;
+ ASN1_UTF8STRING *cATool;
+ ASN1_UTF8STRING *signToolCert;
+ ASN1_UTF8STRING *cAToolCert;
+} ISSUER_SIGN_TOOL;
+
+typedef struct NOTICEREF_st {
+ ASN1_STRING *organization;
+ STACK_OF(ASN1_INTEGER) *noticenos;
+} NOTICEREF;
+
+typedef struct USERNOTICE_st {
+ NOTICEREF *noticeref;
+ ASN1_STRING *exptext;
+} USERNOTICE;
+
+typedef struct POLICYQUALINFO_st {
+ ASN1_OBJECT *pqualid;
+ union {
+ ASN1_IA5STRING *cpsuri;
+ USERNOTICE *usernotice;
+ ASN1_TYPE *other;
+ } d;
+} POLICYQUALINFO;
+
+SKM_DEFINE_STACK_OF_INTERNAL(POLICYQUALINFO, POLICYQUALINFO, POLICYQUALINFO)
+#define sk_POLICYQUALINFO_num(sk) OPENSSL_sk_num(ossl_check_const_POLICYQUALINFO_sk_type(sk))
+#define sk_POLICYQUALINFO_value(sk, idx) ((POLICYQUALINFO *)OPENSSL_sk_value(ossl_check_const_POLICYQUALINFO_sk_type(sk), (idx)))
+#define sk_POLICYQUALINFO_new(cmp) ((STACK_OF(POLICYQUALINFO) *)OPENSSL_sk_new(ossl_check_POLICYQUALINFO_compfunc_type(cmp)))
+#define sk_POLICYQUALINFO_new_null() ((STACK_OF(POLICYQUALINFO) *)OPENSSL_sk_new_null())
+#define sk_POLICYQUALINFO_new_reserve(cmp, n) ((STACK_OF(POLICYQUALINFO) *)OPENSSL_sk_new_reserve(ossl_check_POLICYQUALINFO_compfunc_type(cmp), (n)))
+#define sk_POLICYQUALINFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_POLICYQUALINFO_sk_type(sk), (n))
+#define sk_POLICYQUALINFO_free(sk) OPENSSL_sk_free(ossl_check_POLICYQUALINFO_sk_type(sk))
+#define sk_POLICYQUALINFO_zero(sk) OPENSSL_sk_zero(ossl_check_POLICYQUALINFO_sk_type(sk))
+#define sk_POLICYQUALINFO_delete(sk, i) ((POLICYQUALINFO *)OPENSSL_sk_delete(ossl_check_POLICYQUALINFO_sk_type(sk), (i)))
+#define sk_POLICYQUALINFO_delete_ptr(sk, ptr) ((POLICYQUALINFO *)OPENSSL_sk_delete_ptr(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_type(ptr)))
+#define sk_POLICYQUALINFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_type(ptr))
+#define sk_POLICYQUALINFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_type(ptr))
+#define sk_POLICYQUALINFO_pop(sk) ((POLICYQUALINFO *)OPENSSL_sk_pop(ossl_check_POLICYQUALINFO_sk_type(sk)))
+#define sk_POLICYQUALINFO_shift(sk) ((POLICYQUALINFO *)OPENSSL_sk_shift(ossl_check_POLICYQUALINFO_sk_type(sk)))
+#define sk_POLICYQUALINFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_POLICYQUALINFO_sk_type(sk),ossl_check_POLICYQUALINFO_freefunc_type(freefunc))
+#define sk_POLICYQUALINFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_type(ptr), (idx))
+#define sk_POLICYQUALINFO_set(sk, idx, ptr) ((POLICYQUALINFO *)OPENSSL_sk_set(ossl_check_POLICYQUALINFO_sk_type(sk), (idx), ossl_check_POLICYQUALINFO_type(ptr)))
+#define sk_POLICYQUALINFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_type(ptr))
+#define sk_POLICYQUALINFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_type(ptr))
+#define sk_POLICYQUALINFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_type(ptr), pnum)
+#define sk_POLICYQUALINFO_sort(sk) OPENSSL_sk_sort(ossl_check_POLICYQUALINFO_sk_type(sk))
+#define sk_POLICYQUALINFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_POLICYQUALINFO_sk_type(sk))
+#define sk_POLICYQUALINFO_dup(sk) ((STACK_OF(POLICYQUALINFO) *)OPENSSL_sk_dup(ossl_check_const_POLICYQUALINFO_sk_type(sk)))
+#define sk_POLICYQUALINFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(POLICYQUALINFO) *)OPENSSL_sk_deep_copy(ossl_check_const_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_copyfunc_type(copyfunc), ossl_check_POLICYQUALINFO_freefunc_type(freefunc)))
+#define sk_POLICYQUALINFO_set_cmp_func(sk, cmp) ((sk_POLICYQUALINFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_POLICYQUALINFO_sk_type(sk), ossl_check_POLICYQUALINFO_compfunc_type(cmp)))
+
+
+
+typedef struct POLICYINFO_st {
+ ASN1_OBJECT *policyid;
+ STACK_OF(POLICYQUALINFO) *qualifiers;
+} POLICYINFO;
+
+SKM_DEFINE_STACK_OF_INTERNAL(POLICYINFO, POLICYINFO, POLICYINFO)
+#define sk_POLICYINFO_num(sk) OPENSSL_sk_num(ossl_check_const_POLICYINFO_sk_type(sk))
+#define sk_POLICYINFO_value(sk, idx) ((POLICYINFO *)OPENSSL_sk_value(ossl_check_const_POLICYINFO_sk_type(sk), (idx)))
+#define sk_POLICYINFO_new(cmp) ((STACK_OF(POLICYINFO) *)OPENSSL_sk_new(ossl_check_POLICYINFO_compfunc_type(cmp)))
+#define sk_POLICYINFO_new_null() ((STACK_OF(POLICYINFO) *)OPENSSL_sk_new_null())
+#define sk_POLICYINFO_new_reserve(cmp, n) ((STACK_OF(POLICYINFO) *)OPENSSL_sk_new_reserve(ossl_check_POLICYINFO_compfunc_type(cmp), (n)))
+#define sk_POLICYINFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_POLICYINFO_sk_type(sk), (n))
+#define sk_POLICYINFO_free(sk) OPENSSL_sk_free(ossl_check_POLICYINFO_sk_type(sk))
+#define sk_POLICYINFO_zero(sk) OPENSSL_sk_zero(ossl_check_POLICYINFO_sk_type(sk))
+#define sk_POLICYINFO_delete(sk, i) ((POLICYINFO *)OPENSSL_sk_delete(ossl_check_POLICYINFO_sk_type(sk), (i)))
+#define sk_POLICYINFO_delete_ptr(sk, ptr) ((POLICYINFO *)OPENSSL_sk_delete_ptr(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_type(ptr)))
+#define sk_POLICYINFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_type(ptr))
+#define sk_POLICYINFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_type(ptr))
+#define sk_POLICYINFO_pop(sk) ((POLICYINFO *)OPENSSL_sk_pop(ossl_check_POLICYINFO_sk_type(sk)))
+#define sk_POLICYINFO_shift(sk) ((POLICYINFO *)OPENSSL_sk_shift(ossl_check_POLICYINFO_sk_type(sk)))
+#define sk_POLICYINFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_POLICYINFO_sk_type(sk),ossl_check_POLICYINFO_freefunc_type(freefunc))
+#define sk_POLICYINFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_type(ptr), (idx))
+#define sk_POLICYINFO_set(sk, idx, ptr) ((POLICYINFO *)OPENSSL_sk_set(ossl_check_POLICYINFO_sk_type(sk), (idx), ossl_check_POLICYINFO_type(ptr)))
+#define sk_POLICYINFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_type(ptr))
+#define sk_POLICYINFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_type(ptr))
+#define sk_POLICYINFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_type(ptr), pnum)
+#define sk_POLICYINFO_sort(sk) OPENSSL_sk_sort(ossl_check_POLICYINFO_sk_type(sk))
+#define sk_POLICYINFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_POLICYINFO_sk_type(sk))
+#define sk_POLICYINFO_dup(sk) ((STACK_OF(POLICYINFO) *)OPENSSL_sk_dup(ossl_check_const_POLICYINFO_sk_type(sk)))
+#define sk_POLICYINFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(POLICYINFO) *)OPENSSL_sk_deep_copy(ossl_check_const_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_copyfunc_type(copyfunc), ossl_check_POLICYINFO_freefunc_type(freefunc)))
+#define sk_POLICYINFO_set_cmp_func(sk, cmp) ((sk_POLICYINFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_POLICYINFO_sk_type(sk), ossl_check_POLICYINFO_compfunc_type(cmp)))
+
+
+typedef STACK_OF(POLICYINFO) CERTIFICATEPOLICIES;
+
+typedef struct POLICY_MAPPING_st {
+ ASN1_OBJECT *issuerDomainPolicy;
+ ASN1_OBJECT *subjectDomainPolicy;
+} POLICY_MAPPING;
+
+SKM_DEFINE_STACK_OF_INTERNAL(POLICY_MAPPING, POLICY_MAPPING, POLICY_MAPPING)
+#define sk_POLICY_MAPPING_num(sk) OPENSSL_sk_num(ossl_check_const_POLICY_MAPPING_sk_type(sk))
+#define sk_POLICY_MAPPING_value(sk, idx) ((POLICY_MAPPING *)OPENSSL_sk_value(ossl_check_const_POLICY_MAPPING_sk_type(sk), (idx)))
+#define sk_POLICY_MAPPING_new(cmp) ((STACK_OF(POLICY_MAPPING) *)OPENSSL_sk_new(ossl_check_POLICY_MAPPING_compfunc_type(cmp)))
+#define sk_POLICY_MAPPING_new_null() ((STACK_OF(POLICY_MAPPING) *)OPENSSL_sk_new_null())
+#define sk_POLICY_MAPPING_new_reserve(cmp, n) ((STACK_OF(POLICY_MAPPING) *)OPENSSL_sk_new_reserve(ossl_check_POLICY_MAPPING_compfunc_type(cmp), (n)))
+#define sk_POLICY_MAPPING_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_POLICY_MAPPING_sk_type(sk), (n))
+#define sk_POLICY_MAPPING_free(sk) OPENSSL_sk_free(ossl_check_POLICY_MAPPING_sk_type(sk))
+#define sk_POLICY_MAPPING_zero(sk) OPENSSL_sk_zero(ossl_check_POLICY_MAPPING_sk_type(sk))
+#define sk_POLICY_MAPPING_delete(sk, i) ((POLICY_MAPPING *)OPENSSL_sk_delete(ossl_check_POLICY_MAPPING_sk_type(sk), (i)))
+#define sk_POLICY_MAPPING_delete_ptr(sk, ptr) ((POLICY_MAPPING *)OPENSSL_sk_delete_ptr(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_type(ptr)))
+#define sk_POLICY_MAPPING_push(sk, ptr) OPENSSL_sk_push(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_type(ptr))
+#define sk_POLICY_MAPPING_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_type(ptr))
+#define sk_POLICY_MAPPING_pop(sk) ((POLICY_MAPPING *)OPENSSL_sk_pop(ossl_check_POLICY_MAPPING_sk_type(sk)))
+#define sk_POLICY_MAPPING_shift(sk) ((POLICY_MAPPING *)OPENSSL_sk_shift(ossl_check_POLICY_MAPPING_sk_type(sk)))
+#define sk_POLICY_MAPPING_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_POLICY_MAPPING_sk_type(sk),ossl_check_POLICY_MAPPING_freefunc_type(freefunc))
+#define sk_POLICY_MAPPING_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_type(ptr), (idx))
+#define sk_POLICY_MAPPING_set(sk, idx, ptr) ((POLICY_MAPPING *)OPENSSL_sk_set(ossl_check_POLICY_MAPPING_sk_type(sk), (idx), ossl_check_POLICY_MAPPING_type(ptr)))
+#define sk_POLICY_MAPPING_find(sk, ptr) OPENSSL_sk_find(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_type(ptr))
+#define sk_POLICY_MAPPING_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_type(ptr))
+#define sk_POLICY_MAPPING_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_type(ptr), pnum)
+#define sk_POLICY_MAPPING_sort(sk) OPENSSL_sk_sort(ossl_check_POLICY_MAPPING_sk_type(sk))
+#define sk_POLICY_MAPPING_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_POLICY_MAPPING_sk_type(sk))
+#define sk_POLICY_MAPPING_dup(sk) ((STACK_OF(POLICY_MAPPING) *)OPENSSL_sk_dup(ossl_check_const_POLICY_MAPPING_sk_type(sk)))
+#define sk_POLICY_MAPPING_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(POLICY_MAPPING) *)OPENSSL_sk_deep_copy(ossl_check_const_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_copyfunc_type(copyfunc), ossl_check_POLICY_MAPPING_freefunc_type(freefunc)))
+#define sk_POLICY_MAPPING_set_cmp_func(sk, cmp) ((sk_POLICY_MAPPING_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_POLICY_MAPPING_sk_type(sk), ossl_check_POLICY_MAPPING_compfunc_type(cmp)))
+
+
+typedef STACK_OF(POLICY_MAPPING) POLICY_MAPPINGS;
+
+typedef struct GENERAL_SUBTREE_st {
+ GENERAL_NAME *base;
+ ASN1_INTEGER *minimum;
+ ASN1_INTEGER *maximum;
+} GENERAL_SUBTREE;
+
+SKM_DEFINE_STACK_OF_INTERNAL(GENERAL_SUBTREE, GENERAL_SUBTREE, GENERAL_SUBTREE)
+#define sk_GENERAL_SUBTREE_num(sk) OPENSSL_sk_num(ossl_check_const_GENERAL_SUBTREE_sk_type(sk))
+#define sk_GENERAL_SUBTREE_value(sk, idx) ((GENERAL_SUBTREE *)OPENSSL_sk_value(ossl_check_const_GENERAL_SUBTREE_sk_type(sk), (idx)))
+#define sk_GENERAL_SUBTREE_new(cmp) ((STACK_OF(GENERAL_SUBTREE) *)OPENSSL_sk_new(ossl_check_GENERAL_SUBTREE_compfunc_type(cmp)))
+#define sk_GENERAL_SUBTREE_new_null() ((STACK_OF(GENERAL_SUBTREE) *)OPENSSL_sk_new_null())
+#define sk_GENERAL_SUBTREE_new_reserve(cmp, n) ((STACK_OF(GENERAL_SUBTREE) *)OPENSSL_sk_new_reserve(ossl_check_GENERAL_SUBTREE_compfunc_type(cmp), (n)))
+#define sk_GENERAL_SUBTREE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_GENERAL_SUBTREE_sk_type(sk), (n))
+#define sk_GENERAL_SUBTREE_free(sk) OPENSSL_sk_free(ossl_check_GENERAL_SUBTREE_sk_type(sk))
+#define sk_GENERAL_SUBTREE_zero(sk) OPENSSL_sk_zero(ossl_check_GENERAL_SUBTREE_sk_type(sk))
+#define sk_GENERAL_SUBTREE_delete(sk, i) ((GENERAL_SUBTREE *)OPENSSL_sk_delete(ossl_check_GENERAL_SUBTREE_sk_type(sk), (i)))
+#define sk_GENERAL_SUBTREE_delete_ptr(sk, ptr) ((GENERAL_SUBTREE *)OPENSSL_sk_delete_ptr(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_type(ptr)))
+#define sk_GENERAL_SUBTREE_push(sk, ptr) OPENSSL_sk_push(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_type(ptr))
+#define sk_GENERAL_SUBTREE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_type(ptr))
+#define sk_GENERAL_SUBTREE_pop(sk) ((GENERAL_SUBTREE *)OPENSSL_sk_pop(ossl_check_GENERAL_SUBTREE_sk_type(sk)))
+#define sk_GENERAL_SUBTREE_shift(sk) ((GENERAL_SUBTREE *)OPENSSL_sk_shift(ossl_check_GENERAL_SUBTREE_sk_type(sk)))
+#define sk_GENERAL_SUBTREE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_GENERAL_SUBTREE_sk_type(sk),ossl_check_GENERAL_SUBTREE_freefunc_type(freefunc))
+#define sk_GENERAL_SUBTREE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_type(ptr), (idx))
+#define sk_GENERAL_SUBTREE_set(sk, idx, ptr) ((GENERAL_SUBTREE *)OPENSSL_sk_set(ossl_check_GENERAL_SUBTREE_sk_type(sk), (idx), ossl_check_GENERAL_SUBTREE_type(ptr)))
+#define sk_GENERAL_SUBTREE_find(sk, ptr) OPENSSL_sk_find(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_type(ptr))
+#define sk_GENERAL_SUBTREE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_type(ptr))
+#define sk_GENERAL_SUBTREE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_type(ptr), pnum)
+#define sk_GENERAL_SUBTREE_sort(sk) OPENSSL_sk_sort(ossl_check_GENERAL_SUBTREE_sk_type(sk))
+#define sk_GENERAL_SUBTREE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_GENERAL_SUBTREE_sk_type(sk))
+#define sk_GENERAL_SUBTREE_dup(sk) ((STACK_OF(GENERAL_SUBTREE) *)OPENSSL_sk_dup(ossl_check_const_GENERAL_SUBTREE_sk_type(sk)))
+#define sk_GENERAL_SUBTREE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(GENERAL_SUBTREE) *)OPENSSL_sk_deep_copy(ossl_check_const_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_copyfunc_type(copyfunc), ossl_check_GENERAL_SUBTREE_freefunc_type(freefunc)))
+#define sk_GENERAL_SUBTREE_set_cmp_func(sk, cmp) ((sk_GENERAL_SUBTREE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_GENERAL_SUBTREE_sk_type(sk), ossl_check_GENERAL_SUBTREE_compfunc_type(cmp)))
+
+
+struct NAME_CONSTRAINTS_st {
+ STACK_OF(GENERAL_SUBTREE) *permittedSubtrees;
+ STACK_OF(GENERAL_SUBTREE) *excludedSubtrees;
+};
+
+typedef struct POLICY_CONSTRAINTS_st {
+ ASN1_INTEGER *requireExplicitPolicy;
+ ASN1_INTEGER *inhibitPolicyMapping;
+} POLICY_CONSTRAINTS;
+
+/* Proxy certificate structures, see RFC 3820 */
+typedef struct PROXY_POLICY_st {
+ ASN1_OBJECT *policyLanguage;
+ ASN1_OCTET_STRING *policy;
+} PROXY_POLICY;
+
+typedef struct PROXY_CERT_INFO_EXTENSION_st {
+ ASN1_INTEGER *pcPathLengthConstraint;
+ PROXY_POLICY *proxyPolicy;
+} PROXY_CERT_INFO_EXTENSION;
+
+DECLARE_ASN1_FUNCTIONS(PROXY_POLICY)
+DECLARE_ASN1_FUNCTIONS(PROXY_CERT_INFO_EXTENSION)
+
+struct ISSUING_DIST_POINT_st {
+ DIST_POINT_NAME *distpoint;
+ int onlyuser;
+ int onlyCA;
+ ASN1_BIT_STRING *onlysomereasons;
+ int indirectCRL;
+ int onlyattr;
+};
+
+/* Values in idp_flags field */
+/* IDP present */
+# define IDP_PRESENT 0x1
+/* IDP values inconsistent */
+# define IDP_INVALID 0x2
+/* onlyuser true */
+# define IDP_ONLYUSER 0x4
+/* onlyCA true */
+# define IDP_ONLYCA 0x8
+/* onlyattr true */
+# define IDP_ONLYATTR 0x10
+/* indirectCRL true */
+# define IDP_INDIRECT 0x20
+/* onlysomereasons present */
+# define IDP_REASONS 0x40
+
+# define X509V3_conf_err(val) ERR_add_error_data(6, \
+ "section:", (val)->section, \
+ ",name:", (val)->name, ",value:", (val)->value)
+
+# define X509V3_set_ctx_test(ctx) \
+ X509V3_set_ctx(ctx, NULL, NULL, NULL, NULL, X509V3_CTX_TEST)
+# define X509V3_set_ctx_nodb(ctx) (ctx)->db = NULL;
+
+# define EXT_BITSTRING(nid, table) { nid, 0, ASN1_ITEM_ref(ASN1_BIT_STRING), \
+ 0,0,0,0, \
+ 0,0, \
+ (X509V3_EXT_I2V)i2v_ASN1_BIT_STRING, \
+ (X509V3_EXT_V2I)v2i_ASN1_BIT_STRING, \
+ NULL, NULL, \
+ table}
+
+# define EXT_IA5STRING(nid) { nid, 0, ASN1_ITEM_ref(ASN1_IA5STRING), \
+ 0,0,0,0, \
+ (X509V3_EXT_I2S)i2s_ASN1_IA5STRING, \
+ (X509V3_EXT_S2I)s2i_ASN1_IA5STRING, \
+ 0,0,0,0, \
+ NULL}
+
+#define EXT_UTF8STRING(nid) { nid, 0, ASN1_ITEM_ref(ASN1_UTF8STRING), \
+ 0,0,0,0, \
+ (X509V3_EXT_I2S)i2s_ASN1_UTF8STRING, \
+ (X509V3_EXT_S2I)s2i_ASN1_UTF8STRING, \
+ 0,0,0,0, \
+ NULL}
+
+# define EXT_END { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+
+/* X509_PURPOSE stuff */
+
+# define EXFLAG_BCONS 0x1
+# define EXFLAG_KUSAGE 0x2
+# define EXFLAG_XKUSAGE 0x4
+# define EXFLAG_NSCERT 0x8
+
+# define EXFLAG_CA 0x10
+# define EXFLAG_SI 0x20 /* self-issued, maybe not self-signed */
+# define EXFLAG_V1 0x40
+# define EXFLAG_INVALID 0x80
+/* EXFLAG_SET is set to indicate that some values have been precomputed */
+# define EXFLAG_SET 0x100
+# define EXFLAG_CRITICAL 0x200
+# define EXFLAG_PROXY 0x400
+
+# define EXFLAG_INVALID_POLICY 0x800
+# define EXFLAG_FRESHEST 0x1000
+# define EXFLAG_SS 0x2000 /* cert is apparently self-signed */
+
+# define EXFLAG_BCONS_CRITICAL 0x10000
+# define EXFLAG_AKID_CRITICAL 0x20000
+# define EXFLAG_SKID_CRITICAL 0x40000
+# define EXFLAG_SAN_CRITICAL 0x80000
+# define EXFLAG_NO_FINGERPRINT 0x100000
+
+# define KU_DIGITAL_SIGNATURE 0x0080
+# define KU_NON_REPUDIATION 0x0040
+# define KU_KEY_ENCIPHERMENT 0x0020
+# define KU_DATA_ENCIPHERMENT 0x0010
+# define KU_KEY_AGREEMENT 0x0008
+# define KU_KEY_CERT_SIGN 0x0004
+# define KU_CRL_SIGN 0x0002
+# define KU_ENCIPHER_ONLY 0x0001
+# define KU_DECIPHER_ONLY 0x8000
+
+# define NS_SSL_CLIENT 0x80
+# define NS_SSL_SERVER 0x40
+# define NS_SMIME 0x20
+# define NS_OBJSIGN 0x10
+# define NS_SSL_CA 0x04
+# define NS_SMIME_CA 0x02
+# define NS_OBJSIGN_CA 0x01
+# define NS_ANY_CA (NS_SSL_CA|NS_SMIME_CA|NS_OBJSIGN_CA)
+
+# define XKU_SSL_SERVER 0x1
+# define XKU_SSL_CLIENT 0x2
+# define XKU_SMIME 0x4
+# define XKU_CODE_SIGN 0x8
+# define XKU_SGC 0x10 /* Netscape or MS Server-Gated Crypto */
+# define XKU_OCSP_SIGN 0x20
+# define XKU_TIMESTAMP 0x40
+# define XKU_DVCS 0x80
+# define XKU_ANYEKU 0x100
+
+# define X509_PURPOSE_DYNAMIC 0x1
+# define X509_PURPOSE_DYNAMIC_NAME 0x2
+
+typedef struct x509_purpose_st {
+ int purpose;
+ int trust; /* Default trust ID */
+ int flags;
+ int (*check_purpose) (const struct x509_purpose_st *, const X509 *, int);
+ char *name;
+ char *sname;
+ void *usr_data;
+} X509_PURPOSE;
+
+SKM_DEFINE_STACK_OF_INTERNAL(X509_PURPOSE, X509_PURPOSE, X509_PURPOSE)
+#define sk_X509_PURPOSE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_PURPOSE_sk_type(sk))
+#define sk_X509_PURPOSE_value(sk, idx) ((X509_PURPOSE *)OPENSSL_sk_value(ossl_check_const_X509_PURPOSE_sk_type(sk), (idx)))
+#define sk_X509_PURPOSE_new(cmp) ((STACK_OF(X509_PURPOSE) *)OPENSSL_sk_new(ossl_check_X509_PURPOSE_compfunc_type(cmp)))
+#define sk_X509_PURPOSE_new_null() ((STACK_OF(X509_PURPOSE) *)OPENSSL_sk_new_null())
+#define sk_X509_PURPOSE_new_reserve(cmp, n) ((STACK_OF(X509_PURPOSE) *)OPENSSL_sk_new_reserve(ossl_check_X509_PURPOSE_compfunc_type(cmp), (n)))
+#define sk_X509_PURPOSE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_PURPOSE_sk_type(sk), (n))
+#define sk_X509_PURPOSE_free(sk) OPENSSL_sk_free(ossl_check_X509_PURPOSE_sk_type(sk))
+#define sk_X509_PURPOSE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_PURPOSE_sk_type(sk))
+#define sk_X509_PURPOSE_delete(sk, i) ((X509_PURPOSE *)OPENSSL_sk_delete(ossl_check_X509_PURPOSE_sk_type(sk), (i)))
+#define sk_X509_PURPOSE_delete_ptr(sk, ptr) ((X509_PURPOSE *)OPENSSL_sk_delete_ptr(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_type(ptr)))
+#define sk_X509_PURPOSE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_type(ptr))
+#define sk_X509_PURPOSE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_type(ptr))
+#define sk_X509_PURPOSE_pop(sk) ((X509_PURPOSE *)OPENSSL_sk_pop(ossl_check_X509_PURPOSE_sk_type(sk)))
+#define sk_X509_PURPOSE_shift(sk) ((X509_PURPOSE *)OPENSSL_sk_shift(ossl_check_X509_PURPOSE_sk_type(sk)))
+#define sk_X509_PURPOSE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_PURPOSE_sk_type(sk),ossl_check_X509_PURPOSE_freefunc_type(freefunc))
+#define sk_X509_PURPOSE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_type(ptr), (idx))
+#define sk_X509_PURPOSE_set(sk, idx, ptr) ((X509_PURPOSE *)OPENSSL_sk_set(ossl_check_X509_PURPOSE_sk_type(sk), (idx), ossl_check_X509_PURPOSE_type(ptr)))
+#define sk_X509_PURPOSE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_type(ptr))
+#define sk_X509_PURPOSE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_type(ptr))
+#define sk_X509_PURPOSE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_type(ptr), pnum)
+#define sk_X509_PURPOSE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_PURPOSE_sk_type(sk))
+#define sk_X509_PURPOSE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_PURPOSE_sk_type(sk))
+#define sk_X509_PURPOSE_dup(sk) ((STACK_OF(X509_PURPOSE) *)OPENSSL_sk_dup(ossl_check_const_X509_PURPOSE_sk_type(sk)))
+#define sk_X509_PURPOSE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_PURPOSE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_copyfunc_type(copyfunc), ossl_check_X509_PURPOSE_freefunc_type(freefunc)))
+#define sk_X509_PURPOSE_set_cmp_func(sk, cmp) ((sk_X509_PURPOSE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_PURPOSE_sk_type(sk), ossl_check_X509_PURPOSE_compfunc_type(cmp)))
+
+
+
+# define X509_PURPOSE_SSL_CLIENT 1
+# define X509_PURPOSE_SSL_SERVER 2
+# define X509_PURPOSE_NS_SSL_SERVER 3
+# define X509_PURPOSE_SMIME_SIGN 4
+# define X509_PURPOSE_SMIME_ENCRYPT 5
+# define X509_PURPOSE_CRL_SIGN 6
+# define X509_PURPOSE_ANY 7
+# define X509_PURPOSE_OCSP_HELPER 8
+# define X509_PURPOSE_TIMESTAMP_SIGN 9
+
+# define X509_PURPOSE_MIN 1
+# define X509_PURPOSE_MAX 9
+
+/* Flags for X509V3_EXT_print() */
+
+# define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
+/* Return error for unknown extensions */
+# define X509V3_EXT_DEFAULT 0
+/* Print error for unknown extensions */
+# define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
+/* ASN1 parse unknown extensions */
+# define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
+/* BIO_dump unknown extensions */
+# define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
+
+/* Flags for X509V3_add1_i2d */
+
+# define X509V3_ADD_OP_MASK 0xfL
+# define X509V3_ADD_DEFAULT 0L
+# define X509V3_ADD_APPEND 1L
+# define X509V3_ADD_REPLACE 2L
+# define X509V3_ADD_REPLACE_EXISTING 3L
+# define X509V3_ADD_KEEP_EXISTING 4L
+# define X509V3_ADD_DELETE 5L
+# define X509V3_ADD_SILENT 0x10
+
+DECLARE_ASN1_FUNCTIONS(BASIC_CONSTRAINTS)
+
+DECLARE_ASN1_FUNCTIONS(SXNET)
+DECLARE_ASN1_FUNCTIONS(SXNETID)
+
+DECLARE_ASN1_FUNCTIONS(ISSUER_SIGN_TOOL)
+
+int SXNET_add_id_asc(SXNET **psx, const char *zone, const char *user, int userlen);
+int SXNET_add_id_ulong(SXNET **psx, unsigned long lzone, const char *user,
+ int userlen);
+int SXNET_add_id_INTEGER(SXNET **psx, ASN1_INTEGER *izone, const char *user,
+ int userlen);
+
+ASN1_OCTET_STRING *SXNET_get_id_asc(SXNET *sx, const char *zone);
+ASN1_OCTET_STRING *SXNET_get_id_ulong(SXNET *sx, unsigned long lzone);
+ASN1_OCTET_STRING *SXNET_get_id_INTEGER(SXNET *sx, ASN1_INTEGER *zone);
+
+DECLARE_ASN1_FUNCTIONS(AUTHORITY_KEYID)
+
+DECLARE_ASN1_FUNCTIONS(PKEY_USAGE_PERIOD)
+
+DECLARE_ASN1_FUNCTIONS(GENERAL_NAME)
+DECLARE_ASN1_DUP_FUNCTION(GENERAL_NAME)
+int GENERAL_NAME_cmp(GENERAL_NAME *a, GENERAL_NAME *b);
+
+ASN1_BIT_STRING *v2i_ASN1_BIT_STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx,
+ STACK_OF(CONF_VALUE) *nval);
+STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(X509V3_EXT_METHOD *method,
+ ASN1_BIT_STRING *bits,
+ STACK_OF(CONF_VALUE) *extlist);
+char *i2s_ASN1_IA5STRING(X509V3_EXT_METHOD *method, ASN1_IA5STRING *ia5);
+ASN1_IA5STRING *s2i_ASN1_IA5STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, const char *str);
+char *i2s_ASN1_UTF8STRING(X509V3_EXT_METHOD *method, ASN1_UTF8STRING *utf8);
+ASN1_UTF8STRING *s2i_ASN1_UTF8STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, const char *str);
+
+STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method,
+ GENERAL_NAME *gen,
+ STACK_OF(CONF_VALUE) *ret);
+int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen);
+
+DECLARE_ASN1_FUNCTIONS(GENERAL_NAMES)
+
+STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method,
+ GENERAL_NAMES *gen,
+ STACK_OF(CONF_VALUE) *extlist);
+GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval);
+
+DECLARE_ASN1_FUNCTIONS(OTHERNAME)
+DECLARE_ASN1_FUNCTIONS(EDIPARTYNAME)
+int OTHERNAME_cmp(OTHERNAME *a, OTHERNAME *b);
+void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value);
+void *GENERAL_NAME_get0_value(const GENERAL_NAME *a, int *ptype);
+int GENERAL_NAME_set0_othername(GENERAL_NAME *gen,
+ ASN1_OBJECT *oid, ASN1_TYPE *value);
+int GENERAL_NAME_get0_otherName(const GENERAL_NAME *gen,
+ ASN1_OBJECT **poid, ASN1_TYPE **pvalue);
+
+char *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method,
+ const ASN1_OCTET_STRING *ia5);
+ASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, const char *str);
+
+DECLARE_ASN1_FUNCTIONS(EXTENDED_KEY_USAGE)
+int i2a_ACCESS_DESCRIPTION(BIO *bp, const ACCESS_DESCRIPTION *a);
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TLS_FEATURE)
+
+DECLARE_ASN1_FUNCTIONS(CERTIFICATEPOLICIES)
+DECLARE_ASN1_FUNCTIONS(POLICYINFO)
+DECLARE_ASN1_FUNCTIONS(POLICYQUALINFO)
+DECLARE_ASN1_FUNCTIONS(USERNOTICE)
+DECLARE_ASN1_FUNCTIONS(NOTICEREF)
+
+DECLARE_ASN1_FUNCTIONS(CRL_DIST_POINTS)
+DECLARE_ASN1_FUNCTIONS(DIST_POINT)
+DECLARE_ASN1_FUNCTIONS(DIST_POINT_NAME)
+DECLARE_ASN1_FUNCTIONS(ISSUING_DIST_POINT)
+
+int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, const X509_NAME *iname);
+
+int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc);
+int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc);
+
+DECLARE_ASN1_FUNCTIONS(ACCESS_DESCRIPTION)
+DECLARE_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS)
+
+DECLARE_ASN1_ITEM(POLICY_MAPPING)
+DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_MAPPING)
+DECLARE_ASN1_ITEM(POLICY_MAPPINGS)
+
+DECLARE_ASN1_ITEM(GENERAL_SUBTREE)
+DECLARE_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
+
+DECLARE_ASN1_ITEM(NAME_CONSTRAINTS)
+DECLARE_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS)
+DECLARE_ASN1_ITEM(POLICY_CONSTRAINTS)
+
+GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out,
+ const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, int gen_type,
+ const char *value, int is_nc);
+
+# ifdef OPENSSL_CONF_H
+GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, CONF_VALUE *cnf);
+GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out,
+ const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, CONF_VALUE *cnf,
+ int is_nc);
+
+void X509V3_conf_free(CONF_VALUE *val);
+
+X509_EXTENSION *X509V3_EXT_nconf_nid(CONF *conf, X509V3_CTX *ctx, int ext_nid,
+ const char *value);
+X509_EXTENSION *X509V3_EXT_nconf(CONF *conf, X509V3_CTX *ctx, const char *name,
+ const char *value);
+int X509V3_EXT_add_nconf_sk(CONF *conf, X509V3_CTX *ctx, const char *section,
+ STACK_OF(X509_EXTENSION) **sk);
+int X509V3_EXT_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
+ X509 *cert);
+int X509V3_EXT_REQ_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
+ X509_REQ *req);
+int X509V3_EXT_CRL_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
+ X509_CRL *crl);
+
+X509_EXTENSION *X509V3_EXT_conf_nid(LHASH_OF(CONF_VALUE) *conf,
+ X509V3_CTX *ctx, int ext_nid,
+ const char *value);
+X509_EXTENSION *X509V3_EXT_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *name, const char *value);
+int X509V3_EXT_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *section, X509 *cert);
+int X509V3_EXT_REQ_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *section, X509_REQ *req);
+int X509V3_EXT_CRL_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *section, X509_CRL *crl);
+
+int X509V3_add_value_bool_nf(const char *name, int asn1_bool,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_get_value_bool(const CONF_VALUE *value, int *asn1_bool);
+int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint);
+void X509V3_set_nconf(X509V3_CTX *ctx, CONF *conf);
+void X509V3_set_conf_lhash(X509V3_CTX *ctx, LHASH_OF(CONF_VALUE) *lhash);
+# endif
+
+char *X509V3_get_string(X509V3_CTX *ctx, const char *name, const char *section);
+STACK_OF(CONF_VALUE) *X509V3_get_section(X509V3_CTX *ctx, const char *section);
+void X509V3_string_free(X509V3_CTX *ctx, char *str);
+void X509V3_section_free(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *section);
+void X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subject,
+ X509_REQ *req, X509_CRL *crl, int flags);
+/* For API backward compatibility, this is separate from X509V3_set_ctx(): */
+int X509V3_set_issuer_pkey(X509V3_CTX *ctx, EVP_PKEY *pkey);
+
+int X509V3_add_value(const char *name, const char *value,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_add_value_uchar(const char *name, const unsigned char *value,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_add_value_bool(const char *name, int asn1_bool,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint,
+ STACK_OF(CONF_VALUE) **extlist);
+char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *meth, const ASN1_INTEGER *aint);
+ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *meth, const char *value);
+char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *meth, const ASN1_ENUMERATED *aint);
+char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *meth,
+ const ASN1_ENUMERATED *aint);
+int X509V3_EXT_add(X509V3_EXT_METHOD *ext);
+int X509V3_EXT_add_list(X509V3_EXT_METHOD *extlist);
+int X509V3_EXT_add_alias(int nid_to, int nid_from);
+void X509V3_EXT_cleanup(void);
+
+const X509V3_EXT_METHOD *X509V3_EXT_get(X509_EXTENSION *ext);
+const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid);
+int X509V3_add_standard_extensions(void);
+STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line);
+void *X509V3_EXT_d2i(X509_EXTENSION *ext);
+void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *x, int nid, int *crit,
+ int *idx);
+
+X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc);
+int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value,
+ int crit, unsigned long flags);
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/* The new declarations are in crypto.h, but the old ones were here. */
+# define hex_to_string OPENSSL_buf2hexstr
+# define string_to_hex OPENSSL_hexstr2buf
+#endif
+
+void X509V3_EXT_val_prn(BIO *out, STACK_OF(CONF_VALUE) *val, int indent,
+ int ml);
+int X509V3_EXT_print(BIO *out, X509_EXTENSION *ext, unsigned long flag,
+ int indent);
+#ifndef OPENSSL_NO_STDIO
+int X509V3_EXT_print_fp(FILE *out, X509_EXTENSION *ext, int flag, int indent);
+#endif
+int X509V3_extensions_print(BIO *out, const char *title,
+ const STACK_OF(X509_EXTENSION) *exts,
+ unsigned long flag, int indent);
+
+int X509_check_ca(X509 *x);
+int X509_check_purpose(X509 *x, int id, int ca);
+int X509_supported_extension(X509_EXTENSION *ex);
+int X509_PURPOSE_set(int *p, int purpose);
+int X509_check_issued(X509 *issuer, X509 *subject);
+int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid);
+void X509_set_proxy_flag(X509 *x);
+void X509_set_proxy_pathlen(X509 *x, long l);
+long X509_get_proxy_pathlen(X509 *x);
+
+uint32_t X509_get_extension_flags(X509 *x);
+uint32_t X509_get_key_usage(X509 *x);
+uint32_t X509_get_extended_key_usage(X509 *x);
+const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x);
+const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x);
+const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x);
+const ASN1_INTEGER *X509_get0_authority_serial(X509 *x);
+
+int X509_PURPOSE_get_count(void);
+X509_PURPOSE *X509_PURPOSE_get0(int idx);
+int X509_PURPOSE_get_by_sname(const char *sname);
+int X509_PURPOSE_get_by_id(int id);
+int X509_PURPOSE_add(int id, int trust, int flags,
+ int (*ck) (const X509_PURPOSE *, const X509 *, int),
+ const char *name, const char *sname, void *arg);
+char *X509_PURPOSE_get0_name(const X509_PURPOSE *xp);
+char *X509_PURPOSE_get0_sname(const X509_PURPOSE *xp);
+int X509_PURPOSE_get_trust(const X509_PURPOSE *xp);
+void X509_PURPOSE_cleanup(void);
+int X509_PURPOSE_get_id(const X509_PURPOSE *);
+
+STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x);
+STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x);
+void X509_email_free(STACK_OF(OPENSSL_STRING) *sk);
+STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x);
+/* Flags for X509_check_* functions */
+
+/*
+ * Always check subject name for host match even if subject alt names present
+ */
+# define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT 0x1
+/* Disable wildcard matching for dnsName fields and common name. */
+# define X509_CHECK_FLAG_NO_WILDCARDS 0x2
+/* Wildcards must not match a partial label. */
+# define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0x4
+/* Allow (non-partial) wildcards to match multiple labels. */
+# define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS 0x8
+/* Constraint verifier subdomain patterns to match a single labels. */
+# define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0x10
+/* Never check the subject CN */
+# define X509_CHECK_FLAG_NEVER_CHECK_SUBJECT 0x20
+/*
+ * Match reference identifiers starting with "." to any sub-domain.
+ * This is a non-public flag, turned on implicitly when the subject
+ * reference identity is a DNS name.
+ */
+# define _X509_CHECK_FLAG_DOT_SUBDOMAINS 0x8000
+
+int X509_check_host(X509 *x, const char *chk, size_t chklen,
+ unsigned int flags, char **peername);
+int X509_check_email(X509 *x, const char *chk, size_t chklen,
+ unsigned int flags);
+int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen,
+ unsigned int flags);
+int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags);
+
+ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc);
+ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc);
+int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk,
+ unsigned long chtype);
+
+void X509_POLICY_NODE_print(BIO *out, X509_POLICY_NODE *node, int indent);
+SKM_DEFINE_STACK_OF_INTERNAL(X509_POLICY_NODE, X509_POLICY_NODE, X509_POLICY_NODE)
+#define sk_X509_POLICY_NODE_num(sk) OPENSSL_sk_num(ossl_check_const_X509_POLICY_NODE_sk_type(sk))
+#define sk_X509_POLICY_NODE_value(sk, idx) ((X509_POLICY_NODE *)OPENSSL_sk_value(ossl_check_const_X509_POLICY_NODE_sk_type(sk), (idx)))
+#define sk_X509_POLICY_NODE_new(cmp) ((STACK_OF(X509_POLICY_NODE) *)OPENSSL_sk_new(ossl_check_X509_POLICY_NODE_compfunc_type(cmp)))
+#define sk_X509_POLICY_NODE_new_null() ((STACK_OF(X509_POLICY_NODE) *)OPENSSL_sk_new_null())
+#define sk_X509_POLICY_NODE_new_reserve(cmp, n) ((STACK_OF(X509_POLICY_NODE) *)OPENSSL_sk_new_reserve(ossl_check_X509_POLICY_NODE_compfunc_type(cmp), (n)))
+#define sk_X509_POLICY_NODE_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_X509_POLICY_NODE_sk_type(sk), (n))
+#define sk_X509_POLICY_NODE_free(sk) OPENSSL_sk_free(ossl_check_X509_POLICY_NODE_sk_type(sk))
+#define sk_X509_POLICY_NODE_zero(sk) OPENSSL_sk_zero(ossl_check_X509_POLICY_NODE_sk_type(sk))
+#define sk_X509_POLICY_NODE_delete(sk, i) ((X509_POLICY_NODE *)OPENSSL_sk_delete(ossl_check_X509_POLICY_NODE_sk_type(sk), (i)))
+#define sk_X509_POLICY_NODE_delete_ptr(sk, ptr) ((X509_POLICY_NODE *)OPENSSL_sk_delete_ptr(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_type(ptr)))
+#define sk_X509_POLICY_NODE_push(sk, ptr) OPENSSL_sk_push(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_type(ptr))
+#define sk_X509_POLICY_NODE_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_type(ptr))
+#define sk_X509_POLICY_NODE_pop(sk) ((X509_POLICY_NODE *)OPENSSL_sk_pop(ossl_check_X509_POLICY_NODE_sk_type(sk)))
+#define sk_X509_POLICY_NODE_shift(sk) ((X509_POLICY_NODE *)OPENSSL_sk_shift(ossl_check_X509_POLICY_NODE_sk_type(sk)))
+#define sk_X509_POLICY_NODE_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_X509_POLICY_NODE_sk_type(sk),ossl_check_X509_POLICY_NODE_freefunc_type(freefunc))
+#define sk_X509_POLICY_NODE_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_type(ptr), (idx))
+#define sk_X509_POLICY_NODE_set(sk, idx, ptr) ((X509_POLICY_NODE *)OPENSSL_sk_set(ossl_check_X509_POLICY_NODE_sk_type(sk), (idx), ossl_check_X509_POLICY_NODE_type(ptr)))
+#define sk_X509_POLICY_NODE_find(sk, ptr) OPENSSL_sk_find(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_type(ptr))
+#define sk_X509_POLICY_NODE_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_type(ptr))
+#define sk_X509_POLICY_NODE_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_type(ptr), pnum)
+#define sk_X509_POLICY_NODE_sort(sk) OPENSSL_sk_sort(ossl_check_X509_POLICY_NODE_sk_type(sk))
+#define sk_X509_POLICY_NODE_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_X509_POLICY_NODE_sk_type(sk))
+#define sk_X509_POLICY_NODE_dup(sk) ((STACK_OF(X509_POLICY_NODE) *)OPENSSL_sk_dup(ossl_check_const_X509_POLICY_NODE_sk_type(sk)))
+#define sk_X509_POLICY_NODE_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(X509_POLICY_NODE) *)OPENSSL_sk_deep_copy(ossl_check_const_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_copyfunc_type(copyfunc), ossl_check_X509_POLICY_NODE_freefunc_type(freefunc)))
+#define sk_X509_POLICY_NODE_set_cmp_func(sk, cmp) ((sk_X509_POLICY_NODE_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_X509_POLICY_NODE_sk_type(sk), ossl_check_X509_POLICY_NODE_compfunc_type(cmp)))
+
+
+
+#ifndef OPENSSL_NO_RFC3779
+typedef struct ASRange_st {
+ ASN1_INTEGER *min, *max;
+} ASRange;
+
+# define ASIdOrRange_id 0
+# define ASIdOrRange_range 1
+
+typedef struct ASIdOrRange_st {
+ int type;
+ union {
+ ASN1_INTEGER *id;
+ ASRange *range;
+ } u;
+} ASIdOrRange;
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASIdOrRange, ASIdOrRange, ASIdOrRange)
+#define sk_ASIdOrRange_num(sk) OPENSSL_sk_num(ossl_check_const_ASIdOrRange_sk_type(sk))
+#define sk_ASIdOrRange_value(sk, idx) ((ASIdOrRange *)OPENSSL_sk_value(ossl_check_const_ASIdOrRange_sk_type(sk), (idx)))
+#define sk_ASIdOrRange_new(cmp) ((STACK_OF(ASIdOrRange) *)OPENSSL_sk_new(ossl_check_ASIdOrRange_compfunc_type(cmp)))
+#define sk_ASIdOrRange_new_null() ((STACK_OF(ASIdOrRange) *)OPENSSL_sk_new_null())
+#define sk_ASIdOrRange_new_reserve(cmp, n) ((STACK_OF(ASIdOrRange) *)OPENSSL_sk_new_reserve(ossl_check_ASIdOrRange_compfunc_type(cmp), (n)))
+#define sk_ASIdOrRange_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASIdOrRange_sk_type(sk), (n))
+#define sk_ASIdOrRange_free(sk) OPENSSL_sk_free(ossl_check_ASIdOrRange_sk_type(sk))
+#define sk_ASIdOrRange_zero(sk) OPENSSL_sk_zero(ossl_check_ASIdOrRange_sk_type(sk))
+#define sk_ASIdOrRange_delete(sk, i) ((ASIdOrRange *)OPENSSL_sk_delete(ossl_check_ASIdOrRange_sk_type(sk), (i)))
+#define sk_ASIdOrRange_delete_ptr(sk, ptr) ((ASIdOrRange *)OPENSSL_sk_delete_ptr(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_type(ptr)))
+#define sk_ASIdOrRange_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_type(ptr))
+#define sk_ASIdOrRange_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_type(ptr))
+#define sk_ASIdOrRange_pop(sk) ((ASIdOrRange *)OPENSSL_sk_pop(ossl_check_ASIdOrRange_sk_type(sk)))
+#define sk_ASIdOrRange_shift(sk) ((ASIdOrRange *)OPENSSL_sk_shift(ossl_check_ASIdOrRange_sk_type(sk)))
+#define sk_ASIdOrRange_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASIdOrRange_sk_type(sk),ossl_check_ASIdOrRange_freefunc_type(freefunc))
+#define sk_ASIdOrRange_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_type(ptr), (idx))
+#define sk_ASIdOrRange_set(sk, idx, ptr) ((ASIdOrRange *)OPENSSL_sk_set(ossl_check_ASIdOrRange_sk_type(sk), (idx), ossl_check_ASIdOrRange_type(ptr)))
+#define sk_ASIdOrRange_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_type(ptr))
+#define sk_ASIdOrRange_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_type(ptr))
+#define sk_ASIdOrRange_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_type(ptr), pnum)
+#define sk_ASIdOrRange_sort(sk) OPENSSL_sk_sort(ossl_check_ASIdOrRange_sk_type(sk))
+#define sk_ASIdOrRange_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASIdOrRange_sk_type(sk))
+#define sk_ASIdOrRange_dup(sk) ((STACK_OF(ASIdOrRange) *)OPENSSL_sk_dup(ossl_check_const_ASIdOrRange_sk_type(sk)))
+#define sk_ASIdOrRange_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASIdOrRange) *)OPENSSL_sk_deep_copy(ossl_check_const_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_copyfunc_type(copyfunc), ossl_check_ASIdOrRange_freefunc_type(freefunc)))
+#define sk_ASIdOrRange_set_cmp_func(sk, cmp) ((sk_ASIdOrRange_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASIdOrRange_sk_type(sk), ossl_check_ASIdOrRange_compfunc_type(cmp)))
+
+
+typedef STACK_OF(ASIdOrRange) ASIdOrRanges;
+
+# define ASIdentifierChoice_inherit 0
+# define ASIdentifierChoice_asIdsOrRanges 1
+
+typedef struct ASIdentifierChoice_st {
+ int type;
+ union {
+ ASN1_NULL *inherit;
+ ASIdOrRanges *asIdsOrRanges;
+ } u;
+} ASIdentifierChoice;
+
+typedef struct ASIdentifiers_st {
+ ASIdentifierChoice *asnum, *rdi;
+} ASIdentifiers;
+
+DECLARE_ASN1_FUNCTIONS(ASRange)
+DECLARE_ASN1_FUNCTIONS(ASIdOrRange)
+DECLARE_ASN1_FUNCTIONS(ASIdentifierChoice)
+DECLARE_ASN1_FUNCTIONS(ASIdentifiers)
+
+typedef struct IPAddressRange_st {
+ ASN1_BIT_STRING *min, *max;
+} IPAddressRange;
+
+# define IPAddressOrRange_addressPrefix 0
+# define IPAddressOrRange_addressRange 1
+
+typedef struct IPAddressOrRange_st {
+ int type;
+ union {
+ ASN1_BIT_STRING *addressPrefix;
+ IPAddressRange *addressRange;
+ } u;
+} IPAddressOrRange;
+
+SKM_DEFINE_STACK_OF_INTERNAL(IPAddressOrRange, IPAddressOrRange, IPAddressOrRange)
+#define sk_IPAddressOrRange_num(sk) OPENSSL_sk_num(ossl_check_const_IPAddressOrRange_sk_type(sk))
+#define sk_IPAddressOrRange_value(sk, idx) ((IPAddressOrRange *)OPENSSL_sk_value(ossl_check_const_IPAddressOrRange_sk_type(sk), (idx)))
+#define sk_IPAddressOrRange_new(cmp) ((STACK_OF(IPAddressOrRange) *)OPENSSL_sk_new(ossl_check_IPAddressOrRange_compfunc_type(cmp)))
+#define sk_IPAddressOrRange_new_null() ((STACK_OF(IPAddressOrRange) *)OPENSSL_sk_new_null())
+#define sk_IPAddressOrRange_new_reserve(cmp, n) ((STACK_OF(IPAddressOrRange) *)OPENSSL_sk_new_reserve(ossl_check_IPAddressOrRange_compfunc_type(cmp), (n)))
+#define sk_IPAddressOrRange_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_IPAddressOrRange_sk_type(sk), (n))
+#define sk_IPAddressOrRange_free(sk) OPENSSL_sk_free(ossl_check_IPAddressOrRange_sk_type(sk))
+#define sk_IPAddressOrRange_zero(sk) OPENSSL_sk_zero(ossl_check_IPAddressOrRange_sk_type(sk))
+#define sk_IPAddressOrRange_delete(sk, i) ((IPAddressOrRange *)OPENSSL_sk_delete(ossl_check_IPAddressOrRange_sk_type(sk), (i)))
+#define sk_IPAddressOrRange_delete_ptr(sk, ptr) ((IPAddressOrRange *)OPENSSL_sk_delete_ptr(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_type(ptr)))
+#define sk_IPAddressOrRange_push(sk, ptr) OPENSSL_sk_push(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_type(ptr))
+#define sk_IPAddressOrRange_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_type(ptr))
+#define sk_IPAddressOrRange_pop(sk) ((IPAddressOrRange *)OPENSSL_sk_pop(ossl_check_IPAddressOrRange_sk_type(sk)))
+#define sk_IPAddressOrRange_shift(sk) ((IPAddressOrRange *)OPENSSL_sk_shift(ossl_check_IPAddressOrRange_sk_type(sk)))
+#define sk_IPAddressOrRange_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_IPAddressOrRange_sk_type(sk),ossl_check_IPAddressOrRange_freefunc_type(freefunc))
+#define sk_IPAddressOrRange_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_type(ptr), (idx))
+#define sk_IPAddressOrRange_set(sk, idx, ptr) ((IPAddressOrRange *)OPENSSL_sk_set(ossl_check_IPAddressOrRange_sk_type(sk), (idx), ossl_check_IPAddressOrRange_type(ptr)))
+#define sk_IPAddressOrRange_find(sk, ptr) OPENSSL_sk_find(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_type(ptr))
+#define sk_IPAddressOrRange_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_type(ptr))
+#define sk_IPAddressOrRange_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_type(ptr), pnum)
+#define sk_IPAddressOrRange_sort(sk) OPENSSL_sk_sort(ossl_check_IPAddressOrRange_sk_type(sk))
+#define sk_IPAddressOrRange_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_IPAddressOrRange_sk_type(sk))
+#define sk_IPAddressOrRange_dup(sk) ((STACK_OF(IPAddressOrRange) *)OPENSSL_sk_dup(ossl_check_const_IPAddressOrRange_sk_type(sk)))
+#define sk_IPAddressOrRange_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(IPAddressOrRange) *)OPENSSL_sk_deep_copy(ossl_check_const_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_copyfunc_type(copyfunc), ossl_check_IPAddressOrRange_freefunc_type(freefunc)))
+#define sk_IPAddressOrRange_set_cmp_func(sk, cmp) ((sk_IPAddressOrRange_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_IPAddressOrRange_sk_type(sk), ossl_check_IPAddressOrRange_compfunc_type(cmp)))
+
+
+typedef STACK_OF(IPAddressOrRange) IPAddressOrRanges;
+
+# define IPAddressChoice_inherit 0
+# define IPAddressChoice_addressesOrRanges 1
+
+typedef struct IPAddressChoice_st {
+ int type;
+ union {
+ ASN1_NULL *inherit;
+ IPAddressOrRanges *addressesOrRanges;
+ } u;
+} IPAddressChoice;
+
+typedef struct IPAddressFamily_st {
+ ASN1_OCTET_STRING *addressFamily;
+ IPAddressChoice *ipAddressChoice;
+} IPAddressFamily;
+
+SKM_DEFINE_STACK_OF_INTERNAL(IPAddressFamily, IPAddressFamily, IPAddressFamily)
+#define sk_IPAddressFamily_num(sk) OPENSSL_sk_num(ossl_check_const_IPAddressFamily_sk_type(sk))
+#define sk_IPAddressFamily_value(sk, idx) ((IPAddressFamily *)OPENSSL_sk_value(ossl_check_const_IPAddressFamily_sk_type(sk), (idx)))
+#define sk_IPAddressFamily_new(cmp) ((STACK_OF(IPAddressFamily) *)OPENSSL_sk_new(ossl_check_IPAddressFamily_compfunc_type(cmp)))
+#define sk_IPAddressFamily_new_null() ((STACK_OF(IPAddressFamily) *)OPENSSL_sk_new_null())
+#define sk_IPAddressFamily_new_reserve(cmp, n) ((STACK_OF(IPAddressFamily) *)OPENSSL_sk_new_reserve(ossl_check_IPAddressFamily_compfunc_type(cmp), (n)))
+#define sk_IPAddressFamily_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_IPAddressFamily_sk_type(sk), (n))
+#define sk_IPAddressFamily_free(sk) OPENSSL_sk_free(ossl_check_IPAddressFamily_sk_type(sk))
+#define sk_IPAddressFamily_zero(sk) OPENSSL_sk_zero(ossl_check_IPAddressFamily_sk_type(sk))
+#define sk_IPAddressFamily_delete(sk, i) ((IPAddressFamily *)OPENSSL_sk_delete(ossl_check_IPAddressFamily_sk_type(sk), (i)))
+#define sk_IPAddressFamily_delete_ptr(sk, ptr) ((IPAddressFamily *)OPENSSL_sk_delete_ptr(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_type(ptr)))
+#define sk_IPAddressFamily_push(sk, ptr) OPENSSL_sk_push(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_type(ptr))
+#define sk_IPAddressFamily_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_type(ptr))
+#define sk_IPAddressFamily_pop(sk) ((IPAddressFamily *)OPENSSL_sk_pop(ossl_check_IPAddressFamily_sk_type(sk)))
+#define sk_IPAddressFamily_shift(sk) ((IPAddressFamily *)OPENSSL_sk_shift(ossl_check_IPAddressFamily_sk_type(sk)))
+#define sk_IPAddressFamily_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_IPAddressFamily_sk_type(sk),ossl_check_IPAddressFamily_freefunc_type(freefunc))
+#define sk_IPAddressFamily_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_type(ptr), (idx))
+#define sk_IPAddressFamily_set(sk, idx, ptr) ((IPAddressFamily *)OPENSSL_sk_set(ossl_check_IPAddressFamily_sk_type(sk), (idx), ossl_check_IPAddressFamily_type(ptr)))
+#define sk_IPAddressFamily_find(sk, ptr) OPENSSL_sk_find(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_type(ptr))
+#define sk_IPAddressFamily_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_type(ptr))
+#define sk_IPAddressFamily_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_type(ptr), pnum)
+#define sk_IPAddressFamily_sort(sk) OPENSSL_sk_sort(ossl_check_IPAddressFamily_sk_type(sk))
+#define sk_IPAddressFamily_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_IPAddressFamily_sk_type(sk))
+#define sk_IPAddressFamily_dup(sk) ((STACK_OF(IPAddressFamily) *)OPENSSL_sk_dup(ossl_check_const_IPAddressFamily_sk_type(sk)))
+#define sk_IPAddressFamily_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(IPAddressFamily) *)OPENSSL_sk_deep_copy(ossl_check_const_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_copyfunc_type(copyfunc), ossl_check_IPAddressFamily_freefunc_type(freefunc)))
+#define sk_IPAddressFamily_set_cmp_func(sk, cmp) ((sk_IPAddressFamily_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_IPAddressFamily_sk_type(sk), ossl_check_IPAddressFamily_compfunc_type(cmp)))
+
+
+
+typedef STACK_OF(IPAddressFamily) IPAddrBlocks;
+
+DECLARE_ASN1_FUNCTIONS(IPAddressRange)
+DECLARE_ASN1_FUNCTIONS(IPAddressOrRange)
+DECLARE_ASN1_FUNCTIONS(IPAddressChoice)
+DECLARE_ASN1_FUNCTIONS(IPAddressFamily)
+
+/*
+ * API tag for elements of the ASIdentifer SEQUENCE.
+ */
+# define V3_ASID_ASNUM 0
+# define V3_ASID_RDI 1
+
+/*
+ * AFI values, assigned by IANA. It'd be nice to make the AFI
+ * handling code totally generic, but there are too many little things
+ * that would need to be defined for other address families for it to
+ * be worth the trouble.
+ */
+# define IANA_AFI_IPV4 1
+# define IANA_AFI_IPV6 2
+
+/*
+ * Utilities to construct and extract values from RFC3779 extensions,
+ * since some of the encodings (particularly for IP address prefixes
+ * and ranges) are a bit tedious to work with directly.
+ */
+int X509v3_asid_add_inherit(ASIdentifiers *asid, int which);
+int X509v3_asid_add_id_or_range(ASIdentifiers *asid, int which,
+ ASN1_INTEGER *min, ASN1_INTEGER *max);
+int X509v3_addr_add_inherit(IPAddrBlocks *addr,
+ const unsigned afi, const unsigned *safi);
+int X509v3_addr_add_prefix(IPAddrBlocks *addr,
+ const unsigned afi, const unsigned *safi,
+ unsigned char *a, const int prefixlen);
+int X509v3_addr_add_range(IPAddrBlocks *addr,
+ const unsigned afi, const unsigned *safi,
+ unsigned char *min, unsigned char *max);
+unsigned X509v3_addr_get_afi(const IPAddressFamily *f);
+int X509v3_addr_get_range(IPAddressOrRange *aor, const unsigned afi,
+ unsigned char *min, unsigned char *max,
+ const int length);
+
+/*
+ * Canonical forms.
+ */
+int X509v3_asid_is_canonical(ASIdentifiers *asid);
+int X509v3_addr_is_canonical(IPAddrBlocks *addr);
+int X509v3_asid_canonize(ASIdentifiers *asid);
+int X509v3_addr_canonize(IPAddrBlocks *addr);
+
+/*
+ * Tests for inheritance and containment.
+ */
+int X509v3_asid_inherits(ASIdentifiers *asid);
+int X509v3_addr_inherits(IPAddrBlocks *addr);
+int X509v3_asid_subset(ASIdentifiers *a, ASIdentifiers *b);
+int X509v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b);
+
+/*
+ * Check whether RFC 3779 extensions nest properly in chains.
+ */
+int X509v3_asid_validate_path(X509_STORE_CTX *);
+int X509v3_addr_validate_path(X509_STORE_CTX *);
+int X509v3_asid_validate_resource_set(STACK_OF(X509) *chain,
+ ASIdentifiers *ext,
+ int allow_inheritance);
+int X509v3_addr_validate_resource_set(STACK_OF(X509) *chain,
+ IPAddrBlocks *ext, int allow_inheritance);
+
+#endif /* OPENSSL_NO_RFC3779 */
+
+SKM_DEFINE_STACK_OF_INTERNAL(ASN1_STRING, ASN1_STRING, ASN1_STRING)
+#define sk_ASN1_STRING_num(sk) OPENSSL_sk_num(ossl_check_const_ASN1_STRING_sk_type(sk))
+#define sk_ASN1_STRING_value(sk, idx) ((ASN1_STRING *)OPENSSL_sk_value(ossl_check_const_ASN1_STRING_sk_type(sk), (idx)))
+#define sk_ASN1_STRING_new(cmp) ((STACK_OF(ASN1_STRING) *)OPENSSL_sk_new(ossl_check_ASN1_STRING_compfunc_type(cmp)))
+#define sk_ASN1_STRING_new_null() ((STACK_OF(ASN1_STRING) *)OPENSSL_sk_new_null())
+#define sk_ASN1_STRING_new_reserve(cmp, n) ((STACK_OF(ASN1_STRING) *)OPENSSL_sk_new_reserve(ossl_check_ASN1_STRING_compfunc_type(cmp), (n)))
+#define sk_ASN1_STRING_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ASN1_STRING_sk_type(sk), (n))
+#define sk_ASN1_STRING_free(sk) OPENSSL_sk_free(ossl_check_ASN1_STRING_sk_type(sk))
+#define sk_ASN1_STRING_zero(sk) OPENSSL_sk_zero(ossl_check_ASN1_STRING_sk_type(sk))
+#define sk_ASN1_STRING_delete(sk, i) ((ASN1_STRING *)OPENSSL_sk_delete(ossl_check_ASN1_STRING_sk_type(sk), (i)))
+#define sk_ASN1_STRING_delete_ptr(sk, ptr) ((ASN1_STRING *)OPENSSL_sk_delete_ptr(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_type(ptr)))
+#define sk_ASN1_STRING_push(sk, ptr) OPENSSL_sk_push(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_type(ptr))
+#define sk_ASN1_STRING_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_type(ptr))
+#define sk_ASN1_STRING_pop(sk) ((ASN1_STRING *)OPENSSL_sk_pop(ossl_check_ASN1_STRING_sk_type(sk)))
+#define sk_ASN1_STRING_shift(sk) ((ASN1_STRING *)OPENSSL_sk_shift(ossl_check_ASN1_STRING_sk_type(sk)))
+#define sk_ASN1_STRING_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ASN1_STRING_sk_type(sk),ossl_check_ASN1_STRING_freefunc_type(freefunc))
+#define sk_ASN1_STRING_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_type(ptr), (idx))
+#define sk_ASN1_STRING_set(sk, idx, ptr) ((ASN1_STRING *)OPENSSL_sk_set(ossl_check_ASN1_STRING_sk_type(sk), (idx), ossl_check_ASN1_STRING_type(ptr)))
+#define sk_ASN1_STRING_find(sk, ptr) OPENSSL_sk_find(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_type(ptr))
+#define sk_ASN1_STRING_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_type(ptr))
+#define sk_ASN1_STRING_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_type(ptr), pnum)
+#define sk_ASN1_STRING_sort(sk) OPENSSL_sk_sort(ossl_check_ASN1_STRING_sk_type(sk))
+#define sk_ASN1_STRING_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ASN1_STRING_sk_type(sk))
+#define sk_ASN1_STRING_dup(sk) ((STACK_OF(ASN1_STRING) *)OPENSSL_sk_dup(ossl_check_const_ASN1_STRING_sk_type(sk)))
+#define sk_ASN1_STRING_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ASN1_STRING) *)OPENSSL_sk_deep_copy(ossl_check_const_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_copyfunc_type(copyfunc), ossl_check_ASN1_STRING_freefunc_type(freefunc)))
+#define sk_ASN1_STRING_set_cmp_func(sk, cmp) ((sk_ASN1_STRING_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ASN1_STRING_sk_type(sk), ossl_check_ASN1_STRING_compfunc_type(cmp)))
+
+
+/*
+ * Admission Syntax
+ */
+typedef struct NamingAuthority_st NAMING_AUTHORITY;
+typedef struct ProfessionInfo_st PROFESSION_INFO;
+typedef struct Admissions_st ADMISSIONS;
+typedef struct AdmissionSyntax_st ADMISSION_SYNTAX;
+DECLARE_ASN1_FUNCTIONS(NAMING_AUTHORITY)
+DECLARE_ASN1_FUNCTIONS(PROFESSION_INFO)
+DECLARE_ASN1_FUNCTIONS(ADMISSIONS)
+DECLARE_ASN1_FUNCTIONS(ADMISSION_SYNTAX)
+SKM_DEFINE_STACK_OF_INTERNAL(PROFESSION_INFO, PROFESSION_INFO, PROFESSION_INFO)
+#define sk_PROFESSION_INFO_num(sk) OPENSSL_sk_num(ossl_check_const_PROFESSION_INFO_sk_type(sk))
+#define sk_PROFESSION_INFO_value(sk, idx) ((PROFESSION_INFO *)OPENSSL_sk_value(ossl_check_const_PROFESSION_INFO_sk_type(sk), (idx)))
+#define sk_PROFESSION_INFO_new(cmp) ((STACK_OF(PROFESSION_INFO) *)OPENSSL_sk_new(ossl_check_PROFESSION_INFO_compfunc_type(cmp)))
+#define sk_PROFESSION_INFO_new_null() ((STACK_OF(PROFESSION_INFO) *)OPENSSL_sk_new_null())
+#define sk_PROFESSION_INFO_new_reserve(cmp, n) ((STACK_OF(PROFESSION_INFO) *)OPENSSL_sk_new_reserve(ossl_check_PROFESSION_INFO_compfunc_type(cmp), (n)))
+#define sk_PROFESSION_INFO_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_PROFESSION_INFO_sk_type(sk), (n))
+#define sk_PROFESSION_INFO_free(sk) OPENSSL_sk_free(ossl_check_PROFESSION_INFO_sk_type(sk))
+#define sk_PROFESSION_INFO_zero(sk) OPENSSL_sk_zero(ossl_check_PROFESSION_INFO_sk_type(sk))
+#define sk_PROFESSION_INFO_delete(sk, i) ((PROFESSION_INFO *)OPENSSL_sk_delete(ossl_check_PROFESSION_INFO_sk_type(sk), (i)))
+#define sk_PROFESSION_INFO_delete_ptr(sk, ptr) ((PROFESSION_INFO *)OPENSSL_sk_delete_ptr(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_type(ptr)))
+#define sk_PROFESSION_INFO_push(sk, ptr) OPENSSL_sk_push(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_type(ptr))
+#define sk_PROFESSION_INFO_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_type(ptr))
+#define sk_PROFESSION_INFO_pop(sk) ((PROFESSION_INFO *)OPENSSL_sk_pop(ossl_check_PROFESSION_INFO_sk_type(sk)))
+#define sk_PROFESSION_INFO_shift(sk) ((PROFESSION_INFO *)OPENSSL_sk_shift(ossl_check_PROFESSION_INFO_sk_type(sk)))
+#define sk_PROFESSION_INFO_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_PROFESSION_INFO_sk_type(sk),ossl_check_PROFESSION_INFO_freefunc_type(freefunc))
+#define sk_PROFESSION_INFO_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_type(ptr), (idx))
+#define sk_PROFESSION_INFO_set(sk, idx, ptr) ((PROFESSION_INFO *)OPENSSL_sk_set(ossl_check_PROFESSION_INFO_sk_type(sk), (idx), ossl_check_PROFESSION_INFO_type(ptr)))
+#define sk_PROFESSION_INFO_find(sk, ptr) OPENSSL_sk_find(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_type(ptr))
+#define sk_PROFESSION_INFO_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_type(ptr))
+#define sk_PROFESSION_INFO_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_type(ptr), pnum)
+#define sk_PROFESSION_INFO_sort(sk) OPENSSL_sk_sort(ossl_check_PROFESSION_INFO_sk_type(sk))
+#define sk_PROFESSION_INFO_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_PROFESSION_INFO_sk_type(sk))
+#define sk_PROFESSION_INFO_dup(sk) ((STACK_OF(PROFESSION_INFO) *)OPENSSL_sk_dup(ossl_check_const_PROFESSION_INFO_sk_type(sk)))
+#define sk_PROFESSION_INFO_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(PROFESSION_INFO) *)OPENSSL_sk_deep_copy(ossl_check_const_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_copyfunc_type(copyfunc), ossl_check_PROFESSION_INFO_freefunc_type(freefunc)))
+#define sk_PROFESSION_INFO_set_cmp_func(sk, cmp) ((sk_PROFESSION_INFO_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_PROFESSION_INFO_sk_type(sk), ossl_check_PROFESSION_INFO_compfunc_type(cmp)))
+SKM_DEFINE_STACK_OF_INTERNAL(ADMISSIONS, ADMISSIONS, ADMISSIONS)
+#define sk_ADMISSIONS_num(sk) OPENSSL_sk_num(ossl_check_const_ADMISSIONS_sk_type(sk))
+#define sk_ADMISSIONS_value(sk, idx) ((ADMISSIONS *)OPENSSL_sk_value(ossl_check_const_ADMISSIONS_sk_type(sk), (idx)))
+#define sk_ADMISSIONS_new(cmp) ((STACK_OF(ADMISSIONS) *)OPENSSL_sk_new(ossl_check_ADMISSIONS_compfunc_type(cmp)))
+#define sk_ADMISSIONS_new_null() ((STACK_OF(ADMISSIONS) *)OPENSSL_sk_new_null())
+#define sk_ADMISSIONS_new_reserve(cmp, n) ((STACK_OF(ADMISSIONS) *)OPENSSL_sk_new_reserve(ossl_check_ADMISSIONS_compfunc_type(cmp), (n)))
+#define sk_ADMISSIONS_reserve(sk, n) OPENSSL_sk_reserve(ossl_check_ADMISSIONS_sk_type(sk), (n))
+#define sk_ADMISSIONS_free(sk) OPENSSL_sk_free(ossl_check_ADMISSIONS_sk_type(sk))
+#define sk_ADMISSIONS_zero(sk) OPENSSL_sk_zero(ossl_check_ADMISSIONS_sk_type(sk))
+#define sk_ADMISSIONS_delete(sk, i) ((ADMISSIONS *)OPENSSL_sk_delete(ossl_check_ADMISSIONS_sk_type(sk), (i)))
+#define sk_ADMISSIONS_delete_ptr(sk, ptr) ((ADMISSIONS *)OPENSSL_sk_delete_ptr(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_type(ptr)))
+#define sk_ADMISSIONS_push(sk, ptr) OPENSSL_sk_push(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_type(ptr))
+#define sk_ADMISSIONS_unshift(sk, ptr) OPENSSL_sk_unshift(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_type(ptr))
+#define sk_ADMISSIONS_pop(sk) ((ADMISSIONS *)OPENSSL_sk_pop(ossl_check_ADMISSIONS_sk_type(sk)))
+#define sk_ADMISSIONS_shift(sk) ((ADMISSIONS *)OPENSSL_sk_shift(ossl_check_ADMISSIONS_sk_type(sk)))
+#define sk_ADMISSIONS_pop_free(sk, freefunc) OPENSSL_sk_pop_free(ossl_check_ADMISSIONS_sk_type(sk),ossl_check_ADMISSIONS_freefunc_type(freefunc))
+#define sk_ADMISSIONS_insert(sk, ptr, idx) OPENSSL_sk_insert(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_type(ptr), (idx))
+#define sk_ADMISSIONS_set(sk, idx, ptr) ((ADMISSIONS *)OPENSSL_sk_set(ossl_check_ADMISSIONS_sk_type(sk), (idx), ossl_check_ADMISSIONS_type(ptr)))
+#define sk_ADMISSIONS_find(sk, ptr) OPENSSL_sk_find(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_type(ptr))
+#define sk_ADMISSIONS_find_ex(sk, ptr) OPENSSL_sk_find_ex(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_type(ptr))
+#define sk_ADMISSIONS_find_all(sk, ptr, pnum) OPENSSL_sk_find_all(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_type(ptr), pnum)
+#define sk_ADMISSIONS_sort(sk) OPENSSL_sk_sort(ossl_check_ADMISSIONS_sk_type(sk))
+#define sk_ADMISSIONS_is_sorted(sk) OPENSSL_sk_is_sorted(ossl_check_const_ADMISSIONS_sk_type(sk))
+#define sk_ADMISSIONS_dup(sk) ((STACK_OF(ADMISSIONS) *)OPENSSL_sk_dup(ossl_check_const_ADMISSIONS_sk_type(sk)))
+#define sk_ADMISSIONS_deep_copy(sk, copyfunc, freefunc) ((STACK_OF(ADMISSIONS) *)OPENSSL_sk_deep_copy(ossl_check_const_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_copyfunc_type(copyfunc), ossl_check_ADMISSIONS_freefunc_type(freefunc)))
+#define sk_ADMISSIONS_set_cmp_func(sk, cmp) ((sk_ADMISSIONS_compfunc)OPENSSL_sk_set_cmp_func(ossl_check_ADMISSIONS_sk_type(sk), ossl_check_ADMISSIONS_compfunc_type(cmp)))
+
+typedef STACK_OF(PROFESSION_INFO) PROFESSION_INFOS;
+
+const ASN1_OBJECT *NAMING_AUTHORITY_get0_authorityId(
+ const NAMING_AUTHORITY *n);
+const ASN1_IA5STRING *NAMING_AUTHORITY_get0_authorityURL(
+ const NAMING_AUTHORITY *n);
+const ASN1_STRING *NAMING_AUTHORITY_get0_authorityText(
+ const NAMING_AUTHORITY *n);
+void NAMING_AUTHORITY_set0_authorityId(NAMING_AUTHORITY *n,
+ ASN1_OBJECT* namingAuthorityId);
+void NAMING_AUTHORITY_set0_authorityURL(NAMING_AUTHORITY *n,
+ ASN1_IA5STRING* namingAuthorityUrl);
+void NAMING_AUTHORITY_set0_authorityText(NAMING_AUTHORITY *n,
+ ASN1_STRING* namingAuthorityText);
+
+const GENERAL_NAME *ADMISSION_SYNTAX_get0_admissionAuthority(
+ const ADMISSION_SYNTAX *as);
+void ADMISSION_SYNTAX_set0_admissionAuthority(
+ ADMISSION_SYNTAX *as, GENERAL_NAME *aa);
+const STACK_OF(ADMISSIONS) *ADMISSION_SYNTAX_get0_contentsOfAdmissions(
+ const ADMISSION_SYNTAX *as);
+void ADMISSION_SYNTAX_set0_contentsOfAdmissions(
+ ADMISSION_SYNTAX *as, STACK_OF(ADMISSIONS) *a);
+const GENERAL_NAME *ADMISSIONS_get0_admissionAuthority(const ADMISSIONS *a);
+void ADMISSIONS_set0_admissionAuthority(ADMISSIONS *a, GENERAL_NAME *aa);
+const NAMING_AUTHORITY *ADMISSIONS_get0_namingAuthority(const ADMISSIONS *a);
+void ADMISSIONS_set0_namingAuthority(ADMISSIONS *a, NAMING_AUTHORITY *na);
+const PROFESSION_INFOS *ADMISSIONS_get0_professionInfos(const ADMISSIONS *a);
+void ADMISSIONS_set0_professionInfos(ADMISSIONS *a, PROFESSION_INFOS *pi);
+const ASN1_OCTET_STRING *PROFESSION_INFO_get0_addProfessionInfo(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_addProfessionInfo(
+ PROFESSION_INFO *pi, ASN1_OCTET_STRING *aos);
+const NAMING_AUTHORITY *PROFESSION_INFO_get0_namingAuthority(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_namingAuthority(
+ PROFESSION_INFO *pi, NAMING_AUTHORITY *na);
+const STACK_OF(ASN1_STRING) *PROFESSION_INFO_get0_professionItems(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_professionItems(
+ PROFESSION_INFO *pi, STACK_OF(ASN1_STRING) *as);
+const STACK_OF(ASN1_OBJECT) *PROFESSION_INFO_get0_professionOIDs(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_professionOIDs(
+ PROFESSION_INFO *pi, STACK_OF(ASN1_OBJECT) *po);
+const ASN1_PRINTABLESTRING *PROFESSION_INFO_get0_registrationNumber(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_registrationNumber(
+ PROFESSION_INFO *pi, ASN1_PRINTABLESTRING *rn);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/x509v3.h.in b/include/openssl/x509v3.h.in
new file mode 100644
index 00000000..d00a66a3
--- /dev/null
+++ b/include/openssl/x509v3.h.in
@@ -0,0 +1,1017 @@
+/*
+ * {- join("\n * ", @autowarntext) -}
+ *
+ * Copyright 1999-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+{-
+use OpenSSL::stackhash qw(generate_stack_macros);
+-}
+
+#ifndef OPENSSL_X509V3_H
+# define OPENSSL_X509V3_H
+# pragma once
+
+# include <openssl/macros.h>
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define HEADER_X509V3_H
+# endif
+
+# include <openssl/bio.h>
+# include <openssl/x509.h>
+# include <openssl/conf.h>
+# include <openssl/x509v3err.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Forward reference */
+struct v3_ext_method;
+struct v3_ext_ctx;
+
+/* Useful typedefs */
+
+typedef void *(*X509V3_EXT_NEW)(void);
+typedef void (*X509V3_EXT_FREE) (void *);
+typedef void *(*X509V3_EXT_D2I)(void *, const unsigned char **, long);
+typedef int (*X509V3_EXT_I2D) (const void *, unsigned char **);
+typedef STACK_OF(CONF_VALUE) *
+ (*X509V3_EXT_I2V) (const struct v3_ext_method *method, void *ext,
+ STACK_OF(CONF_VALUE) *extlist);
+typedef void *(*X509V3_EXT_V2I)(const struct v3_ext_method *method,
+ struct v3_ext_ctx *ctx,
+ STACK_OF(CONF_VALUE) *values);
+typedef char *(*X509V3_EXT_I2S)(const struct v3_ext_method *method,
+ void *ext);
+typedef void *(*X509V3_EXT_S2I)(const struct v3_ext_method *method,
+ struct v3_ext_ctx *ctx, const char *str);
+typedef int (*X509V3_EXT_I2R) (const struct v3_ext_method *method, void *ext,
+ BIO *out, int indent);
+typedef void *(*X509V3_EXT_R2I)(const struct v3_ext_method *method,
+ struct v3_ext_ctx *ctx, const char *str);
+
+/* V3 extension structure */
+
+struct v3_ext_method {
+ int ext_nid;
+ int ext_flags;
+/* If this is set the following four fields are ignored */
+ ASN1_ITEM_EXP *it;
+/* Old style ASN1 calls */
+ X509V3_EXT_NEW ext_new;
+ X509V3_EXT_FREE ext_free;
+ X509V3_EXT_D2I d2i;
+ X509V3_EXT_I2D i2d;
+/* The following pair is used for string extensions */
+ X509V3_EXT_I2S i2s;
+ X509V3_EXT_S2I s2i;
+/* The following pair is used for multi-valued extensions */
+ X509V3_EXT_I2V i2v;
+ X509V3_EXT_V2I v2i;
+/* The following are used for raw extensions */
+ X509V3_EXT_I2R i2r;
+ X509V3_EXT_R2I r2i;
+ void *usr_data; /* Any extension specific data */
+};
+
+typedef struct X509V3_CONF_METHOD_st {
+ char *(*get_string) (void *db, const char *section, const char *value);
+ STACK_OF(CONF_VALUE) *(*get_section) (void *db, const char *section);
+ void (*free_string) (void *db, char *string);
+ void (*free_section) (void *db, STACK_OF(CONF_VALUE) *section);
+} X509V3_CONF_METHOD;
+
+/* Context specific info for producing X509 v3 extensions*/
+struct v3_ext_ctx {
+# define X509V3_CTX_TEST 0x1
+# ifndef OPENSSL_NO_DEPRECATED_3_0
+# define CTX_TEST X509V3_CTX_TEST
+# endif
+# define X509V3_CTX_REPLACE 0x2
+ int flags;
+ X509 *issuer_cert;
+ X509 *subject_cert;
+ X509_REQ *subject_req;
+ X509_CRL *crl;
+ X509V3_CONF_METHOD *db_meth;
+ void *db;
+ EVP_PKEY *issuer_pkey;
+/* Maybe more here */
+};
+
+typedef struct v3_ext_method X509V3_EXT_METHOD;
+
+{-
+ generate_stack_macros("X509V3_EXT_METHOD");
+-}
+
+/* ext_flags values */
+# define X509V3_EXT_DYNAMIC 0x1
+# define X509V3_EXT_CTX_DEP 0x2
+# define X509V3_EXT_MULTILINE 0x4
+
+typedef BIT_STRING_BITNAME ENUMERATED_NAMES;
+
+typedef struct BASIC_CONSTRAINTS_st {
+ int ca;
+ ASN1_INTEGER *pathlen;
+} BASIC_CONSTRAINTS;
+
+typedef struct PKEY_USAGE_PERIOD_st {
+ ASN1_GENERALIZEDTIME *notBefore;
+ ASN1_GENERALIZEDTIME *notAfter;
+} PKEY_USAGE_PERIOD;
+
+typedef struct otherName_st {
+ ASN1_OBJECT *type_id;
+ ASN1_TYPE *value;
+} OTHERNAME;
+
+typedef struct EDIPartyName_st {
+ ASN1_STRING *nameAssigner;
+ ASN1_STRING *partyName;
+} EDIPARTYNAME;
+
+typedef struct GENERAL_NAME_st {
+# define GEN_OTHERNAME 0
+# define GEN_EMAIL 1
+# define GEN_DNS 2
+# define GEN_X400 3
+# define GEN_DIRNAME 4
+# define GEN_EDIPARTY 5
+# define GEN_URI 6
+# define GEN_IPADD 7
+# define GEN_RID 8
+ int type;
+ union {
+ char *ptr;
+ OTHERNAME *otherName; /* otherName */
+ ASN1_IA5STRING *rfc822Name;
+ ASN1_IA5STRING *dNSName;
+ ASN1_TYPE *x400Address;
+ X509_NAME *directoryName;
+ EDIPARTYNAME *ediPartyName;
+ ASN1_IA5STRING *uniformResourceIdentifier;
+ ASN1_OCTET_STRING *iPAddress;
+ ASN1_OBJECT *registeredID;
+ /* Old names */
+ ASN1_OCTET_STRING *ip; /* iPAddress */
+ X509_NAME *dirn; /* dirn */
+ ASN1_IA5STRING *ia5; /* rfc822Name, dNSName,
+ * uniformResourceIdentifier */
+ ASN1_OBJECT *rid; /* registeredID */
+ ASN1_TYPE *other; /* x400Address */
+ } d;
+} GENERAL_NAME;
+
+typedef struct ACCESS_DESCRIPTION_st {
+ ASN1_OBJECT *method;
+ GENERAL_NAME *location;
+} ACCESS_DESCRIPTION;
+
+{-
+ generate_stack_macros("ACCESS_DESCRIPTION")
+ .generate_stack_macros("GENERAL_NAME");
+-}
+
+typedef STACK_OF(ACCESS_DESCRIPTION) AUTHORITY_INFO_ACCESS;
+typedef STACK_OF(ASN1_OBJECT) EXTENDED_KEY_USAGE;
+typedef STACK_OF(ASN1_INTEGER) TLS_FEATURE;
+typedef STACK_OF(GENERAL_NAME) GENERAL_NAMES;
+
+{-
+ generate_stack_macros("GENERAL_NAMES");
+-}
+
+typedef struct DIST_POINT_NAME_st {
+ int type;
+ union {
+ GENERAL_NAMES *fullname;
+ STACK_OF(X509_NAME_ENTRY) *relativename;
+ } name;
+/* If relativename then this contains the full distribution point name */
+ X509_NAME *dpname;
+} DIST_POINT_NAME;
+/* All existing reasons */
+# define CRLDP_ALL_REASONS 0x807f
+
+# define CRL_REASON_NONE -1
+# define CRL_REASON_UNSPECIFIED 0
+# define CRL_REASON_KEY_COMPROMISE 1
+# define CRL_REASON_CA_COMPROMISE 2
+# define CRL_REASON_AFFILIATION_CHANGED 3
+# define CRL_REASON_SUPERSEDED 4
+# define CRL_REASON_CESSATION_OF_OPERATION 5
+# define CRL_REASON_CERTIFICATE_HOLD 6
+# define CRL_REASON_REMOVE_FROM_CRL 8
+# define CRL_REASON_PRIVILEGE_WITHDRAWN 9
+# define CRL_REASON_AA_COMPROMISE 10
+
+struct DIST_POINT_st {
+ DIST_POINT_NAME *distpoint;
+ ASN1_BIT_STRING *reasons;
+ GENERAL_NAMES *CRLissuer;
+ int dp_reasons;
+};
+
+{-
+ generate_stack_macros("DIST_POINT");
+-}
+
+typedef STACK_OF(DIST_POINT) CRL_DIST_POINTS;
+
+struct AUTHORITY_KEYID_st {
+ ASN1_OCTET_STRING *keyid;
+ GENERAL_NAMES *issuer;
+ ASN1_INTEGER *serial;
+};
+
+/* Strong extranet structures */
+
+typedef struct SXNET_ID_st {
+ ASN1_INTEGER *zone;
+ ASN1_OCTET_STRING *user;
+} SXNETID;
+
+{-
+ generate_stack_macros("SXNETID");
+-}
+
+
+typedef struct SXNET_st {
+ ASN1_INTEGER *version;
+ STACK_OF(SXNETID) *ids;
+} SXNET;
+
+typedef struct ISSUER_SIGN_TOOL_st {
+ ASN1_UTF8STRING *signTool;
+ ASN1_UTF8STRING *cATool;
+ ASN1_UTF8STRING *signToolCert;
+ ASN1_UTF8STRING *cAToolCert;
+} ISSUER_SIGN_TOOL;
+
+typedef struct NOTICEREF_st {
+ ASN1_STRING *organization;
+ STACK_OF(ASN1_INTEGER) *noticenos;
+} NOTICEREF;
+
+typedef struct USERNOTICE_st {
+ NOTICEREF *noticeref;
+ ASN1_STRING *exptext;
+} USERNOTICE;
+
+typedef struct POLICYQUALINFO_st {
+ ASN1_OBJECT *pqualid;
+ union {
+ ASN1_IA5STRING *cpsuri;
+ USERNOTICE *usernotice;
+ ASN1_TYPE *other;
+ } d;
+} POLICYQUALINFO;
+
+{-
+ generate_stack_macros("POLICYQUALINFO");
+-}
+
+
+typedef struct POLICYINFO_st {
+ ASN1_OBJECT *policyid;
+ STACK_OF(POLICYQUALINFO) *qualifiers;
+} POLICYINFO;
+
+{-
+ generate_stack_macros("POLICYINFO");
+-}
+
+typedef STACK_OF(POLICYINFO) CERTIFICATEPOLICIES;
+
+typedef struct POLICY_MAPPING_st {
+ ASN1_OBJECT *issuerDomainPolicy;
+ ASN1_OBJECT *subjectDomainPolicy;
+} POLICY_MAPPING;
+
+{-
+ generate_stack_macros("POLICY_MAPPING");
+-}
+
+typedef STACK_OF(POLICY_MAPPING) POLICY_MAPPINGS;
+
+typedef struct GENERAL_SUBTREE_st {
+ GENERAL_NAME *base;
+ ASN1_INTEGER *minimum;
+ ASN1_INTEGER *maximum;
+} GENERAL_SUBTREE;
+
+{-
+ generate_stack_macros("GENERAL_SUBTREE");
+-}
+
+struct NAME_CONSTRAINTS_st {
+ STACK_OF(GENERAL_SUBTREE) *permittedSubtrees;
+ STACK_OF(GENERAL_SUBTREE) *excludedSubtrees;
+};
+
+typedef struct POLICY_CONSTRAINTS_st {
+ ASN1_INTEGER *requireExplicitPolicy;
+ ASN1_INTEGER *inhibitPolicyMapping;
+} POLICY_CONSTRAINTS;
+
+/* Proxy certificate structures, see RFC 3820 */
+typedef struct PROXY_POLICY_st {
+ ASN1_OBJECT *policyLanguage;
+ ASN1_OCTET_STRING *policy;
+} PROXY_POLICY;
+
+typedef struct PROXY_CERT_INFO_EXTENSION_st {
+ ASN1_INTEGER *pcPathLengthConstraint;
+ PROXY_POLICY *proxyPolicy;
+} PROXY_CERT_INFO_EXTENSION;
+
+DECLARE_ASN1_FUNCTIONS(PROXY_POLICY)
+DECLARE_ASN1_FUNCTIONS(PROXY_CERT_INFO_EXTENSION)
+
+struct ISSUING_DIST_POINT_st {
+ DIST_POINT_NAME *distpoint;
+ int onlyuser;
+ int onlyCA;
+ ASN1_BIT_STRING *onlysomereasons;
+ int indirectCRL;
+ int onlyattr;
+};
+
+/* Values in idp_flags field */
+/* IDP present */
+# define IDP_PRESENT 0x1
+/* IDP values inconsistent */
+# define IDP_INVALID 0x2
+/* onlyuser true */
+# define IDP_ONLYUSER 0x4
+/* onlyCA true */
+# define IDP_ONLYCA 0x8
+/* onlyattr true */
+# define IDP_ONLYATTR 0x10
+/* indirectCRL true */
+# define IDP_INDIRECT 0x20
+/* onlysomereasons present */
+# define IDP_REASONS 0x40
+
+# define X509V3_conf_err(val) ERR_add_error_data(6, \
+ "section:", (val)->section, \
+ ",name:", (val)->name, ",value:", (val)->value)
+
+# define X509V3_set_ctx_test(ctx) \
+ X509V3_set_ctx(ctx, NULL, NULL, NULL, NULL, X509V3_CTX_TEST)
+# define X509V3_set_ctx_nodb(ctx) (ctx)->db = NULL;
+
+# define EXT_BITSTRING(nid, table) { nid, 0, ASN1_ITEM_ref(ASN1_BIT_STRING), \
+ 0,0,0,0, \
+ 0,0, \
+ (X509V3_EXT_I2V)i2v_ASN1_BIT_STRING, \
+ (X509V3_EXT_V2I)v2i_ASN1_BIT_STRING, \
+ NULL, NULL, \
+ table}
+
+# define EXT_IA5STRING(nid) { nid, 0, ASN1_ITEM_ref(ASN1_IA5STRING), \
+ 0,0,0,0, \
+ (X509V3_EXT_I2S)i2s_ASN1_IA5STRING, \
+ (X509V3_EXT_S2I)s2i_ASN1_IA5STRING, \
+ 0,0,0,0, \
+ NULL}
+
+#define EXT_UTF8STRING(nid) { nid, 0, ASN1_ITEM_ref(ASN1_UTF8STRING), \
+ 0,0,0,0, \
+ (X509V3_EXT_I2S)i2s_ASN1_UTF8STRING, \
+ (X509V3_EXT_S2I)s2i_ASN1_UTF8STRING, \
+ 0,0,0,0, \
+ NULL}
+
+# define EXT_END { -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
+
+/* X509_PURPOSE stuff */
+
+# define EXFLAG_BCONS 0x1
+# define EXFLAG_KUSAGE 0x2
+# define EXFLAG_XKUSAGE 0x4
+# define EXFLAG_NSCERT 0x8
+
+# define EXFLAG_CA 0x10
+# define EXFLAG_SI 0x20 /* self-issued, maybe not self-signed */
+# define EXFLAG_V1 0x40
+# define EXFLAG_INVALID 0x80
+/* EXFLAG_SET is set to indicate that some values have been precomputed */
+# define EXFLAG_SET 0x100
+# define EXFLAG_CRITICAL 0x200
+# define EXFLAG_PROXY 0x400
+
+# define EXFLAG_INVALID_POLICY 0x800
+# define EXFLAG_FRESHEST 0x1000
+# define EXFLAG_SS 0x2000 /* cert is apparently self-signed */
+
+# define EXFLAG_BCONS_CRITICAL 0x10000
+# define EXFLAG_AKID_CRITICAL 0x20000
+# define EXFLAG_SKID_CRITICAL 0x40000
+# define EXFLAG_SAN_CRITICAL 0x80000
+# define EXFLAG_NO_FINGERPRINT 0x100000
+
+# define KU_DIGITAL_SIGNATURE 0x0080
+# define KU_NON_REPUDIATION 0x0040
+# define KU_KEY_ENCIPHERMENT 0x0020
+# define KU_DATA_ENCIPHERMENT 0x0010
+# define KU_KEY_AGREEMENT 0x0008
+# define KU_KEY_CERT_SIGN 0x0004
+# define KU_CRL_SIGN 0x0002
+# define KU_ENCIPHER_ONLY 0x0001
+# define KU_DECIPHER_ONLY 0x8000
+
+# define NS_SSL_CLIENT 0x80
+# define NS_SSL_SERVER 0x40
+# define NS_SMIME 0x20
+# define NS_OBJSIGN 0x10
+# define NS_SSL_CA 0x04
+# define NS_SMIME_CA 0x02
+# define NS_OBJSIGN_CA 0x01
+# define NS_ANY_CA (NS_SSL_CA|NS_SMIME_CA|NS_OBJSIGN_CA)
+
+# define XKU_SSL_SERVER 0x1
+# define XKU_SSL_CLIENT 0x2
+# define XKU_SMIME 0x4
+# define XKU_CODE_SIGN 0x8
+# define XKU_SGC 0x10 /* Netscape or MS Server-Gated Crypto */
+# define XKU_OCSP_SIGN 0x20
+# define XKU_TIMESTAMP 0x40
+# define XKU_DVCS 0x80
+# define XKU_ANYEKU 0x100
+
+# define X509_PURPOSE_DYNAMIC 0x1
+# define X509_PURPOSE_DYNAMIC_NAME 0x2
+
+typedef struct x509_purpose_st {
+ int purpose;
+ int trust; /* Default trust ID */
+ int flags;
+ int (*check_purpose) (const struct x509_purpose_st *, const X509 *, int);
+ char *name;
+ char *sname;
+ void *usr_data;
+} X509_PURPOSE;
+
+{-
+ generate_stack_macros("X509_PURPOSE");
+-}
+
+
+# define X509_PURPOSE_SSL_CLIENT 1
+# define X509_PURPOSE_SSL_SERVER 2
+# define X509_PURPOSE_NS_SSL_SERVER 3
+# define X509_PURPOSE_SMIME_SIGN 4
+# define X509_PURPOSE_SMIME_ENCRYPT 5
+# define X509_PURPOSE_CRL_SIGN 6
+# define X509_PURPOSE_ANY 7
+# define X509_PURPOSE_OCSP_HELPER 8
+# define X509_PURPOSE_TIMESTAMP_SIGN 9
+
+# define X509_PURPOSE_MIN 1
+# define X509_PURPOSE_MAX 9
+
+/* Flags for X509V3_EXT_print() */
+
+# define X509V3_EXT_UNKNOWN_MASK (0xfL << 16)
+/* Return error for unknown extensions */
+# define X509V3_EXT_DEFAULT 0
+/* Print error for unknown extensions */
+# define X509V3_EXT_ERROR_UNKNOWN (1L << 16)
+/* ASN1 parse unknown extensions */
+# define X509V3_EXT_PARSE_UNKNOWN (2L << 16)
+/* BIO_dump unknown extensions */
+# define X509V3_EXT_DUMP_UNKNOWN (3L << 16)
+
+/* Flags for X509V3_add1_i2d */
+
+# define X509V3_ADD_OP_MASK 0xfL
+# define X509V3_ADD_DEFAULT 0L
+# define X509V3_ADD_APPEND 1L
+# define X509V3_ADD_REPLACE 2L
+# define X509V3_ADD_REPLACE_EXISTING 3L
+# define X509V3_ADD_KEEP_EXISTING 4L
+# define X509V3_ADD_DELETE 5L
+# define X509V3_ADD_SILENT 0x10
+
+DECLARE_ASN1_FUNCTIONS(BASIC_CONSTRAINTS)
+
+DECLARE_ASN1_FUNCTIONS(SXNET)
+DECLARE_ASN1_FUNCTIONS(SXNETID)
+
+DECLARE_ASN1_FUNCTIONS(ISSUER_SIGN_TOOL)
+
+int SXNET_add_id_asc(SXNET **psx, const char *zone, const char *user, int userlen);
+int SXNET_add_id_ulong(SXNET **psx, unsigned long lzone, const char *user,
+ int userlen);
+int SXNET_add_id_INTEGER(SXNET **psx, ASN1_INTEGER *izone, const char *user,
+ int userlen);
+
+ASN1_OCTET_STRING *SXNET_get_id_asc(SXNET *sx, const char *zone);
+ASN1_OCTET_STRING *SXNET_get_id_ulong(SXNET *sx, unsigned long lzone);
+ASN1_OCTET_STRING *SXNET_get_id_INTEGER(SXNET *sx, ASN1_INTEGER *zone);
+
+DECLARE_ASN1_FUNCTIONS(AUTHORITY_KEYID)
+
+DECLARE_ASN1_FUNCTIONS(PKEY_USAGE_PERIOD)
+
+DECLARE_ASN1_FUNCTIONS(GENERAL_NAME)
+DECLARE_ASN1_DUP_FUNCTION(GENERAL_NAME)
+int GENERAL_NAME_cmp(GENERAL_NAME *a, GENERAL_NAME *b);
+
+ASN1_BIT_STRING *v2i_ASN1_BIT_STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx,
+ STACK_OF(CONF_VALUE) *nval);
+STACK_OF(CONF_VALUE) *i2v_ASN1_BIT_STRING(X509V3_EXT_METHOD *method,
+ ASN1_BIT_STRING *bits,
+ STACK_OF(CONF_VALUE) *extlist);
+char *i2s_ASN1_IA5STRING(X509V3_EXT_METHOD *method, ASN1_IA5STRING *ia5);
+ASN1_IA5STRING *s2i_ASN1_IA5STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, const char *str);
+char *i2s_ASN1_UTF8STRING(X509V3_EXT_METHOD *method, ASN1_UTF8STRING *utf8);
+ASN1_UTF8STRING *s2i_ASN1_UTF8STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, const char *str);
+
+STACK_OF(CONF_VALUE) *i2v_GENERAL_NAME(X509V3_EXT_METHOD *method,
+ GENERAL_NAME *gen,
+ STACK_OF(CONF_VALUE) *ret);
+int GENERAL_NAME_print(BIO *out, GENERAL_NAME *gen);
+
+DECLARE_ASN1_FUNCTIONS(GENERAL_NAMES)
+
+STACK_OF(CONF_VALUE) *i2v_GENERAL_NAMES(X509V3_EXT_METHOD *method,
+ GENERAL_NAMES *gen,
+ STACK_OF(CONF_VALUE) *extlist);
+GENERAL_NAMES *v2i_GENERAL_NAMES(const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *nval);
+
+DECLARE_ASN1_FUNCTIONS(OTHERNAME)
+DECLARE_ASN1_FUNCTIONS(EDIPARTYNAME)
+int OTHERNAME_cmp(OTHERNAME *a, OTHERNAME *b);
+void GENERAL_NAME_set0_value(GENERAL_NAME *a, int type, void *value);
+void *GENERAL_NAME_get0_value(const GENERAL_NAME *a, int *ptype);
+int GENERAL_NAME_set0_othername(GENERAL_NAME *gen,
+ ASN1_OBJECT *oid, ASN1_TYPE *value);
+int GENERAL_NAME_get0_otherName(const GENERAL_NAME *gen,
+ ASN1_OBJECT **poid, ASN1_TYPE **pvalue);
+
+char *i2s_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method,
+ const ASN1_OCTET_STRING *ia5);
+ASN1_OCTET_STRING *s2i_ASN1_OCTET_STRING(X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, const char *str);
+
+DECLARE_ASN1_FUNCTIONS(EXTENDED_KEY_USAGE)
+int i2a_ACCESS_DESCRIPTION(BIO *bp, const ACCESS_DESCRIPTION *a);
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(TLS_FEATURE)
+
+DECLARE_ASN1_FUNCTIONS(CERTIFICATEPOLICIES)
+DECLARE_ASN1_FUNCTIONS(POLICYINFO)
+DECLARE_ASN1_FUNCTIONS(POLICYQUALINFO)
+DECLARE_ASN1_FUNCTIONS(USERNOTICE)
+DECLARE_ASN1_FUNCTIONS(NOTICEREF)
+
+DECLARE_ASN1_FUNCTIONS(CRL_DIST_POINTS)
+DECLARE_ASN1_FUNCTIONS(DIST_POINT)
+DECLARE_ASN1_FUNCTIONS(DIST_POINT_NAME)
+DECLARE_ASN1_FUNCTIONS(ISSUING_DIST_POINT)
+
+int DIST_POINT_set_dpname(DIST_POINT_NAME *dpn, const X509_NAME *iname);
+
+int NAME_CONSTRAINTS_check(X509 *x, NAME_CONSTRAINTS *nc);
+int NAME_CONSTRAINTS_check_CN(X509 *x, NAME_CONSTRAINTS *nc);
+
+DECLARE_ASN1_FUNCTIONS(ACCESS_DESCRIPTION)
+DECLARE_ASN1_FUNCTIONS(AUTHORITY_INFO_ACCESS)
+
+DECLARE_ASN1_ITEM(POLICY_MAPPING)
+DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_MAPPING)
+DECLARE_ASN1_ITEM(POLICY_MAPPINGS)
+
+DECLARE_ASN1_ITEM(GENERAL_SUBTREE)
+DECLARE_ASN1_ALLOC_FUNCTIONS(GENERAL_SUBTREE)
+
+DECLARE_ASN1_ITEM(NAME_CONSTRAINTS)
+DECLARE_ASN1_ALLOC_FUNCTIONS(NAME_CONSTRAINTS)
+
+DECLARE_ASN1_ALLOC_FUNCTIONS(POLICY_CONSTRAINTS)
+DECLARE_ASN1_ITEM(POLICY_CONSTRAINTS)
+
+GENERAL_NAME *a2i_GENERAL_NAME(GENERAL_NAME *out,
+ const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, int gen_type,
+ const char *value, int is_nc);
+
+# ifdef OPENSSL_CONF_H
+GENERAL_NAME *v2i_GENERAL_NAME(const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, CONF_VALUE *cnf);
+GENERAL_NAME *v2i_GENERAL_NAME_ex(GENERAL_NAME *out,
+ const X509V3_EXT_METHOD *method,
+ X509V3_CTX *ctx, CONF_VALUE *cnf,
+ int is_nc);
+
+void X509V3_conf_free(CONF_VALUE *val);
+
+X509_EXTENSION *X509V3_EXT_nconf_nid(CONF *conf, X509V3_CTX *ctx, int ext_nid,
+ const char *value);
+X509_EXTENSION *X509V3_EXT_nconf(CONF *conf, X509V3_CTX *ctx, const char *name,
+ const char *value);
+int X509V3_EXT_add_nconf_sk(CONF *conf, X509V3_CTX *ctx, const char *section,
+ STACK_OF(X509_EXTENSION) **sk);
+int X509V3_EXT_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
+ X509 *cert);
+int X509V3_EXT_REQ_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
+ X509_REQ *req);
+int X509V3_EXT_CRL_add_nconf(CONF *conf, X509V3_CTX *ctx, const char *section,
+ X509_CRL *crl);
+
+X509_EXTENSION *X509V3_EXT_conf_nid(LHASH_OF(CONF_VALUE) *conf,
+ X509V3_CTX *ctx, int ext_nid,
+ const char *value);
+X509_EXTENSION *X509V3_EXT_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *name, const char *value);
+int X509V3_EXT_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *section, X509 *cert);
+int X509V3_EXT_REQ_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *section, X509_REQ *req);
+int X509V3_EXT_CRL_add_conf(LHASH_OF(CONF_VALUE) *conf, X509V3_CTX *ctx,
+ const char *section, X509_CRL *crl);
+
+int X509V3_add_value_bool_nf(const char *name, int asn1_bool,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_get_value_bool(const CONF_VALUE *value, int *asn1_bool);
+int X509V3_get_value_int(const CONF_VALUE *value, ASN1_INTEGER **aint);
+void X509V3_set_nconf(X509V3_CTX *ctx, CONF *conf);
+void X509V3_set_conf_lhash(X509V3_CTX *ctx, LHASH_OF(CONF_VALUE) *lhash);
+# endif
+
+char *X509V3_get_string(X509V3_CTX *ctx, const char *name, const char *section);
+STACK_OF(CONF_VALUE) *X509V3_get_section(X509V3_CTX *ctx, const char *section);
+void X509V3_string_free(X509V3_CTX *ctx, char *str);
+void X509V3_section_free(X509V3_CTX *ctx, STACK_OF(CONF_VALUE) *section);
+void X509V3_set_ctx(X509V3_CTX *ctx, X509 *issuer, X509 *subject,
+ X509_REQ *req, X509_CRL *crl, int flags);
+/* For API backward compatibility, this is separate from X509V3_set_ctx(): */
+int X509V3_set_issuer_pkey(X509V3_CTX *ctx, EVP_PKEY *pkey);
+
+int X509V3_add_value(const char *name, const char *value,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_add_value_uchar(const char *name, const unsigned char *value,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_add_value_bool(const char *name, int asn1_bool,
+ STACK_OF(CONF_VALUE) **extlist);
+int X509V3_add_value_int(const char *name, const ASN1_INTEGER *aint,
+ STACK_OF(CONF_VALUE) **extlist);
+char *i2s_ASN1_INTEGER(X509V3_EXT_METHOD *meth, const ASN1_INTEGER *aint);
+ASN1_INTEGER *s2i_ASN1_INTEGER(X509V3_EXT_METHOD *meth, const char *value);
+char *i2s_ASN1_ENUMERATED(X509V3_EXT_METHOD *meth, const ASN1_ENUMERATED *aint);
+char *i2s_ASN1_ENUMERATED_TABLE(X509V3_EXT_METHOD *meth,
+ const ASN1_ENUMERATED *aint);
+int X509V3_EXT_add(X509V3_EXT_METHOD *ext);
+int X509V3_EXT_add_list(X509V3_EXT_METHOD *extlist);
+int X509V3_EXT_add_alias(int nid_to, int nid_from);
+void X509V3_EXT_cleanup(void);
+
+const X509V3_EXT_METHOD *X509V3_EXT_get(X509_EXTENSION *ext);
+const X509V3_EXT_METHOD *X509V3_EXT_get_nid(int nid);
+int X509V3_add_standard_extensions(void);
+STACK_OF(CONF_VALUE) *X509V3_parse_list(const char *line);
+void *X509V3_EXT_d2i(X509_EXTENSION *ext);
+void *X509V3_get_d2i(const STACK_OF(X509_EXTENSION) *x, int nid, int *crit,
+ int *idx);
+
+X509_EXTENSION *X509V3_EXT_i2d(int ext_nid, int crit, void *ext_struc);
+int X509V3_add1_i2d(STACK_OF(X509_EXTENSION) **x, int nid, void *value,
+ int crit, unsigned long flags);
+
+#ifndef OPENSSL_NO_DEPRECATED_1_1_0
+/* The new declarations are in crypto.h, but the old ones were here. */
+# define hex_to_string OPENSSL_buf2hexstr
+# define string_to_hex OPENSSL_hexstr2buf
+#endif
+
+void X509V3_EXT_val_prn(BIO *out, STACK_OF(CONF_VALUE) *val, int indent,
+ int ml);
+int X509V3_EXT_print(BIO *out, X509_EXTENSION *ext, unsigned long flag,
+ int indent);
+#ifndef OPENSSL_NO_STDIO
+int X509V3_EXT_print_fp(FILE *out, X509_EXTENSION *ext, int flag, int indent);
+#endif
+int X509V3_extensions_print(BIO *out, const char *title,
+ const STACK_OF(X509_EXTENSION) *exts,
+ unsigned long flag, int indent);
+
+int X509_check_ca(X509 *x);
+int X509_check_purpose(X509 *x, int id, int ca);
+int X509_supported_extension(X509_EXTENSION *ex);
+int X509_PURPOSE_set(int *p, int purpose);
+int X509_check_issued(X509 *issuer, X509 *subject);
+int X509_check_akid(const X509 *issuer, const AUTHORITY_KEYID *akid);
+void X509_set_proxy_flag(X509 *x);
+void X509_set_proxy_pathlen(X509 *x, long l);
+long X509_get_proxy_pathlen(X509 *x);
+
+uint32_t X509_get_extension_flags(X509 *x);
+uint32_t X509_get_key_usage(X509 *x);
+uint32_t X509_get_extended_key_usage(X509 *x);
+const ASN1_OCTET_STRING *X509_get0_subject_key_id(X509 *x);
+const ASN1_OCTET_STRING *X509_get0_authority_key_id(X509 *x);
+const GENERAL_NAMES *X509_get0_authority_issuer(X509 *x);
+const ASN1_INTEGER *X509_get0_authority_serial(X509 *x);
+
+int X509_PURPOSE_get_count(void);
+X509_PURPOSE *X509_PURPOSE_get0(int idx);
+int X509_PURPOSE_get_by_sname(const char *sname);
+int X509_PURPOSE_get_by_id(int id);
+int X509_PURPOSE_add(int id, int trust, int flags,
+ int (*ck) (const X509_PURPOSE *, const X509 *, int),
+ const char *name, const char *sname, void *arg);
+char *X509_PURPOSE_get0_name(const X509_PURPOSE *xp);
+char *X509_PURPOSE_get0_sname(const X509_PURPOSE *xp);
+int X509_PURPOSE_get_trust(const X509_PURPOSE *xp);
+void X509_PURPOSE_cleanup(void);
+int X509_PURPOSE_get_id(const X509_PURPOSE *);
+
+STACK_OF(OPENSSL_STRING) *X509_get1_email(X509 *x);
+STACK_OF(OPENSSL_STRING) *X509_REQ_get1_email(X509_REQ *x);
+void X509_email_free(STACK_OF(OPENSSL_STRING) *sk);
+STACK_OF(OPENSSL_STRING) *X509_get1_ocsp(X509 *x);
+/* Flags for X509_check_* functions */
+
+/*
+ * Always check subject name for host match even if subject alt names present
+ */
+# define X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT 0x1
+/* Disable wildcard matching for dnsName fields and common name. */
+# define X509_CHECK_FLAG_NO_WILDCARDS 0x2
+/* Wildcards must not match a partial label. */
+# define X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS 0x4
+/* Allow (non-partial) wildcards to match multiple labels. */
+# define X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS 0x8
+/* Constraint verifier subdomain patterns to match a single labels. */
+# define X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS 0x10
+/* Never check the subject CN */
+# define X509_CHECK_FLAG_NEVER_CHECK_SUBJECT 0x20
+/*
+ * Match reference identifiers starting with "." to any sub-domain.
+ * This is a non-public flag, turned on implicitly when the subject
+ * reference identity is a DNS name.
+ */
+# define _X509_CHECK_FLAG_DOT_SUBDOMAINS 0x8000
+
+int X509_check_host(X509 *x, const char *chk, size_t chklen,
+ unsigned int flags, char **peername);
+int X509_check_email(X509 *x, const char *chk, size_t chklen,
+ unsigned int flags);
+int X509_check_ip(X509 *x, const unsigned char *chk, size_t chklen,
+ unsigned int flags);
+int X509_check_ip_asc(X509 *x, const char *ipasc, unsigned int flags);
+
+ASN1_OCTET_STRING *a2i_IPADDRESS(const char *ipasc);
+ASN1_OCTET_STRING *a2i_IPADDRESS_NC(const char *ipasc);
+int X509V3_NAME_from_section(X509_NAME *nm, STACK_OF(CONF_VALUE) *dn_sk,
+ unsigned long chtype);
+
+void X509_POLICY_NODE_print(BIO *out, X509_POLICY_NODE *node, int indent);
+{-
+ generate_stack_macros("X509_POLICY_NODE");
+-}
+
+
+#ifndef OPENSSL_NO_RFC3779
+typedef struct ASRange_st {
+ ASN1_INTEGER *min, *max;
+} ASRange;
+
+# define ASIdOrRange_id 0
+# define ASIdOrRange_range 1
+
+typedef struct ASIdOrRange_st {
+ int type;
+ union {
+ ASN1_INTEGER *id;
+ ASRange *range;
+ } u;
+} ASIdOrRange;
+
+{-
+ generate_stack_macros("ASIdOrRange");
+-}
+
+typedef STACK_OF(ASIdOrRange) ASIdOrRanges;
+
+# define ASIdentifierChoice_inherit 0
+# define ASIdentifierChoice_asIdsOrRanges 1
+
+typedef struct ASIdentifierChoice_st {
+ int type;
+ union {
+ ASN1_NULL *inherit;
+ ASIdOrRanges *asIdsOrRanges;
+ } u;
+} ASIdentifierChoice;
+
+typedef struct ASIdentifiers_st {
+ ASIdentifierChoice *asnum, *rdi;
+} ASIdentifiers;
+
+DECLARE_ASN1_FUNCTIONS(ASRange)
+DECLARE_ASN1_FUNCTIONS(ASIdOrRange)
+DECLARE_ASN1_FUNCTIONS(ASIdentifierChoice)
+DECLARE_ASN1_FUNCTIONS(ASIdentifiers)
+
+typedef struct IPAddressRange_st {
+ ASN1_BIT_STRING *min, *max;
+} IPAddressRange;
+
+# define IPAddressOrRange_addressPrefix 0
+# define IPAddressOrRange_addressRange 1
+
+typedef struct IPAddressOrRange_st {
+ int type;
+ union {
+ ASN1_BIT_STRING *addressPrefix;
+ IPAddressRange *addressRange;
+ } u;
+} IPAddressOrRange;
+
+{-
+ generate_stack_macros("IPAddressOrRange");
+-}
+
+typedef STACK_OF(IPAddressOrRange) IPAddressOrRanges;
+
+# define IPAddressChoice_inherit 0
+# define IPAddressChoice_addressesOrRanges 1
+
+typedef struct IPAddressChoice_st {
+ int type;
+ union {
+ ASN1_NULL *inherit;
+ IPAddressOrRanges *addressesOrRanges;
+ } u;
+} IPAddressChoice;
+
+typedef struct IPAddressFamily_st {
+ ASN1_OCTET_STRING *addressFamily;
+ IPAddressChoice *ipAddressChoice;
+} IPAddressFamily;
+
+{-
+ generate_stack_macros("IPAddressFamily");
+-}
+
+
+typedef STACK_OF(IPAddressFamily) IPAddrBlocks;
+
+DECLARE_ASN1_FUNCTIONS(IPAddressRange)
+DECLARE_ASN1_FUNCTIONS(IPAddressOrRange)
+DECLARE_ASN1_FUNCTIONS(IPAddressChoice)
+DECLARE_ASN1_FUNCTIONS(IPAddressFamily)
+
+/*
+ * API tag for elements of the ASIdentifer SEQUENCE.
+ */
+# define V3_ASID_ASNUM 0
+# define V3_ASID_RDI 1
+
+/*
+ * AFI values, assigned by IANA. It'd be nice to make the AFI
+ * handling code totally generic, but there are too many little things
+ * that would need to be defined for other address families for it to
+ * be worth the trouble.
+ */
+# define IANA_AFI_IPV4 1
+# define IANA_AFI_IPV6 2
+
+/*
+ * Utilities to construct and extract values from RFC3779 extensions,
+ * since some of the encodings (particularly for IP address prefixes
+ * and ranges) are a bit tedious to work with directly.
+ */
+int X509v3_asid_add_inherit(ASIdentifiers *asid, int which);
+int X509v3_asid_add_id_or_range(ASIdentifiers *asid, int which,
+ ASN1_INTEGER *min, ASN1_INTEGER *max);
+int X509v3_addr_add_inherit(IPAddrBlocks *addr,
+ const unsigned afi, const unsigned *safi);
+int X509v3_addr_add_prefix(IPAddrBlocks *addr,
+ const unsigned afi, const unsigned *safi,
+ unsigned char *a, const int prefixlen);
+int X509v3_addr_add_range(IPAddrBlocks *addr,
+ const unsigned afi, const unsigned *safi,
+ unsigned char *min, unsigned char *max);
+unsigned X509v3_addr_get_afi(const IPAddressFamily *f);
+int X509v3_addr_get_range(IPAddressOrRange *aor, const unsigned afi,
+ unsigned char *min, unsigned char *max,
+ const int length);
+
+/*
+ * Canonical forms.
+ */
+int X509v3_asid_is_canonical(ASIdentifiers *asid);
+int X509v3_addr_is_canonical(IPAddrBlocks *addr);
+int X509v3_asid_canonize(ASIdentifiers *asid);
+int X509v3_addr_canonize(IPAddrBlocks *addr);
+
+/*
+ * Tests for inheritance and containment.
+ */
+int X509v3_asid_inherits(ASIdentifiers *asid);
+int X509v3_addr_inherits(IPAddrBlocks *addr);
+int X509v3_asid_subset(ASIdentifiers *a, ASIdentifiers *b);
+int X509v3_addr_subset(IPAddrBlocks *a, IPAddrBlocks *b);
+
+/*
+ * Check whether RFC 3779 extensions nest properly in chains.
+ */
+int X509v3_asid_validate_path(X509_STORE_CTX *);
+int X509v3_addr_validate_path(X509_STORE_CTX *);
+int X509v3_asid_validate_resource_set(STACK_OF(X509) *chain,
+ ASIdentifiers *ext,
+ int allow_inheritance);
+int X509v3_addr_validate_resource_set(STACK_OF(X509) *chain,
+ IPAddrBlocks *ext, int allow_inheritance);
+
+#endif /* OPENSSL_NO_RFC3779 */
+
+{-
+ generate_stack_macros("ASN1_STRING");
+-}
+
+/*
+ * Admission Syntax
+ */
+typedef struct NamingAuthority_st NAMING_AUTHORITY;
+typedef struct ProfessionInfo_st PROFESSION_INFO;
+typedef struct Admissions_st ADMISSIONS;
+typedef struct AdmissionSyntax_st ADMISSION_SYNTAX;
+DECLARE_ASN1_FUNCTIONS(NAMING_AUTHORITY)
+DECLARE_ASN1_FUNCTIONS(PROFESSION_INFO)
+DECLARE_ASN1_FUNCTIONS(ADMISSIONS)
+DECLARE_ASN1_FUNCTIONS(ADMISSION_SYNTAX)
+{-
+ generate_stack_macros("PROFESSION_INFO")
+ .generate_stack_macros("ADMISSIONS");
+-}
+typedef STACK_OF(PROFESSION_INFO) PROFESSION_INFOS;
+
+const ASN1_OBJECT *NAMING_AUTHORITY_get0_authorityId(
+ const NAMING_AUTHORITY *n);
+const ASN1_IA5STRING *NAMING_AUTHORITY_get0_authorityURL(
+ const NAMING_AUTHORITY *n);
+const ASN1_STRING *NAMING_AUTHORITY_get0_authorityText(
+ const NAMING_AUTHORITY *n);
+void NAMING_AUTHORITY_set0_authorityId(NAMING_AUTHORITY *n,
+ ASN1_OBJECT* namingAuthorityId);
+void NAMING_AUTHORITY_set0_authorityURL(NAMING_AUTHORITY *n,
+ ASN1_IA5STRING* namingAuthorityUrl);
+void NAMING_AUTHORITY_set0_authorityText(NAMING_AUTHORITY *n,
+ ASN1_STRING* namingAuthorityText);
+
+const GENERAL_NAME *ADMISSION_SYNTAX_get0_admissionAuthority(
+ const ADMISSION_SYNTAX *as);
+void ADMISSION_SYNTAX_set0_admissionAuthority(
+ ADMISSION_SYNTAX *as, GENERAL_NAME *aa);
+const STACK_OF(ADMISSIONS) *ADMISSION_SYNTAX_get0_contentsOfAdmissions(
+ const ADMISSION_SYNTAX *as);
+void ADMISSION_SYNTAX_set0_contentsOfAdmissions(
+ ADMISSION_SYNTAX *as, STACK_OF(ADMISSIONS) *a);
+const GENERAL_NAME *ADMISSIONS_get0_admissionAuthority(const ADMISSIONS *a);
+void ADMISSIONS_set0_admissionAuthority(ADMISSIONS *a, GENERAL_NAME *aa);
+const NAMING_AUTHORITY *ADMISSIONS_get0_namingAuthority(const ADMISSIONS *a);
+void ADMISSIONS_set0_namingAuthority(ADMISSIONS *a, NAMING_AUTHORITY *na);
+const PROFESSION_INFOS *ADMISSIONS_get0_professionInfos(const ADMISSIONS *a);
+void ADMISSIONS_set0_professionInfos(ADMISSIONS *a, PROFESSION_INFOS *pi);
+const ASN1_OCTET_STRING *PROFESSION_INFO_get0_addProfessionInfo(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_addProfessionInfo(
+ PROFESSION_INFO *pi, ASN1_OCTET_STRING *aos);
+const NAMING_AUTHORITY *PROFESSION_INFO_get0_namingAuthority(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_namingAuthority(
+ PROFESSION_INFO *pi, NAMING_AUTHORITY *na);
+const STACK_OF(ASN1_STRING) *PROFESSION_INFO_get0_professionItems(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_professionItems(
+ PROFESSION_INFO *pi, STACK_OF(ASN1_STRING) *as);
+const STACK_OF(ASN1_OBJECT) *PROFESSION_INFO_get0_professionOIDs(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_professionOIDs(
+ PROFESSION_INFO *pi, STACK_OF(ASN1_OBJECT) *po);
+const ASN1_PRINTABLESTRING *PROFESSION_INFO_get0_registrationNumber(
+ const PROFESSION_INFO *pi);
+void PROFESSION_INFO_set0_registrationNumber(
+ PROFESSION_INFO *pi, ASN1_PRINTABLESTRING *rn);
+
+# ifdef __cplusplus
+}
+# endif
+#endif
diff --git a/include/openssl/x509v3err.h b/include/openssl/x509v3err.h
new file mode 100644
index 00000000..1ae3a562
--- /dev/null
+++ b/include/openssl/x509v3err.h
@@ -0,0 +1,93 @@
+/*
+ * Generated by util/mkerr.pl DO NOT EDIT
+ * Copyright 1995-2021 The OpenSSL Project Authors. All Rights Reserved.
+ *
+ * Licensed under the Apache License 2.0 (the "License"). You may not use
+ * this file except in compliance with the License. You can obtain a copy
+ * in the file LICENSE in the source distribution or at
+ * https://www.openssl.org/source/license.html
+ */
+
+#ifndef OPENSSL_X509V3ERR_H
+# define OPENSSL_X509V3ERR_H
+# pragma once
+
+# include <openssl/opensslconf.h>
+# include <openssl/symhacks.h>
+# include <openssl/cryptoerr_legacy.h>
+
+
+
+/*
+ * X509V3 reason codes.
+ */
+# define X509V3_R_BAD_IP_ADDRESS 118
+# define X509V3_R_BAD_OBJECT 119
+# define X509V3_R_BN_DEC2BN_ERROR 100
+# define X509V3_R_BN_TO_ASN1_INTEGER_ERROR 101
+# define X509V3_R_DIRNAME_ERROR 149
+# define X509V3_R_DISTPOINT_ALREADY_SET 160
+# define X509V3_R_DUPLICATE_ZONE_ID 133
+# define X509V3_R_EMPTY_KEY_USAGE 169
+# define X509V3_R_ERROR_CONVERTING_ZONE 131
+# define X509V3_R_ERROR_CREATING_EXTENSION 144
+# define X509V3_R_ERROR_IN_EXTENSION 128
+# define X509V3_R_EXPECTED_A_SECTION_NAME 137
+# define X509V3_R_EXTENSION_EXISTS 145
+# define X509V3_R_EXTENSION_NAME_ERROR 115
+# define X509V3_R_EXTENSION_NOT_FOUND 102
+# define X509V3_R_EXTENSION_SETTING_NOT_SUPPORTED 103
+# define X509V3_R_EXTENSION_VALUE_ERROR 116
+# define X509V3_R_ILLEGAL_EMPTY_EXTENSION 151
+# define X509V3_R_INCORRECT_POLICY_SYNTAX_TAG 152
+# define X509V3_R_INVALID_ASNUMBER 162
+# define X509V3_R_INVALID_ASRANGE 163
+# define X509V3_R_INVALID_BOOLEAN_STRING 104
+# define X509V3_R_INVALID_CERTIFICATE 158
+# define X509V3_R_INVALID_EMPTY_NAME 108
+# define X509V3_R_INVALID_EXTENSION_STRING 105
+# define X509V3_R_INVALID_INHERITANCE 165
+# define X509V3_R_INVALID_IPADDRESS 166
+# define X509V3_R_INVALID_MULTIPLE_RDNS 161
+# define X509V3_R_INVALID_NAME 106
+# define X509V3_R_INVALID_NULL_ARGUMENT 107
+# define X509V3_R_INVALID_NULL_VALUE 109
+# define X509V3_R_INVALID_NUMBER 140
+# define X509V3_R_INVALID_NUMBERS 141
+# define X509V3_R_INVALID_OBJECT_IDENTIFIER 110
+# define X509V3_R_INVALID_OPTION 138
+# define X509V3_R_INVALID_POLICY_IDENTIFIER 134
+# define X509V3_R_INVALID_PROXY_POLICY_SETTING 153
+# define X509V3_R_INVALID_PURPOSE 146
+# define X509V3_R_INVALID_SAFI 164
+# define X509V3_R_INVALID_SECTION 135
+# define X509V3_R_INVALID_SYNTAX 143
+# define X509V3_R_ISSUER_DECODE_ERROR 126
+# define X509V3_R_MISSING_VALUE 124
+# define X509V3_R_NEED_ORGANIZATION_AND_NUMBERS 142
+# define X509V3_R_NEGATIVE_PATHLEN 168
+# define X509V3_R_NO_CONFIG_DATABASE 136
+# define X509V3_R_NO_ISSUER_CERTIFICATE 121
+# define X509V3_R_NO_ISSUER_DETAILS 127
+# define X509V3_R_NO_POLICY_IDENTIFIER 139
+# define X509V3_R_NO_PROXY_CERT_POLICY_LANGUAGE_DEFINED 154
+# define X509V3_R_NO_PUBLIC_KEY 114
+# define X509V3_R_NO_SUBJECT_DETAILS 125
+# define X509V3_R_OPERATION_NOT_DEFINED 148
+# define X509V3_R_OTHERNAME_ERROR 147
+# define X509V3_R_POLICY_LANGUAGE_ALREADY_DEFINED 155
+# define X509V3_R_POLICY_PATH_LENGTH 156
+# define X509V3_R_POLICY_PATH_LENGTH_ALREADY_DEFINED 157
+# define X509V3_R_POLICY_WHEN_PROXY_LANGUAGE_REQUIRES_NO_POLICY 159
+# define X509V3_R_SECTION_NOT_FOUND 150
+# define X509V3_R_UNABLE_TO_GET_ISSUER_DETAILS 122
+# define X509V3_R_UNABLE_TO_GET_ISSUER_KEYID 123
+# define X509V3_R_UNKNOWN_BIT_STRING_ARGUMENT 111
+# define X509V3_R_UNKNOWN_EXTENSION 129
+# define X509V3_R_UNKNOWN_EXTENSION_NAME 130
+# define X509V3_R_UNKNOWN_OPTION 120
+# define X509V3_R_UNSUPPORTED_OPTION 117
+# define X509V3_R_UNSUPPORTED_TYPE 167
+# define X509V3_R_USER_TOO_LONG 132
+
+#endif
diff --git a/include/rapidjson/allocators.h b/include/rapidjson/allocators.h
new file mode 100644
index 00000000..98affe03
--- /dev/null
+++ b/include/rapidjson/allocators.h
@@ -0,0 +1,271 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_ALLOCATORS_H_
+#define RAPIDJSON_ALLOCATORS_H_
+
+#include "rapidjson.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+///////////////////////////////////////////////////////////////////////////////
+// Allocator
+
+/*! \class rapidjson::Allocator
+ \brief Concept for allocating, resizing and freeing memory block.
+
+ Note that Malloc() and Realloc() are non-static but Free() is static.
+
+ So if an allocator need to support Free(), it needs to put its pointer in
+ the header of memory block.
+
+\code
+concept Allocator {
+ static const bool kNeedFree; //!< Whether this allocator needs to call Free().
+
+ // Allocate a memory block.
+ // \param size of the memory block in bytes.
+ // \returns pointer to the memory block.
+ void* Malloc(size_t size);
+
+ // Resize a memory block.
+ // \param originalPtr The pointer to current memory block. Null pointer is permitted.
+ // \param originalSize The current size in bytes. (Design issue: since some allocator may not book-keep this, explicitly pass to it can save memory.)
+ // \param newSize the new size in bytes.
+ void* Realloc(void* originalPtr, size_t originalSize, size_t newSize);
+
+ // Free a memory block.
+ // \param pointer to the memory block. Null pointer is permitted.
+ static void Free(void *ptr);
+};
+\endcode
+*/
+
+///////////////////////////////////////////////////////////////////////////////
+// CrtAllocator
+
+//! C-runtime library allocator.
+/*! This class is just wrapper for standard C library memory routines.
+ \note implements Allocator concept
+*/
+class CrtAllocator {
+public:
+ static const bool kNeedFree = true;
+ void* Malloc(size_t size) {
+ if (size) // behavior of malloc(0) is implementation defined.
+ return std::malloc(size);
+ else
+ return NULL; // standardize to returning NULL.
+ }
+ void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
+ (void)originalSize;
+ if (newSize == 0) {
+ std::free(originalPtr);
+ return NULL;
+ }
+ return std::realloc(originalPtr, newSize);
+ }
+ static void Free(void *ptr) { std::free(ptr); }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// MemoryPoolAllocator
+
+//! Default memory allocator used by the parser and DOM.
+/*! This allocator allocate memory blocks from pre-allocated memory chunks.
+
+ It does not free memory blocks. And Realloc() only allocate new memory.
+
+ The memory chunks are allocated by BaseAllocator, which is CrtAllocator by default.
+
+ User may also supply a buffer as the first chunk.
+
+ If the user-buffer is full then additional chunks are allocated by BaseAllocator.
+
+ The user-buffer is not deallocated by this allocator.
+
+ \tparam BaseAllocator the allocator type for allocating memory chunks. Default is CrtAllocator.
+ \note implements Allocator concept
+*/
+template <typename BaseAllocator = CrtAllocator>
+class MemoryPoolAllocator {
+public:
+ static const bool kNeedFree = false; //!< Tell users that no need to call Free() with this allocator. (concept Allocator)
+
+ //! Constructor with chunkSize.
+ /*! \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
+ \param baseAllocator The allocator for allocating memory chunks.
+ */
+ MemoryPoolAllocator(size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
+ chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(0), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
+ {
+ }
+
+ //! Constructor with user-supplied buffer.
+ /*! The user buffer will be used firstly. When it is full, memory pool allocates new chunk with chunk size.
+
+ The user buffer will not be deallocated when this allocator is destructed.
+
+ \param buffer User supplied buffer.
+ \param size Size of the buffer in bytes. It must at least larger than sizeof(ChunkHeader).
+ \param chunkSize The size of memory chunk. The default is kDefaultChunkSize.
+ \param baseAllocator The allocator for allocating memory chunks.
+ */
+ MemoryPoolAllocator(void *buffer, size_t size, size_t chunkSize = kDefaultChunkCapacity, BaseAllocator* baseAllocator = 0) :
+ chunkHead_(0), chunk_capacity_(chunkSize), userBuffer_(buffer), baseAllocator_(baseAllocator), ownBaseAllocator_(0)
+ {
+ RAPIDJSON_ASSERT(buffer != 0);
+ RAPIDJSON_ASSERT(size > sizeof(ChunkHeader));
+ chunkHead_ = reinterpret_cast<ChunkHeader*>(buffer);
+ chunkHead_->capacity = size - sizeof(ChunkHeader);
+ chunkHead_->size = 0;
+ chunkHead_->next = 0;
+ }
+
+ //! Destructor.
+ /*! This deallocates all memory chunks, excluding the user-supplied buffer.
+ */
+ ~MemoryPoolAllocator() {
+ Clear();
+ RAPIDJSON_DELETE(ownBaseAllocator_);
+ }
+
+ //! Deallocates all memory chunks, excluding the user-supplied buffer.
+ void Clear() {
+ while (chunkHead_ && chunkHead_ != userBuffer_) {
+ ChunkHeader* next = chunkHead_->next;
+ baseAllocator_->Free(chunkHead_);
+ chunkHead_ = next;
+ }
+ if (chunkHead_ && chunkHead_ == userBuffer_)
+ chunkHead_->size = 0; // Clear user buffer
+ }
+
+ //! Computes the total capacity of allocated memory chunks.
+ /*! \return total capacity in bytes.
+ */
+ size_t Capacity() const {
+ size_t capacity = 0;
+ for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
+ capacity += c->capacity;
+ return capacity;
+ }
+
+ //! Computes the memory blocks allocated.
+ /*! \return total used bytes.
+ */
+ size_t Size() const {
+ size_t size = 0;
+ for (ChunkHeader* c = chunkHead_; c != 0; c = c->next)
+ size += c->size;
+ return size;
+ }
+
+ //! Allocates a memory block. (concept Allocator)
+ void* Malloc(size_t size) {
+ if (!size)
+ return NULL;
+
+ size = RAPIDJSON_ALIGN(size);
+ if (chunkHead_ == 0 || chunkHead_->size + size > chunkHead_->capacity)
+ if (!AddChunk(chunk_capacity_ > size ? chunk_capacity_ : size))
+ return NULL;
+
+ void *buffer = reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size;
+ chunkHead_->size += size;
+ return buffer;
+ }
+
+ //! Resizes a memory block (concept Allocator)
+ void* Realloc(void* originalPtr, size_t originalSize, size_t newSize) {
+ if (originalPtr == 0)
+ return Malloc(newSize);
+
+ if (newSize == 0)
+ return NULL;
+
+ originalSize = RAPIDJSON_ALIGN(originalSize);
+ newSize = RAPIDJSON_ALIGN(newSize);
+
+ // Do not shrink if new size is smaller than original
+ if (originalSize >= newSize)
+ return originalPtr;
+
+ // Simply expand it if it is the last allocation and there is sufficient space
+ if (originalPtr == reinterpret_cast<char *>(chunkHead_) + RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + chunkHead_->size - originalSize) {
+ size_t increment = static_cast<size_t>(newSize - originalSize);
+ if (chunkHead_->size + increment <= chunkHead_->capacity) {
+ chunkHead_->size += increment;
+ return originalPtr;
+ }
+ }
+
+ // Realloc process: allocate and copy memory, do not free original buffer.
+ if (void* newBuffer = Malloc(newSize)) {
+ if (originalSize)
+ std::memcpy(newBuffer, originalPtr, originalSize);
+ return newBuffer;
+ }
+ else
+ return NULL;
+ }
+
+ //! Frees a memory block (concept Allocator)
+ static void Free(void *ptr) { (void)ptr; } // Do nothing
+
+private:
+ //! Copy constructor is not permitted.
+ MemoryPoolAllocator(const MemoryPoolAllocator& rhs) /* = delete */;
+ //! Copy assignment operator is not permitted.
+ MemoryPoolAllocator& operator=(const MemoryPoolAllocator& rhs) /* = delete */;
+
+ //! Creates a new chunk.
+ /*! \param capacity Capacity of the chunk in bytes.
+ \return true if success.
+ */
+ bool AddChunk(size_t capacity) {
+ if (!baseAllocator_)
+ ownBaseAllocator_ = baseAllocator_ = RAPIDJSON_NEW(BaseAllocator());
+ if (ChunkHeader* chunk = reinterpret_cast<ChunkHeader*>(baseAllocator_->Malloc(RAPIDJSON_ALIGN(sizeof(ChunkHeader)) + capacity))) {
+ chunk->capacity = capacity;
+ chunk->size = 0;
+ chunk->next = chunkHead_;
+ chunkHead_ = chunk;
+ return true;
+ }
+ else
+ return false;
+ }
+
+ static const int kDefaultChunkCapacity = 64 * 1024; //!< Default chunk capacity.
+
+ //! Chunk header for perpending to each chunk.
+ /*! Chunks are stored as a singly linked list.
+ */
+ struct ChunkHeader {
+ size_t capacity; //!< Capacity of the chunk in bytes (excluding the header itself).
+ size_t size; //!< Current size of allocated memory in bytes.
+ ChunkHeader *next; //!< Next chunk in the linked list.
+ };
+
+ ChunkHeader *chunkHead_; //!< Head of the chunk linked-list. Only the head chunk serves allocation.
+ size_t chunk_capacity_; //!< The minimum capacity of chunk when they are allocated.
+ void *userBuffer_; //!< User supplied buffer.
+ BaseAllocator* baseAllocator_; //!< base allocator for allocating memory chunks.
+ BaseAllocator* ownBaseAllocator_; //!< base allocator created by this object.
+};
+
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_ENCODINGS_H_
diff --git a/include/rapidjson/document.h b/include/rapidjson/document.h
new file mode 100644
index 00000000..e3e20dfb
--- /dev/null
+++ b/include/rapidjson/document.h
@@ -0,0 +1,2575 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_DOCUMENT_H_
+#define RAPIDJSON_DOCUMENT_H_
+
+/*! \file document.h */
+
+#include "reader.h"
+#include "internal/meta.h"
+#include "internal/strfunc.h"
+#include "memorystream.h"
+#include "encodedstream.h"
+#include <new> // placement new
+#include <limits>
+
+RAPIDJSON_DIAG_PUSH
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
+RAPIDJSON_DIAG_OFF(4244) // conversion from kXxxFlags to 'uint16_t', possible loss of data
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_OFF(padded)
+RAPIDJSON_DIAG_OFF(switch-enum)
+RAPIDJSON_DIAG_OFF(c++98-compat)
+#endif
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_OFF(effc++)
+#if __GNUC__ >= 6
+RAPIDJSON_DIAG_OFF(terminate) // ignore throwing RAPIDJSON_ASSERT in RAPIDJSON_NOEXCEPT functions
+#endif
+#endif // __GNUC__
+
+#ifndef RAPIDJSON_NOMEMBERITERATORCLASS
+#include <iterator> // std::iterator, std::random_access_iterator_tag
+#endif
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+#include <utility> // std::move
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+// Forward declaration.
+template <typename Encoding, typename Allocator>
+class GenericValue;
+
+template <typename Encoding, typename Allocator, typename StackAllocator>
+class GenericDocument;
+
+//! Name-value pair in a JSON object value.
+/*!
+ This class was internal to GenericValue. It used to be a inner struct.
+ But a compiler (IBM XL C/C++ for AIX) have reported to have problem with that so it moved as a namespace scope struct.
+ https://code.google.com/p/rapidjson/issues/detail?id=64
+*/
+template <typename Encoding, typename Allocator>
+struct GenericMember {
+ GenericValue<Encoding, Allocator> name; //!< name of member (must be a string)
+ GenericValue<Encoding, Allocator> value; //!< value of member.
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericMemberIterator
+
+#ifndef RAPIDJSON_NOMEMBERITERATORCLASS
+
+//! (Constant) member iterator for a JSON object value
+/*!
+ \tparam Const Is this a constant iterator?
+ \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
+ \tparam Allocator Allocator type for allocating memory of object, array and string.
+
+ This class implements a Random Access Iterator for GenericMember elements
+ of a GenericValue, see ISO/IEC 14882:2003(E) C++ standard, 24.1 [lib.iterator.requirements].
+
+ \note This iterator implementation is mainly intended to avoid implicit
+ conversions from iterator values to \c NULL,
+ e.g. from GenericValue::FindMember.
+
+ \note Define \c RAPIDJSON_NOMEMBERITERATORCLASS to fall back to a
+ pointer-based implementation, if your platform doesn't provide
+ the C++ <iterator> header.
+
+ \see GenericMember, GenericValue::MemberIterator, GenericValue::ConstMemberIterator
+ */
+template <bool Const, typename Encoding, typename Allocator>
+class GenericMemberIterator
+ : public std::iterator<std::random_access_iterator_tag
+ , typename internal::MaybeAddConst<Const,GenericMember<Encoding,Allocator> >::Type> {
+
+ friend class GenericValue<Encoding,Allocator>;
+ template <bool, typename, typename> friend class GenericMemberIterator;
+
+ typedef GenericMember<Encoding,Allocator> PlainType;
+ typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
+ typedef std::iterator<std::random_access_iterator_tag,ValueType> BaseType;
+
+public:
+ //! Iterator type itself
+ typedef GenericMemberIterator Iterator;
+ //! Constant iterator type
+ typedef GenericMemberIterator<true,Encoding,Allocator> ConstIterator;
+ //! Non-constant iterator type
+ typedef GenericMemberIterator<false,Encoding,Allocator> NonConstIterator;
+
+ //! Pointer to (const) GenericMember
+ typedef typename BaseType::pointer Pointer;
+ //! Reference to (const) GenericMember
+ typedef typename BaseType::reference Reference;
+ //! Signed integer type (e.g. \c ptrdiff_t)
+ typedef typename BaseType::difference_type DifferenceType;
+
+ //! Default constructor (singular value)
+ /*! Creates an iterator pointing to no element.
+ \note All operations, except for comparisons, are undefined on such values.
+ */
+ GenericMemberIterator() : ptr_() {}
+
+ //! Iterator conversions to more const
+ /*!
+ \param it (Non-const) iterator to copy from
+
+ Allows the creation of an iterator from another GenericMemberIterator
+ that is "less const". Especially, creating a non-constant iterator
+ from a constant iterator are disabled:
+ \li const -> non-const (not ok)
+ \li const -> const (ok)
+ \li non-const -> const (ok)
+ \li non-const -> non-const (ok)
+
+ \note If the \c Const template parameter is already \c false, this
+ constructor effectively defines a regular copy-constructor.
+ Otherwise, the copy constructor is implicitly defined.
+ */
+ GenericMemberIterator(const NonConstIterator & it) : ptr_(it.ptr_) {}
+ Iterator& operator=(const NonConstIterator & it) { ptr_ = it.ptr_; return *this; }
+
+ //! @name stepping
+ //@{
+ Iterator& operator++(){ ++ptr_; return *this; }
+ Iterator& operator--(){ --ptr_; return *this; }
+ Iterator operator++(int){ Iterator old(*this); ++ptr_; return old; }
+ Iterator operator--(int){ Iterator old(*this); --ptr_; return old; }
+ //@}
+
+ //! @name increment/decrement
+ //@{
+ Iterator operator+(DifferenceType n) const { return Iterator(ptr_+n); }
+ Iterator operator-(DifferenceType n) const { return Iterator(ptr_-n); }
+
+ Iterator& operator+=(DifferenceType n) { ptr_+=n; return *this; }
+ Iterator& operator-=(DifferenceType n) { ptr_-=n; return *this; }
+ //@}
+
+ //! @name relations
+ //@{
+ bool operator==(ConstIterator that) const { return ptr_ == that.ptr_; }
+ bool operator!=(ConstIterator that) const { return ptr_ != that.ptr_; }
+ bool operator<=(ConstIterator that) const { return ptr_ <= that.ptr_; }
+ bool operator>=(ConstIterator that) const { return ptr_ >= that.ptr_; }
+ bool operator< (ConstIterator that) const { return ptr_ < that.ptr_; }
+ bool operator> (ConstIterator that) const { return ptr_ > that.ptr_; }
+ //@}
+
+ //! @name dereference
+ //@{
+ Reference operator*() const { return *ptr_; }
+ Pointer operator->() const { return ptr_; }
+ Reference operator[](DifferenceType n) const { return ptr_[n]; }
+ //@}
+
+ //! Distance
+ DifferenceType operator-(ConstIterator that) const { return ptr_-that.ptr_; }
+
+private:
+ //! Internal constructor from plain pointer
+ explicit GenericMemberIterator(Pointer p) : ptr_(p) {}
+
+ Pointer ptr_; //!< raw pointer
+};
+
+#else // RAPIDJSON_NOMEMBERITERATORCLASS
+
+// class-based member iterator implementation disabled, use plain pointers
+
+template <bool Const, typename Encoding, typename Allocator>
+struct GenericMemberIterator;
+
+//! non-const GenericMemberIterator
+template <typename Encoding, typename Allocator>
+struct GenericMemberIterator<false,Encoding,Allocator> {
+ //! use plain pointer as iterator type
+ typedef GenericMember<Encoding,Allocator>* Iterator;
+};
+//! const GenericMemberIterator
+template <typename Encoding, typename Allocator>
+struct GenericMemberIterator<true,Encoding,Allocator> {
+ //! use plain const pointer as iterator type
+ typedef const GenericMember<Encoding,Allocator>* Iterator;
+};
+
+#endif // RAPIDJSON_NOMEMBERITERATORCLASS
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericStringRef
+
+//! Reference to a constant string (not taking a copy)
+/*!
+ \tparam CharType character type of the string
+
+ This helper class is used to automatically infer constant string
+ references for string literals, especially from \c const \b (!)
+ character arrays.
+
+ The main use is for creating JSON string values without copying the
+ source string via an \ref Allocator. This requires that the referenced
+ string pointers have a sufficient lifetime, which exceeds the lifetime
+ of the associated GenericValue.
+
+ \b Example
+ \code
+ Value v("foo"); // ok, no need to copy & calculate length
+ const char foo[] = "foo";
+ v.SetString(foo); // ok
+
+ const char* bar = foo;
+ // Value x(bar); // not ok, can't rely on bar's lifetime
+ Value x(StringRef(bar)); // lifetime explicitly guaranteed by user
+ Value y(StringRef(bar, 3)); // ok, explicitly pass length
+ \endcode
+
+ \see StringRef, GenericValue::SetString
+*/
+template<typename CharType>
+struct GenericStringRef {
+ typedef CharType Ch; //!< character type of the string
+
+ //! Create string reference from \c const character array
+#ifndef __clang__ // -Wdocumentation
+ /*!
+ This constructor implicitly creates a constant string reference from
+ a \c const character array. It has better performance than
+ \ref StringRef(const CharType*) by inferring the string \ref length
+ from the array length, and also supports strings containing null
+ characters.
+
+ \tparam N length of the string, automatically inferred
+
+ \param str Constant character array, lifetime assumed to be longer
+ than the use of the string in e.g. a GenericValue
+
+ \post \ref s == str
+
+ \note Constant complexity.
+ \note There is a hidden, private overload to disallow references to
+ non-const character arrays to be created via this constructor.
+ By this, e.g. function-scope arrays used to be filled via
+ \c snprintf are excluded from consideration.
+ In such cases, the referenced string should be \b copied to the
+ GenericValue instead.
+ */
+#endif
+ template<SizeType N>
+ GenericStringRef(const CharType (&str)[N]) RAPIDJSON_NOEXCEPT
+ : s(str), length(N-1) {}
+
+ //! Explicitly create string reference from \c const character pointer
+#ifndef __clang__ // -Wdocumentation
+ /*!
+ This constructor can be used to \b explicitly create a reference to
+ a constant string pointer.
+
+ \see StringRef(const CharType*)
+
+ \param str Constant character pointer, lifetime assumed to be longer
+ than the use of the string in e.g. a GenericValue
+
+ \post \ref s == str
+
+ \note There is a hidden, private overload to disallow references to
+ non-const character arrays to be created via this constructor.
+ By this, e.g. function-scope arrays used to be filled via
+ \c snprintf are excluded from consideration.
+ In such cases, the referenced string should be \b copied to the
+ GenericValue instead.
+ */
+#endif
+ explicit GenericStringRef(const CharType* str)
+ : s(str), length(internal::StrLen(str)){ RAPIDJSON_ASSERT(s != 0); }
+
+ //! Create constant string reference from pointer and length
+#ifndef __clang__ // -Wdocumentation
+ /*! \param str constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
+ \param len length of the string, excluding the trailing NULL terminator
+
+ \post \ref s == str && \ref length == len
+ \note Constant complexity.
+ */
+#endif
+ GenericStringRef(const CharType* str, SizeType len)
+ : s(str), length(len) { RAPIDJSON_ASSERT(s != 0); }
+
+ GenericStringRef(const GenericStringRef& rhs) : s(rhs.s), length(rhs.length) {}
+
+ GenericStringRef& operator=(const GenericStringRef& rhs) { s = rhs.s; length = rhs.length; }
+
+ //! implicit conversion to plain CharType pointer
+ operator const Ch *() const { return s; }
+
+ const Ch* const s; //!< plain CharType pointer
+ const SizeType length; //!< length of the string (excluding the trailing NULL terminator)
+
+private:
+ //! Disallow construction from non-const array
+ template<SizeType N>
+ GenericStringRef(CharType (&str)[N]) /* = delete */;
+};
+
+//! Mark a character pointer as constant string
+/*! Mark a plain character pointer as a "string literal". This function
+ can be used to avoid copying a character string to be referenced as a
+ value in a JSON GenericValue object, if the string's lifetime is known
+ to be valid long enough.
+ \tparam CharType Character type of the string
+ \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
+ \return GenericStringRef string reference object
+ \relatesalso GenericStringRef
+
+ \see GenericValue::GenericValue(StringRefType), GenericValue::operator=(StringRefType), GenericValue::SetString(StringRefType), GenericValue::PushBack(StringRefType, Allocator&), GenericValue::AddMember
+*/
+template<typename CharType>
+inline GenericStringRef<CharType> StringRef(const CharType* str) {
+ return GenericStringRef<CharType>(str, internal::StrLen(str));
+}
+
+//! Mark a character pointer as constant string
+/*! Mark a plain character pointer as a "string literal". This function
+ can be used to avoid copying a character string to be referenced as a
+ value in a JSON GenericValue object, if the string's lifetime is known
+ to be valid long enough.
+
+ This version has better performance with supplied length, and also
+ supports string containing null characters.
+
+ \tparam CharType character type of the string
+ \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
+ \param length The length of source string.
+ \return GenericStringRef string reference object
+ \relatesalso GenericStringRef
+*/
+template<typename CharType>
+inline GenericStringRef<CharType> StringRef(const CharType* str, size_t length) {
+ return GenericStringRef<CharType>(str, SizeType(length));
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+//! Mark a string object as constant string
+/*! Mark a string object (e.g. \c std::string) as a "string literal".
+ This function can be used to avoid copying a string to be referenced as a
+ value in a JSON GenericValue object, if the string's lifetime is known
+ to be valid long enough.
+
+ \tparam CharType character type of the string
+ \param str Constant string, lifetime assumed to be longer than the use of the string in e.g. a GenericValue
+ \return GenericStringRef string reference object
+ \relatesalso GenericStringRef
+ \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
+*/
+template<typename CharType>
+inline GenericStringRef<CharType> StringRef(const std::basic_string<CharType>& str) {
+ return GenericStringRef<CharType>(str.data(), SizeType(str.size()));
+}
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericValue type traits
+namespace internal {
+
+template <typename T, typename Encoding = void, typename Allocator = void>
+struct IsGenericValueImpl : FalseType {};
+
+// select candidates according to nested encoding and allocator types
+template <typename T> struct IsGenericValueImpl<T, typename Void<typename T::EncodingType>::Type, typename Void<typename T::AllocatorType>::Type>
+ : IsBaseOf<GenericValue<typename T::EncodingType, typename T::AllocatorType>, T>::Type {};
+
+// helper to match arbitrary GenericValue instantiations, including derived classes
+template <typename T> struct IsGenericValue : IsGenericValueImpl<T>::Type {};
+
+} // namespace internal
+
+///////////////////////////////////////////////////////////////////////////////
+// TypeHelper
+
+namespace internal {
+
+template <typename ValueType, typename T>
+struct TypeHelper {};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, bool> {
+ static bool Is(const ValueType& v) { return v.IsBool(); }
+ static bool Get(const ValueType& v) { return v.GetBool(); }
+ static ValueType& Set(ValueType& v, bool data) { return v.SetBool(data); }
+ static ValueType& Set(ValueType& v, bool data, typename ValueType::AllocatorType&) { return v.SetBool(data); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, int> {
+ static bool Is(const ValueType& v) { return v.IsInt(); }
+ static int Get(const ValueType& v) { return v.GetInt(); }
+ static ValueType& Set(ValueType& v, int data) { return v.SetInt(data); }
+ static ValueType& Set(ValueType& v, int data, typename ValueType::AllocatorType&) { return v.SetInt(data); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, unsigned> {
+ static bool Is(const ValueType& v) { return v.IsUint(); }
+ static unsigned Get(const ValueType& v) { return v.GetUint(); }
+ static ValueType& Set(ValueType& v, unsigned data) { return v.SetUint(data); }
+ static ValueType& Set(ValueType& v, unsigned data, typename ValueType::AllocatorType&) { return v.SetUint(data); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, int64_t> {
+ static bool Is(const ValueType& v) { return v.IsInt64(); }
+ static int64_t Get(const ValueType& v) { return v.GetInt64(); }
+ static ValueType& Set(ValueType& v, int64_t data) { return v.SetInt64(data); }
+ static ValueType& Set(ValueType& v, int64_t data, typename ValueType::AllocatorType&) { return v.SetInt64(data); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, uint64_t> {
+ static bool Is(const ValueType& v) { return v.IsUint64(); }
+ static uint64_t Get(const ValueType& v) { return v.GetUint64(); }
+ static ValueType& Set(ValueType& v, uint64_t data) { return v.SetUint64(data); }
+ static ValueType& Set(ValueType& v, uint64_t data, typename ValueType::AllocatorType&) { return v.SetUint64(data); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, double> {
+ static bool Is(const ValueType& v) { return v.IsDouble(); }
+ static double Get(const ValueType& v) { return v.GetDouble(); }
+ static ValueType& Set(ValueType& v, double data) { return v.SetDouble(data); }
+ static ValueType& Set(ValueType& v, double data, typename ValueType::AllocatorType&) { return v.SetDouble(data); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, float> {
+ static bool Is(const ValueType& v) { return v.IsFloat(); }
+ static float Get(const ValueType& v) { return v.GetFloat(); }
+ static ValueType& Set(ValueType& v, float data) { return v.SetFloat(data); }
+ static ValueType& Set(ValueType& v, float data, typename ValueType::AllocatorType&) { return v.SetFloat(data); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, const typename ValueType::Ch*> {
+ typedef const typename ValueType::Ch* StringType;
+ static bool Is(const ValueType& v) { return v.IsString(); }
+ static StringType Get(const ValueType& v) { return v.GetString(); }
+ static ValueType& Set(ValueType& v, const StringType data) { return v.SetString(typename ValueType::StringRefType(data)); }
+ static ValueType& Set(ValueType& v, const StringType data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }
+};
+
+#if RAPIDJSON_HAS_STDSTRING
+template<typename ValueType>
+struct TypeHelper<ValueType, std::basic_string<typename ValueType::Ch> > {
+ typedef std::basic_string<typename ValueType::Ch> StringType;
+ static bool Is(const ValueType& v) { return v.IsString(); }
+ static StringType Get(const ValueType& v) { return StringType(v.GetString(), v.GetStringLength()); }
+ static ValueType& Set(ValueType& v, const StringType& data, typename ValueType::AllocatorType& a) { return v.SetString(data, a); }
+};
+#endif
+
+template<typename ValueType>
+struct TypeHelper<ValueType, typename ValueType::Array> {
+ typedef typename ValueType::Array ArrayType;
+ static bool Is(const ValueType& v) { return v.IsArray(); }
+ static ArrayType Get(ValueType& v) { return v.GetArray(); }
+ static ValueType& Set(ValueType& v, ArrayType data) { return v = data; }
+ static ValueType& Set(ValueType& v, ArrayType data, typename ValueType::AllocatorType&) { return v = data; }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, typename ValueType::ConstArray> {
+ typedef typename ValueType::ConstArray ArrayType;
+ static bool Is(const ValueType& v) { return v.IsArray(); }
+ static ArrayType Get(const ValueType& v) { return v.GetArray(); }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, typename ValueType::Object> {
+ typedef typename ValueType::Object ObjectType;
+ static bool Is(const ValueType& v) { return v.IsObject(); }
+ static ObjectType Get(ValueType& v) { return v.GetObject(); }
+ static ValueType& Set(ValueType& v, ObjectType data) { return v = data; }
+ static ValueType& Set(ValueType& v, ObjectType data, typename ValueType::AllocatorType&) { v = data; }
+};
+
+template<typename ValueType>
+struct TypeHelper<ValueType, typename ValueType::ConstObject> {
+ typedef typename ValueType::ConstObject ObjectType;
+ static bool Is(const ValueType& v) { return v.IsObject(); }
+ static ObjectType Get(const ValueType& v) { return v.GetObject(); }
+};
+
+} // namespace internal
+
+// Forward declarations
+template <bool, typename> class GenericArray;
+template <bool, typename> class GenericObject;
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericValue
+
+//! Represents a JSON value. Use Value for UTF8 encoding and default allocator.
+/*!
+ A JSON value can be one of 7 types. This class is a variant type supporting
+ these types.
+
+ Use the Value if UTF8 and default allocator
+
+ \tparam Encoding Encoding of the value. (Even non-string values need to have the same encoding in a document)
+ \tparam Allocator Allocator type for allocating memory of object, array and string.
+*/
+template <typename Encoding, typename Allocator = MemoryPoolAllocator<> >
+class GenericValue {
+public:
+ //! Name-value pair in an object.
+ typedef GenericMember<Encoding, Allocator> Member;
+ typedef Encoding EncodingType; //!< Encoding type from template parameter.
+ typedef Allocator AllocatorType; //!< Allocator type from template parameter.
+ typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
+ typedef GenericStringRef<Ch> StringRefType; //!< Reference to a constant string
+ typedef typename GenericMemberIterator<false,Encoding,Allocator>::Iterator MemberIterator; //!< Member iterator for iterating in object.
+ typedef typename GenericMemberIterator<true,Encoding,Allocator>::Iterator ConstMemberIterator; //!< Constant member iterator for iterating in object.
+ typedef GenericValue* ValueIterator; //!< Value iterator for iterating in array.
+ typedef const GenericValue* ConstValueIterator; //!< Constant value iterator for iterating in array.
+ typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of itself.
+ typedef GenericArray<false, ValueType> Array;
+ typedef GenericArray<true, ValueType> ConstArray;
+ typedef GenericObject<false, ValueType> Object;
+ typedef GenericObject<true, ValueType> ConstObject;
+
+ //!@name Constructors and destructor.
+ //@{
+
+ //! Default constructor creates a null value.
+ GenericValue() RAPIDJSON_NOEXCEPT : data_() { data_.f.flags = kNullFlag; }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ //! Move constructor in C++11
+ GenericValue(GenericValue&& rhs) RAPIDJSON_NOEXCEPT : data_(rhs.data_) {
+ rhs.data_.f.flags = kNullFlag; // give up contents
+ }
+#endif
+
+private:
+ //! Copy constructor is not permitted.
+ GenericValue(const GenericValue& rhs);
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ //! Moving from a GenericDocument is not permitted.
+ template <typename StackAllocator>
+ GenericValue(GenericDocument<Encoding,Allocator,StackAllocator>&& rhs);
+
+ //! Move assignment from a GenericDocument is not permitted.
+ template <typename StackAllocator>
+ GenericValue& operator=(GenericDocument<Encoding,Allocator,StackAllocator>&& rhs);
+#endif
+
+public:
+
+ //! Constructor with JSON value type.
+ /*! This creates a Value of specified type with default content.
+ \param type Type of the value.
+ \note Default content for number is zero.
+ */
+ explicit GenericValue(Type type) RAPIDJSON_NOEXCEPT : data_() {
+ static const uint16_t defaultFlags[7] = {
+ kNullFlag, kFalseFlag, kTrueFlag, kObjectFlag, kArrayFlag, kShortStringFlag,
+ kNumberAnyFlag
+ };
+ RAPIDJSON_ASSERT(type <= kNumberType);
+ data_.f.flags = defaultFlags[type];
+
+ // Use ShortString to store empty string.
+ if (type == kStringType)
+ data_.ss.SetLength(0);
+ }
+
+ //! Explicit copy constructor (with allocator)
+ /*! Creates a copy of a Value by using the given Allocator
+ \tparam SourceAllocator allocator of \c rhs
+ \param rhs Value to copy from (read-only)
+ \param allocator Allocator for allocating copied elements and buffers. Commonly use GenericDocument::GetAllocator().
+ \see CopyFrom()
+ */
+ template< typename SourceAllocator >
+ GenericValue(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator & allocator);
+
+ //! Constructor for boolean value.
+ /*! \param b Boolean value
+ \note This constructor is limited to \em real boolean values and rejects
+ implicitly converted types like arbitrary pointers. Use an explicit cast
+ to \c bool, if you want to construct a boolean JSON value in such cases.
+ */
+#ifndef RAPIDJSON_DOXYGEN_RUNNING // hide SFINAE from Doxygen
+ template <typename T>
+ explicit GenericValue(T b, RAPIDJSON_ENABLEIF((internal::IsSame<bool, T>))) RAPIDJSON_NOEXCEPT // See #472
+#else
+ explicit GenericValue(bool b) RAPIDJSON_NOEXCEPT
+#endif
+ : data_() {
+ // safe-guard against failing SFINAE
+ RAPIDJSON_STATIC_ASSERT((internal::IsSame<bool,T>::Value));
+ data_.f.flags = b ? kTrueFlag : kFalseFlag;
+ }
+
+ //! Constructor for int value.
+ explicit GenericValue(int i) RAPIDJSON_NOEXCEPT : data_() {
+ data_.n.i64 = i;
+ data_.f.flags = (i >= 0) ? (kNumberIntFlag | kUintFlag | kUint64Flag) : kNumberIntFlag;
+ }
+
+ //! Constructor for unsigned value.
+ explicit GenericValue(unsigned u) RAPIDJSON_NOEXCEPT : data_() {
+ data_.n.u64 = u;
+ data_.f.flags = (u & 0x80000000) ? kNumberUintFlag : (kNumberUintFlag | kIntFlag | kInt64Flag);
+ }
+
+ //! Constructor for int64_t value.
+ explicit GenericValue(int64_t i64) RAPIDJSON_NOEXCEPT : data_() {
+ data_.n.i64 = i64;
+ data_.f.flags = kNumberInt64Flag;
+ if (i64 >= 0) {
+ data_.f.flags |= kNumberUint64Flag;
+ if (!(static_cast<uint64_t>(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
+ data_.f.flags |= kUintFlag;
+ if (!(static_cast<uint64_t>(i64) & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
+ data_.f.flags |= kIntFlag;
+ }
+ else if (i64 >= static_cast<int64_t>(RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
+ data_.f.flags |= kIntFlag;
+ }
+
+ //! Constructor for uint64_t value.
+ explicit GenericValue(uint64_t u64) RAPIDJSON_NOEXCEPT : data_() {
+ data_.n.u64 = u64;
+ data_.f.flags = kNumberUint64Flag;
+ if (!(u64 & RAPIDJSON_UINT64_C2(0x80000000, 0x00000000)))
+ data_.f.flags |= kInt64Flag;
+ if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x00000000)))
+ data_.f.flags |= kUintFlag;
+ if (!(u64 & RAPIDJSON_UINT64_C2(0xFFFFFFFF, 0x80000000)))
+ data_.f.flags |= kIntFlag;
+ }
+
+ //! Constructor for double value.
+ explicit GenericValue(double d) RAPIDJSON_NOEXCEPT : data_() { data_.n.d = d; data_.f.flags = kNumberDoubleFlag; }
+
+ //! Constructor for constant string (i.e. do not make a copy of string)
+ GenericValue(const Ch* s, SizeType length) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(StringRef(s, length)); }
+
+ //! Constructor for constant string (i.e. do not make a copy of string)
+ explicit GenericValue(StringRefType s) RAPIDJSON_NOEXCEPT : data_() { SetStringRaw(s); }
+
+ //! Constructor for copy-string (i.e. do make a copy of string)
+ GenericValue(const Ch* s, SizeType length, Allocator& allocator) : data_() { SetStringRaw(StringRef(s, length), allocator); }
+
+ //! Constructor for copy-string (i.e. do make a copy of string)
+ GenericValue(const Ch*s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Constructor for copy-string from a string object (i.e. do make a copy of string)
+ /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
+ */
+ GenericValue(const std::basic_string<Ch>& s, Allocator& allocator) : data_() { SetStringRaw(StringRef(s), allocator); }
+#endif
+
+ //! Constructor for Array.
+ /*!
+ \param a An array obtained by \c GetArray().
+ \note \c Array is always pass-by-value.
+ \note the source array is moved into this value and the sourec array becomes empty.
+ */
+ GenericValue(Array a) RAPIDJSON_NOEXCEPT : data_(a.value_.data_) {
+ a.value_.data_ = Data();
+ a.value_.data_.f.flags = kArrayFlag;
+ }
+
+ //! Constructor for Object.
+ /*!
+ \param o An object obtained by \c GetObject().
+ \note \c Object is always pass-by-value.
+ \note the source object is moved into this value and the sourec object becomes empty.
+ */
+ GenericValue(Object o) RAPIDJSON_NOEXCEPT : data_(o.value_.data_) {
+ o.value_.data_ = Data();
+ o.value_.data_.f.flags = kObjectFlag;
+ }
+
+ //! Destructor.
+ /*! Need to destruct elements of array, members of object, or copy-string.
+ */
+ ~GenericValue() {
+ if (Allocator::kNeedFree) { // Shortcut by Allocator's trait
+ switch(data_.f.flags) {
+ case kArrayFlag:
+ {
+ GenericValue* e = GetElementsPointer();
+ for (GenericValue* v = e; v != e + data_.a.size; ++v)
+ v->~GenericValue();
+ Allocator::Free(e);
+ }
+ break;
+
+ case kObjectFlag:
+ for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
+ m->~Member();
+ Allocator::Free(GetMembersPointer());
+ break;
+
+ case kCopyStringFlag:
+ Allocator::Free(const_cast<Ch*>(GetStringPointer()));
+ break;
+
+ default:
+ break; // Do nothing for other types.
+ }
+ }
+ }
+
+ //@}
+
+ //!@name Assignment operators
+ //@{
+
+ //! Assignment with move semantics.
+ /*! \param rhs Source of the assignment. It will become a null value after assignment.
+ */
+ GenericValue& operator=(GenericValue& rhs) RAPIDJSON_NOEXCEPT {
+ RAPIDJSON_ASSERT(this != &rhs);
+ this->~GenericValue();
+ RawAssign(rhs);
+ return *this;
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ //! Move assignment in C++11
+ GenericValue& operator=(GenericValue&& rhs) RAPIDJSON_NOEXCEPT {
+ return *this = rhs.Move();
+ }
+#endif
+
+ //! Assignment of constant string reference (no copy)
+ /*! \param str Constant string reference to be assigned
+ \note This overload is needed to avoid clashes with the generic primitive type assignment overload below.
+ \see GenericStringRef, operator=(T)
+ */
+ GenericValue& operator=(StringRefType str) RAPIDJSON_NOEXCEPT {
+ GenericValue s(str);
+ return *this = s;
+ }
+
+ //! Assignment with primitive types.
+ /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
+ \param value The value to be assigned.
+
+ \note The source type \c T explicitly disallows all pointer types,
+ especially (\c const) \ref Ch*. This helps avoiding implicitly
+ referencing character strings with insufficient lifetime, use
+ \ref SetString(const Ch*, Allocator&) (for copying) or
+ \ref StringRef() (to explicitly mark the pointer as constant) instead.
+ All other pointer types would implicitly convert to \c bool,
+ use \ref SetBool() instead.
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::IsPointer<T>), (GenericValue&))
+ operator=(T value) {
+ GenericValue v(value);
+ return *this = v;
+ }
+
+ //! Deep-copy assignment from Value
+ /*! Assigns a \b copy of the Value to the current Value object
+ \tparam SourceAllocator Allocator type of \c rhs
+ \param rhs Value to copy from (read-only)
+ \param allocator Allocator to use for copying
+ */
+ template <typename SourceAllocator>
+ GenericValue& CopyFrom(const GenericValue<Encoding, SourceAllocator>& rhs, Allocator& allocator) {
+ RAPIDJSON_ASSERT(static_cast<void*>(this) != static_cast<void const*>(&rhs));
+ this->~GenericValue();
+ new (this) GenericValue(rhs, allocator);
+ return *this;
+ }
+
+ //! Exchange the contents of this value with those of other.
+ /*!
+ \param other Another value.
+ \note Constant complexity.
+ */
+ GenericValue& Swap(GenericValue& other) RAPIDJSON_NOEXCEPT {
+ GenericValue temp;
+ temp.RawAssign(*this);
+ RawAssign(other);
+ other.RawAssign(temp);
+ return *this;
+ }
+
+ //! free-standing swap function helper
+ /*!
+ Helper function to enable support for common swap implementation pattern based on \c std::swap:
+ \code
+ void swap(MyClass& a, MyClass& b) {
+ using std::swap;
+ swap(a.value, b.value);
+ // ...
+ }
+ \endcode
+ \see Swap()
+ */
+ friend inline void swap(GenericValue& a, GenericValue& b) RAPIDJSON_NOEXCEPT { a.Swap(b); }
+
+ //! Prepare Value for move semantics
+ /*! \return *this */
+ GenericValue& Move() RAPIDJSON_NOEXCEPT { return *this; }
+ //@}
+
+ //!@name Equal-to and not-equal-to operators
+ //@{
+ //! Equal-to operator
+ /*!
+ \note If an object contains duplicated named member, comparing equality with any object is always \c false.
+ \note Linear time complexity (number of all values in the subtree and total lengths of all strings).
+ */
+ template <typename SourceAllocator>
+ bool operator==(const GenericValue<Encoding, SourceAllocator>& rhs) const {
+ typedef GenericValue<Encoding, SourceAllocator> RhsType;
+ if (GetType() != rhs.GetType())
+ return false;
+
+ switch (GetType()) {
+ case kObjectType: // Warning: O(n^2) inner-loop
+ if (data_.o.size != rhs.data_.o.size)
+ return false;
+ for (ConstMemberIterator lhsMemberItr = MemberBegin(); lhsMemberItr != MemberEnd(); ++lhsMemberItr) {
+ typename RhsType::ConstMemberIterator rhsMemberItr = rhs.FindMember(lhsMemberItr->name);
+ if (rhsMemberItr == rhs.MemberEnd() || lhsMemberItr->value != rhsMemberItr->value)
+ return false;
+ }
+ return true;
+
+ case kArrayType:
+ if (data_.a.size != rhs.data_.a.size)
+ return false;
+ for (SizeType i = 0; i < data_.a.size; i++)
+ if ((*this)[i] != rhs[i])
+ return false;
+ return true;
+
+ case kStringType:
+ return StringEqual(rhs);
+
+ case kNumberType:
+ if (IsDouble() || rhs.IsDouble()) {
+ double a = GetDouble(); // May convert from integer to double.
+ double b = rhs.GetDouble(); // Ditto
+ return a >= b && a <= b; // Prevent -Wfloat-equal
+ }
+ else
+ return data_.n.u64 == rhs.data_.n.u64;
+
+ default:
+ return true;
+ }
+ }
+
+ //! Equal-to operator with const C-string pointer
+ bool operator==(const Ch* rhs) const { return *this == GenericValue(StringRef(rhs)); }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Equal-to operator with string object
+ /*! \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
+ */
+ bool operator==(const std::basic_string<Ch>& rhs) const { return *this == GenericValue(StringRef(rhs)); }
+#endif
+
+ //! Equal-to operator with primitive types
+ /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c true, \c false
+ */
+ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>,internal::IsGenericValue<T> >), (bool)) operator==(const T& rhs) const { return *this == GenericValue(rhs); }
+
+ //! Not-equal-to operator
+ /*! \return !(*this == rhs)
+ */
+ template <typename SourceAllocator>
+ bool operator!=(const GenericValue<Encoding, SourceAllocator>& rhs) const { return !(*this == rhs); }
+
+ //! Not-equal-to operator with const C-string pointer
+ bool operator!=(const Ch* rhs) const { return !(*this == rhs); }
+
+ //! Not-equal-to operator with arbitrary types
+ /*! \return !(*this == rhs)
+ */
+ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& rhs) const { return !(*this == rhs); }
+
+ //! Equal-to operator with arbitrary types (symmetric version)
+ /*! \return (rhs == lhs)
+ */
+ template <typename T> friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator==(const T& lhs, const GenericValue& rhs) { return rhs == lhs; }
+
+ //! Not-Equal-to operator with arbitrary types (symmetric version)
+ /*! \return !(rhs == lhs)
+ */
+ template <typename T> friend RAPIDJSON_DISABLEIF_RETURN((internal::IsGenericValue<T>), (bool)) operator!=(const T& lhs, const GenericValue& rhs) { return !(rhs == lhs); }
+ //@}
+
+ //!@name Type
+ //@{
+
+ Type GetType() const { return static_cast<Type>(data_.f.flags & kTypeMask); }
+ bool IsNull() const { return data_.f.flags == kNullFlag; }
+ bool IsFalse() const { return data_.f.flags == kFalseFlag; }
+ bool IsTrue() const { return data_.f.flags == kTrueFlag; }
+ bool IsBool() const { return (data_.f.flags & kBoolFlag) != 0; }
+ bool IsObject() const { return data_.f.flags == kObjectFlag; }
+ bool IsArray() const { return data_.f.flags == kArrayFlag; }
+ bool IsNumber() const { return (data_.f.flags & kNumberFlag) != 0; }
+ bool IsInt() const { return (data_.f.flags & kIntFlag) != 0; }
+ bool IsUint() const { return (data_.f.flags & kUintFlag) != 0; }
+ bool IsInt64() const { return (data_.f.flags & kInt64Flag) != 0; }
+ bool IsUint64() const { return (data_.f.flags & kUint64Flag) != 0; }
+ bool IsDouble() const { return (data_.f.flags & kDoubleFlag) != 0; }
+ bool IsString() const { return (data_.f.flags & kStringFlag) != 0; }
+
+ // Checks whether a number can be losslessly converted to a double.
+ bool IsLosslessDouble() const {
+ if (!IsNumber()) return false;
+ if (IsUint64()) {
+ uint64_t u = GetUint64();
+ volatile double d = static_cast<double>(u);
+ return (d >= 0.0)
+ && (d < static_cast<double>(std::numeric_limits<uint64_t>::max()))
+ && (u == static_cast<uint64_t>(d));
+ }
+ if (IsInt64()) {
+ int64_t i = GetInt64();
+ volatile double d = static_cast<double>(i);
+ return (d >= static_cast<double>(std::numeric_limits<int64_t>::min()))
+ && (d < static_cast<double>(std::numeric_limits<int64_t>::max()))
+ && (i == static_cast<int64_t>(d));
+ }
+ return true; // double, int, uint are always lossless
+ }
+
+ // Checks whether a number is a float (possible lossy).
+ bool IsFloat() const {
+ if ((data_.f.flags & kDoubleFlag) == 0)
+ return false;
+ double d = GetDouble();
+ return d >= -3.4028234e38 && d <= 3.4028234e38;
+ }
+ // Checks whether a number can be losslessly converted to a float.
+ bool IsLosslessFloat() const {
+ if (!IsNumber()) return false;
+ double a = GetDouble();
+ if (a < static_cast<double>(-std::numeric_limits<float>::max())
+ || a > static_cast<double>(std::numeric_limits<float>::max()))
+ return false;
+ double b = static_cast<double>(static_cast<float>(a));
+ return a >= b && a <= b; // Prevent -Wfloat-equal
+ }
+
+ //@}
+
+ //!@name Null
+ //@{
+
+ GenericValue& SetNull() { this->~GenericValue(); new (this) GenericValue(); return *this; }
+
+ //@}
+
+ //!@name Bool
+ //@{
+
+ bool GetBool() const { RAPIDJSON_ASSERT(IsBool()); return data_.f.flags == kTrueFlag; }
+ //!< Set boolean value
+ /*! \post IsBool() == true */
+ GenericValue& SetBool(bool b) { this->~GenericValue(); new (this) GenericValue(b); return *this; }
+
+ //@}
+
+ //!@name Object
+ //@{
+
+ //! Set this value as an empty object.
+ /*! \post IsObject() == true */
+ GenericValue& SetObject() { this->~GenericValue(); new (this) GenericValue(kObjectType); return *this; }
+
+ //! Get the number of members in the object.
+ SizeType MemberCount() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size; }
+
+ //! Check whether the object is empty.
+ bool ObjectEmpty() const { RAPIDJSON_ASSERT(IsObject()); return data_.o.size == 0; }
+
+ //! Get a value from an object associated with the name.
+ /*! \pre IsObject() == true
+ \tparam T Either \c Ch or \c const \c Ch (template used for disambiguation with \ref operator[](SizeType))
+ \note In version 0.1x, if the member is not found, this function returns a null value. This makes issue 7.
+ Since 0.2, if the name is not correct, it will assert.
+ If user is unsure whether a member exists, user should use HasMember() first.
+ A better approach is to use FindMember().
+ \note Linear time complexity.
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(GenericValue&)) operator[](T* name) {
+ GenericValue n(StringRef(name));
+ return (*this)[n];
+ }
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >),(const GenericValue&)) operator[](T* name) const { return const_cast<GenericValue&>(*this)[name]; }
+
+ //! Get a value from an object associated with the name.
+ /*! \pre IsObject() == true
+ \tparam SourceAllocator Allocator of the \c name value
+
+ \note Compared to \ref operator[](T*), this version is faster because it does not need a StrLen().
+ And it can also handle strings with embedded null characters.
+
+ \note Linear time complexity.
+ */
+ template <typename SourceAllocator>
+ GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) {
+ MemberIterator member = FindMember(name);
+ if (member != MemberEnd())
+ return member->value;
+ else {
+ RAPIDJSON_ASSERT(false); // see above note
+
+ // This will generate -Wexit-time-destructors in clang
+ // static GenericValue NullValue;
+ // return NullValue;
+
+ // Use static buffer and placement-new to prevent destruction
+ static char buffer[sizeof(GenericValue)];
+ return *new (buffer) GenericValue();
+ }
+ }
+ template <typename SourceAllocator>
+ const GenericValue& operator[](const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this)[name]; }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Get a value from an object associated with name (string object).
+ GenericValue& operator[](const std::basic_string<Ch>& name) { return (*this)[GenericValue(StringRef(name))]; }
+ const GenericValue& operator[](const std::basic_string<Ch>& name) const { return (*this)[GenericValue(StringRef(name))]; }
+#endif
+
+ //! Const member iterator
+ /*! \pre IsObject() == true */
+ ConstMemberIterator MemberBegin() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer()); }
+ //! Const \em past-the-end member iterator
+ /*! \pre IsObject() == true */
+ ConstMemberIterator MemberEnd() const { RAPIDJSON_ASSERT(IsObject()); return ConstMemberIterator(GetMembersPointer() + data_.o.size); }
+ //! Member iterator
+ /*! \pre IsObject() == true */
+ MemberIterator MemberBegin() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer()); }
+ //! \em Past-the-end member iterator
+ /*! \pre IsObject() == true */
+ MemberIterator MemberEnd() { RAPIDJSON_ASSERT(IsObject()); return MemberIterator(GetMembersPointer() + data_.o.size); }
+
+ //! Check whether a member exists in the object.
+ /*!
+ \param name Member name to be searched.
+ \pre IsObject() == true
+ \return Whether a member with that name exists.
+ \note It is better to use FindMember() directly if you need the obtain the value as well.
+ \note Linear time complexity.
+ */
+ bool HasMember(const Ch* name) const { return FindMember(name) != MemberEnd(); }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Check whether a member exists in the object with string object.
+ /*!
+ \param name Member name to be searched.
+ \pre IsObject() == true
+ \return Whether a member with that name exists.
+ \note It is better to use FindMember() directly if you need the obtain the value as well.
+ \note Linear time complexity.
+ */
+ bool HasMember(const std::basic_string<Ch>& name) const { return FindMember(name) != MemberEnd(); }
+#endif
+
+ //! Check whether a member exists in the object with GenericValue name.
+ /*!
+ This version is faster because it does not need a StrLen(). It can also handle string with null character.
+ \param name Member name to be searched.
+ \pre IsObject() == true
+ \return Whether a member with that name exists.
+ \note It is better to use FindMember() directly if you need the obtain the value as well.
+ \note Linear time complexity.
+ */
+ template <typename SourceAllocator>
+ bool HasMember(const GenericValue<Encoding, SourceAllocator>& name) const { return FindMember(name) != MemberEnd(); }
+
+ //! Find member by name.
+ /*!
+ \param name Member name to be searched.
+ \pre IsObject() == true
+ \return Iterator to member, if it exists.
+ Otherwise returns \ref MemberEnd().
+
+ \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
+ the requested member doesn't exist. For consistency with e.g.
+ \c std::map, this has been changed to MemberEnd() now.
+ \note Linear time complexity.
+ */
+ MemberIterator FindMember(const Ch* name) {
+ GenericValue n(StringRef(name));
+ return FindMember(n);
+ }
+
+ ConstMemberIterator FindMember(const Ch* name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
+
+ //! Find member by name.
+ /*!
+ This version is faster because it does not need a StrLen(). It can also handle string with null character.
+ \param name Member name to be searched.
+ \pre IsObject() == true
+ \return Iterator to member, if it exists.
+ Otherwise returns \ref MemberEnd().
+
+ \note Earlier versions of Rapidjson returned a \c NULL pointer, in case
+ the requested member doesn't exist. For consistency with e.g.
+ \c std::map, this has been changed to MemberEnd() now.
+ \note Linear time complexity.
+ */
+ template <typename SourceAllocator>
+ MemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) {
+ RAPIDJSON_ASSERT(IsObject());
+ RAPIDJSON_ASSERT(name.IsString());
+ MemberIterator member = MemberBegin();
+ for ( ; member != MemberEnd(); ++member)
+ if (name.StringEqual(member->name))
+ break;
+ return member;
+ }
+ template <typename SourceAllocator> ConstMemberIterator FindMember(const GenericValue<Encoding, SourceAllocator>& name) const { return const_cast<GenericValue&>(*this).FindMember(name); }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Find member by string object name.
+ /*!
+ \param name Member name to be searched.
+ \pre IsObject() == true
+ \return Iterator to member, if it exists.
+ Otherwise returns \ref MemberEnd().
+ */
+ MemberIterator FindMember(const std::basic_string<Ch>& name) { return FindMember(GenericValue(StringRef(name))); }
+ ConstMemberIterator FindMember(const std::basic_string<Ch>& name) const { return FindMember(GenericValue(StringRef(name))); }
+#endif
+
+ //! Add a member (name-value pair) to the object.
+ /*! \param name A string value as name of member.
+ \param value Value of any type.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \note The ownership of \c name and \c value will be transferred to this object on success.
+ \pre IsObject() && name.IsString()
+ \post name.IsNull() && value.IsNull()
+ \note Amortized Constant time complexity.
+ */
+ GenericValue& AddMember(GenericValue& name, GenericValue& value, Allocator& allocator) {
+ RAPIDJSON_ASSERT(IsObject());
+ RAPIDJSON_ASSERT(name.IsString());
+
+ ObjectData& o = data_.o;
+ if (o.size >= o.capacity) {
+ if (o.capacity == 0) {
+ o.capacity = kDefaultObjectCapacity;
+ SetMembersPointer(reinterpret_cast<Member*>(allocator.Malloc(o.capacity * sizeof(Member))));
+ }
+ else {
+ SizeType oldCapacity = o.capacity;
+ o.capacity += (oldCapacity + 1) / 2; // grow by factor 1.5
+ SetMembersPointer(reinterpret_cast<Member*>(allocator.Realloc(GetMembersPointer(), oldCapacity * sizeof(Member), o.capacity * sizeof(Member))));
+ }
+ }
+ Member* members = GetMembersPointer();
+ members[o.size].name.RawAssign(name);
+ members[o.size].value.RawAssign(value);
+ o.size++;
+ return *this;
+ }
+
+ //! Add a constant string value as member (name-value pair) to the object.
+ /*! \param name A string value as name of member.
+ \param value constant string reference as value of member.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \pre IsObject()
+ \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below.
+ \note Amortized Constant time complexity.
+ */
+ GenericValue& AddMember(GenericValue& name, StringRefType value, Allocator& allocator) {
+ GenericValue v(value);
+ return AddMember(name, v, allocator);
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Add a string object as member (name-value pair) to the object.
+ /*! \param name A string value as name of member.
+ \param value constant string reference as value of member.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \pre IsObject()
+ \note This overload is needed to avoid clashes with the generic primitive type AddMember(GenericValue&,T,Allocator&) overload below.
+ \note Amortized Constant time complexity.
+ */
+ GenericValue& AddMember(GenericValue& name, std::basic_string<Ch>& value, Allocator& allocator) {
+ GenericValue v(value, allocator);
+ return AddMember(name, v, allocator);
+ }
+#endif
+
+ //! Add any primitive value as member (name-value pair) to the object.
+ /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
+ \param name A string value as name of member.
+ \param value Value of primitive type \c T as value of member
+ \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \pre IsObject()
+
+ \note The source type \c T explicitly disallows all pointer types,
+ especially (\c const) \ref Ch*. This helps avoiding implicitly
+ referencing character strings with insufficient lifetime, use
+ \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
+ AddMember(StringRefType, StringRefType, Allocator&).
+ All other pointer types would implicitly convert to \c bool,
+ use an explicit cast instead, if needed.
+ \note Amortized Constant time complexity.
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
+ AddMember(GenericValue& name, T value, Allocator& allocator) {
+ GenericValue v(value);
+ return AddMember(name, v, allocator);
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ GenericValue& AddMember(GenericValue&& name, GenericValue&& value, Allocator& allocator) {
+ return AddMember(name, value, allocator);
+ }
+ GenericValue& AddMember(GenericValue&& name, GenericValue& value, Allocator& allocator) {
+ return AddMember(name, value, allocator);
+ }
+ GenericValue& AddMember(GenericValue& name, GenericValue&& value, Allocator& allocator) {
+ return AddMember(name, value, allocator);
+ }
+ GenericValue& AddMember(StringRefType name, GenericValue&& value, Allocator& allocator) {
+ GenericValue n(name);
+ return AddMember(n, value, allocator);
+ }
+#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
+
+
+ //! Add a member (name-value pair) to the object.
+ /*! \param name A constant string reference as name of member.
+ \param value Value of any type.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \note The ownership of \c value will be transferred to this object on success.
+ \pre IsObject()
+ \post value.IsNull()
+ \note Amortized Constant time complexity.
+ */
+ GenericValue& AddMember(StringRefType name, GenericValue& value, Allocator& allocator) {
+ GenericValue n(name);
+ return AddMember(n, value, allocator);
+ }
+
+ //! Add a constant string value as member (name-value pair) to the object.
+ /*! \param name A constant string reference as name of member.
+ \param value constant string reference as value of member.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \pre IsObject()
+ \note This overload is needed to avoid clashes with the generic primitive type AddMember(StringRefType,T,Allocator&) overload below.
+ \note Amortized Constant time complexity.
+ */
+ GenericValue& AddMember(StringRefType name, StringRefType value, Allocator& allocator) {
+ GenericValue v(value);
+ return AddMember(name, v, allocator);
+ }
+
+ //! Add any primitive value as member (name-value pair) to the object.
+ /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
+ \param name A constant string reference as name of member.
+ \param value Value of primitive type \c T as value of member
+ \param allocator Allocator for reallocating memory. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \pre IsObject()
+
+ \note The source type \c T explicitly disallows all pointer types,
+ especially (\c const) \ref Ch*. This helps avoiding implicitly
+ referencing character strings with insufficient lifetime, use
+ \ref AddMember(StringRefType, GenericValue&, Allocator&) or \ref
+ AddMember(StringRefType, StringRefType, Allocator&).
+ All other pointer types would implicitly convert to \c bool,
+ use an explicit cast instead, if needed.
+ \note Amortized Constant time complexity.
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
+ AddMember(StringRefType name, T value, Allocator& allocator) {
+ GenericValue n(name);
+ return AddMember(n, value, allocator);
+ }
+
+ //! Remove all members in the object.
+ /*! This function do not deallocate memory in the object, i.e. the capacity is unchanged.
+ \note Linear time complexity.
+ */
+ void RemoveAllMembers() {
+ RAPIDJSON_ASSERT(IsObject());
+ for (MemberIterator m = MemberBegin(); m != MemberEnd(); ++m)
+ m->~Member();
+ data_.o.size = 0;
+ }
+
+ //! Remove a member in object by its name.
+ /*! \param name Name of member to be removed.
+ \return Whether the member existed.
+ \note This function may reorder the object members. Use \ref
+ EraseMember(ConstMemberIterator) if you need to preserve the
+ relative order of the remaining members.
+ \note Linear time complexity.
+ */
+ bool RemoveMember(const Ch* name) {
+ GenericValue n(StringRef(name));
+ return RemoveMember(n);
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ bool RemoveMember(const std::basic_string<Ch>& name) { return RemoveMember(GenericValue(StringRef(name))); }
+#endif
+
+ template <typename SourceAllocator>
+ bool RemoveMember(const GenericValue<Encoding, SourceAllocator>& name) {
+ MemberIterator m = FindMember(name);
+ if (m != MemberEnd()) {
+ RemoveMember(m);
+ return true;
+ }
+ else
+ return false;
+ }
+
+ //! Remove a member in object by iterator.
+ /*! \param m member iterator (obtained by FindMember() or MemberBegin()).
+ \return the new iterator after removal.
+ \note This function may reorder the object members. Use \ref
+ EraseMember(ConstMemberIterator) if you need to preserve the
+ relative order of the remaining members.
+ \note Constant time complexity.
+ */
+ MemberIterator RemoveMember(MemberIterator m) {
+ RAPIDJSON_ASSERT(IsObject());
+ RAPIDJSON_ASSERT(data_.o.size > 0);
+ RAPIDJSON_ASSERT(GetMembersPointer() != 0);
+ RAPIDJSON_ASSERT(m >= MemberBegin() && m < MemberEnd());
+
+ MemberIterator last(GetMembersPointer() + (data_.o.size - 1));
+ if (data_.o.size > 1 && m != last)
+ *m = *last; // Move the last one to this place
+ else
+ m->~Member(); // Only one left, just destroy
+ --data_.o.size;
+ return m;
+ }
+
+ //! Remove a member from an object by iterator.
+ /*! \param pos iterator to the member to remove
+ \pre IsObject() == true && \ref MemberBegin() <= \c pos < \ref MemberEnd()
+ \return Iterator following the removed element.
+ If the iterator \c pos refers to the last element, the \ref MemberEnd() iterator is returned.
+ \note This function preserves the relative order of the remaining object
+ members. If you do not need this, use the more efficient \ref RemoveMember(MemberIterator).
+ \note Linear time complexity.
+ */
+ MemberIterator EraseMember(ConstMemberIterator pos) {
+ return EraseMember(pos, pos +1);
+ }
+
+ //! Remove members in the range [first, last) from an object.
+ /*! \param first iterator to the first member to remove
+ \param last iterator following the last member to remove
+ \pre IsObject() == true && \ref MemberBegin() <= \c first <= \c last <= \ref MemberEnd()
+ \return Iterator following the last removed element.
+ \note This function preserves the relative order of the remaining object
+ members.
+ \note Linear time complexity.
+ */
+ MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) {
+ RAPIDJSON_ASSERT(IsObject());
+ RAPIDJSON_ASSERT(data_.o.size > 0);
+ RAPIDJSON_ASSERT(GetMembersPointer() != 0);
+ RAPIDJSON_ASSERT(first >= MemberBegin());
+ RAPIDJSON_ASSERT(first <= last);
+ RAPIDJSON_ASSERT(last <= MemberEnd());
+
+ MemberIterator pos = MemberBegin() + (first - MemberBegin());
+ for (MemberIterator itr = pos; itr != last; ++itr)
+ itr->~Member();
+ std::memmove(&*pos, &*last, static_cast<size_t>(MemberEnd() - last) * sizeof(Member));
+ data_.o.size -= static_cast<SizeType>(last - first);
+ return pos;
+ }
+
+ //! Erase a member in object by its name.
+ /*! \param name Name of member to be removed.
+ \return Whether the member existed.
+ \note Linear time complexity.
+ */
+ bool EraseMember(const Ch* name) {
+ GenericValue n(StringRef(name));
+ return EraseMember(n);
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ bool EraseMember(const std::basic_string<Ch>& name) { return EraseMember(GenericValue(StringRef(name))); }
+#endif
+
+ template <typename SourceAllocator>
+ bool EraseMember(const GenericValue<Encoding, SourceAllocator>& name) {
+ MemberIterator m = FindMember(name);
+ if (m != MemberEnd()) {
+ EraseMember(m);
+ return true;
+ }
+ else
+ return false;
+ }
+
+ Object GetObject() { RAPIDJSON_ASSERT(IsObject()); return Object(*this); }
+ ConstObject GetObject() const { RAPIDJSON_ASSERT(IsObject()); return ConstObject(*this); }
+
+ //@}
+
+ //!@name Array
+ //@{
+
+ //! Set this value as an empty array.
+ /*! \post IsArray == true */
+ GenericValue& SetArray() { this->~GenericValue(); new (this) GenericValue(kArrayType); return *this; }
+
+ //! Get the number of elements in array.
+ SizeType Size() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size; }
+
+ //! Get the capacity of array.
+ SizeType Capacity() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.capacity; }
+
+ //! Check whether the array is empty.
+ bool Empty() const { RAPIDJSON_ASSERT(IsArray()); return data_.a.size == 0; }
+
+ //! Remove all elements in the array.
+ /*! This function do not deallocate memory in the array, i.e. the capacity is unchanged.
+ \note Linear time complexity.
+ */
+ void Clear() {
+ RAPIDJSON_ASSERT(IsArray());
+ GenericValue* e = GetElementsPointer();
+ for (GenericValue* v = e; v != e + data_.a.size; ++v)
+ v->~GenericValue();
+ data_.a.size = 0;
+ }
+
+ //! Get an element from array by index.
+ /*! \pre IsArray() == true
+ \param index Zero-based index of element.
+ \see operator[](T*)
+ */
+ GenericValue& operator[](SizeType index) {
+ RAPIDJSON_ASSERT(IsArray());
+ RAPIDJSON_ASSERT(index < data_.a.size);
+ return GetElementsPointer()[index];
+ }
+ const GenericValue& operator[](SizeType index) const { return const_cast<GenericValue&>(*this)[index]; }
+
+ //! Element iterator
+ /*! \pre IsArray() == true */
+ ValueIterator Begin() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer(); }
+ //! \em Past-the-end element iterator
+ /*! \pre IsArray() == true */
+ ValueIterator End() { RAPIDJSON_ASSERT(IsArray()); return GetElementsPointer() + data_.a.size; }
+ //! Constant element iterator
+ /*! \pre IsArray() == true */
+ ConstValueIterator Begin() const { return const_cast<GenericValue&>(*this).Begin(); }
+ //! Constant \em past-the-end element iterator
+ /*! \pre IsArray() == true */
+ ConstValueIterator End() const { return const_cast<GenericValue&>(*this).End(); }
+
+ //! Request the array to have enough capacity to store elements.
+ /*! \param newCapacity The capacity that the array at least need to have.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \note Linear time complexity.
+ */
+ GenericValue& Reserve(SizeType newCapacity, Allocator &allocator) {
+ RAPIDJSON_ASSERT(IsArray());
+ if (newCapacity > data_.a.capacity) {
+ SetElementsPointer(reinterpret_cast<GenericValue*>(allocator.Realloc(GetElementsPointer(), data_.a.capacity * sizeof(GenericValue), newCapacity * sizeof(GenericValue))));
+ data_.a.capacity = newCapacity;
+ }
+ return *this;
+ }
+
+ //! Append a GenericValue at the end of the array.
+ /*! \param value Value to be appended.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \pre IsArray() == true
+ \post value.IsNull() == true
+ \return The value itself for fluent API.
+ \note The ownership of \c value will be transferred to this array on success.
+ \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
+ \note Amortized constant time complexity.
+ */
+ GenericValue& PushBack(GenericValue& value, Allocator& allocator) {
+ RAPIDJSON_ASSERT(IsArray());
+ if (data_.a.size >= data_.a.capacity)
+ Reserve(data_.a.capacity == 0 ? kDefaultArrayCapacity : (data_.a.capacity + (data_.a.capacity + 1) / 2), allocator);
+ GetElementsPointer()[data_.a.size++].RawAssign(value);
+ return *this;
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ GenericValue& PushBack(GenericValue&& value, Allocator& allocator) {
+ return PushBack(value, allocator);
+ }
+#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
+
+ //! Append a constant string reference at the end of the array.
+ /*! \param value Constant string reference to be appended.
+ \param allocator Allocator for reallocating memory. It must be the same one used previously. Commonly use GenericDocument::GetAllocator().
+ \pre IsArray() == true
+ \return The value itself for fluent API.
+ \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
+ \note Amortized constant time complexity.
+ \see GenericStringRef
+ */
+ GenericValue& PushBack(StringRefType value, Allocator& allocator) {
+ return (*this).template PushBack<StringRefType>(value, allocator);
+ }
+
+ //! Append a primitive value at the end of the array.
+ /*! \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t
+ \param value Value of primitive type T to be appended.
+ \param allocator Allocator for reallocating memory. It must be the same one as used before. Commonly use GenericDocument::GetAllocator().
+ \pre IsArray() == true
+ \return The value itself for fluent API.
+ \note If the number of elements to be appended is known, calls Reserve() once first may be more efficient.
+
+ \note The source type \c T explicitly disallows all pointer types,
+ especially (\c const) \ref Ch*. This helps avoiding implicitly
+ referencing character strings with insufficient lifetime, use
+ \ref PushBack(GenericValue&, Allocator&) or \ref
+ PushBack(StringRefType, Allocator&).
+ All other pointer types would implicitly convert to \c bool,
+ use an explicit cast instead, if needed.
+ \note Amortized constant time complexity.
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericValue&))
+ PushBack(T value, Allocator& allocator) {
+ GenericValue v(value);
+ return PushBack(v, allocator);
+ }
+
+ //! Remove the last element in the array.
+ /*!
+ \note Constant time complexity.
+ */
+ GenericValue& PopBack() {
+ RAPIDJSON_ASSERT(IsArray());
+ RAPIDJSON_ASSERT(!Empty());
+ GetElementsPointer()[--data_.a.size].~GenericValue();
+ return *this;
+ }
+
+ //! Remove an element of array by iterator.
+ /*!
+ \param pos iterator to the element to remove
+ \pre IsArray() == true && \ref Begin() <= \c pos < \ref End()
+ \return Iterator following the removed element. If the iterator pos refers to the last element, the End() iterator is returned.
+ \note Linear time complexity.
+ */
+ ValueIterator Erase(ConstValueIterator pos) {
+ return Erase(pos, pos + 1);
+ }
+
+ //! Remove elements in the range [first, last) of the array.
+ /*!
+ \param first iterator to the first element to remove
+ \param last iterator following the last element to remove
+ \pre IsArray() == true && \ref Begin() <= \c first <= \c last <= \ref End()
+ \return Iterator following the last removed element.
+ \note Linear time complexity.
+ */
+ ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) {
+ RAPIDJSON_ASSERT(IsArray());
+ RAPIDJSON_ASSERT(data_.a.size > 0);
+ RAPIDJSON_ASSERT(GetElementsPointer() != 0);
+ RAPIDJSON_ASSERT(first >= Begin());
+ RAPIDJSON_ASSERT(first <= last);
+ RAPIDJSON_ASSERT(last <= End());
+ ValueIterator pos = Begin() + (first - Begin());
+ for (ValueIterator itr = pos; itr != last; ++itr)
+ itr->~GenericValue();
+ std::memmove(pos, last, static_cast<size_t>(End() - last) * sizeof(GenericValue));
+ data_.a.size -= static_cast<SizeType>(last - first);
+ return pos;
+ }
+
+ Array GetArray() { RAPIDJSON_ASSERT(IsArray()); return Array(*this); }
+ ConstArray GetArray() const { RAPIDJSON_ASSERT(IsArray()); return ConstArray(*this); }
+
+ //@}
+
+ //!@name Number
+ //@{
+
+ int GetInt() const { RAPIDJSON_ASSERT(data_.f.flags & kIntFlag); return data_.n.i.i; }
+ unsigned GetUint() const { RAPIDJSON_ASSERT(data_.f.flags & kUintFlag); return data_.n.u.u; }
+ int64_t GetInt64() const { RAPIDJSON_ASSERT(data_.f.flags & kInt64Flag); return data_.n.i64; }
+ uint64_t GetUint64() const { RAPIDJSON_ASSERT(data_.f.flags & kUint64Flag); return data_.n.u64; }
+
+ //! Get the value as double type.
+ /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessDouble() to check whether the converison is lossless.
+ */
+ double GetDouble() const {
+ RAPIDJSON_ASSERT(IsNumber());
+ if ((data_.f.flags & kDoubleFlag) != 0) return data_.n.d; // exact type, no conversion.
+ if ((data_.f.flags & kIntFlag) != 0) return data_.n.i.i; // int -> double
+ if ((data_.f.flags & kUintFlag) != 0) return data_.n.u.u; // unsigned -> double
+ if ((data_.f.flags & kInt64Flag) != 0) return static_cast<double>(data_.n.i64); // int64_t -> double (may lose precision)
+ RAPIDJSON_ASSERT((data_.f.flags & kUint64Flag) != 0); return static_cast<double>(data_.n.u64); // uint64_t -> double (may lose precision)
+ }
+
+ //! Get the value as float type.
+ /*! \note If the value is 64-bit integer type, it may lose precision. Use \c IsLosslessFloat() to check whether the converison is lossless.
+ */
+ float GetFloat() const {
+ return static_cast<float>(GetDouble());
+ }
+
+ GenericValue& SetInt(int i) { this->~GenericValue(); new (this) GenericValue(i); return *this; }
+ GenericValue& SetUint(unsigned u) { this->~GenericValue(); new (this) GenericValue(u); return *this; }
+ GenericValue& SetInt64(int64_t i64) { this->~GenericValue(); new (this) GenericValue(i64); return *this; }
+ GenericValue& SetUint64(uint64_t u64) { this->~GenericValue(); new (this) GenericValue(u64); return *this; }
+ GenericValue& SetDouble(double d) { this->~GenericValue(); new (this) GenericValue(d); return *this; }
+ GenericValue& SetFloat(float f) { this->~GenericValue(); new (this) GenericValue(f); return *this; }
+
+ //@}
+
+ //!@name String
+ //@{
+
+ const Ch* GetString() const { RAPIDJSON_ASSERT(IsString()); return (data_.f.flags & kInlineStrFlag) ? data_.ss.str : GetStringPointer(); }
+
+ //! Get the length of string.
+ /*! Since rapidjson permits "\\u0000" in the json string, strlen(v.GetString()) may not equal to v.GetStringLength().
+ */
+ SizeType GetStringLength() const { RAPIDJSON_ASSERT(IsString()); return ((data_.f.flags & kInlineStrFlag) ? (data_.ss.GetLength()) : data_.s.length); }
+
+ //! Set this value as a string without copying source string.
+ /*! This version has better performance with supplied length, and also support string containing null character.
+ \param s source string pointer.
+ \param length The length of source string, excluding the trailing null terminator.
+ \return The value itself for fluent API.
+ \post IsString() == true && GetString() == s && GetStringLength() == length
+ \see SetString(StringRefType)
+ */
+ GenericValue& SetString(const Ch* s, SizeType length) { return SetString(StringRef(s, length)); }
+
+ //! Set this value as a string without copying source string.
+ /*! \param s source string reference
+ \return The value itself for fluent API.
+ \post IsString() == true && GetString() == s && GetStringLength() == s.length
+ */
+ GenericValue& SetString(StringRefType s) { this->~GenericValue(); SetStringRaw(s); return *this; }
+
+ //! Set this value as a string by copying from source string.
+ /*! This version has better performance with supplied length, and also support string containing null character.
+ \param s source string.
+ \param length The length of source string, excluding the trailing null terminator.
+ \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
+ */
+ GenericValue& SetString(const Ch* s, SizeType length, Allocator& allocator) { this->~GenericValue(); SetStringRaw(StringRef(s, length), allocator); return *this; }
+
+ //! Set this value as a string by copying from source string.
+ /*! \param s source string.
+ \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \post IsString() == true && GetString() != s && strcmp(GetString(),s) == 0 && GetStringLength() == length
+ */
+ GenericValue& SetString(const Ch* s, Allocator& allocator) { return SetString(s, internal::StrLen(s), allocator); }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Set this value as a string by copying from source string.
+ /*! \param s source string.
+ \param allocator Allocator for allocating copied buffer. Commonly use GenericDocument::GetAllocator().
+ \return The value itself for fluent API.
+ \post IsString() == true && GetString() != s.data() && strcmp(GetString(),s.data() == 0 && GetStringLength() == s.size()
+ \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
+ */
+ GenericValue& SetString(const std::basic_string<Ch>& s, Allocator& allocator) { return SetString(s.data(), SizeType(s.size()), allocator); }
+#endif
+
+ //@}
+
+ //!@name Array
+ //@{
+
+ //! Templated version for checking whether this value is type T.
+ /*!
+ \tparam T Either \c bool, \c int, \c unsigned, \c int64_t, \c uint64_t, \c double, \c float, \c const \c char*, \c std::basic_string<Ch>
+ */
+ template <typename T>
+ bool Is() const { return internal::TypeHelper<ValueType, T>::Is(*this); }
+
+ template <typename T>
+ T Get() const { return internal::TypeHelper<ValueType, T>::Get(*this); }
+
+ template <typename T>
+ T Get() { return internal::TypeHelper<ValueType, T>::Get(*this); }
+
+ template<typename T>
+ ValueType& Set(const T& data) { return internal::TypeHelper<ValueType, T>::Set(*this, data); }
+
+ template<typename T>
+ ValueType& Set(const T& data, AllocatorType& allocator) { return internal::TypeHelper<ValueType, T>::Set(*this, data, allocator); }
+
+ //@}
+
+ //! Generate events of this value to a Handler.
+ /*! This function adopts the GoF visitor pattern.
+ Typical usage is to output this JSON value as JSON text via Writer, which is a Handler.
+ It can also be used to deep clone this value via GenericDocument, which is also a Handler.
+ \tparam Handler type of handler.
+ \param handler An object implementing concept Handler.
+ */
+ template <typename Handler>
+ bool Accept(Handler& handler) const {
+ switch(GetType()) {
+ case kNullType: return handler.Null();
+ case kFalseType: return handler.Bool(false);
+ case kTrueType: return handler.Bool(true);
+
+ case kObjectType:
+ if (RAPIDJSON_UNLIKELY(!handler.StartObject()))
+ return false;
+ for (ConstMemberIterator m = MemberBegin(); m != MemberEnd(); ++m) {
+ RAPIDJSON_ASSERT(m->name.IsString()); // User may change the type of name by MemberIterator.
+ if (RAPIDJSON_UNLIKELY(!handler.Key(m->name.GetString(), m->name.GetStringLength(), (m->name.data_.f.flags & kCopyFlag) != 0)))
+ return false;
+ if (RAPIDJSON_UNLIKELY(!m->value.Accept(handler)))
+ return false;
+ }
+ return handler.EndObject(data_.o.size);
+
+ case kArrayType:
+ if (RAPIDJSON_UNLIKELY(!handler.StartArray()))
+ return false;
+ for (const GenericValue* v = Begin(); v != End(); ++v)
+ if (RAPIDJSON_UNLIKELY(!v->Accept(handler)))
+ return false;
+ return handler.EndArray(data_.a.size);
+
+ case kStringType:
+ return handler.String(GetString(), GetStringLength(), (data_.f.flags & kCopyFlag) != 0);
+
+ default:
+ RAPIDJSON_ASSERT(GetType() == kNumberType);
+ if (IsDouble()) return handler.Double(data_.n.d);
+ else if (IsInt()) return handler.Int(data_.n.i.i);
+ else if (IsUint()) return handler.Uint(data_.n.u.u);
+ else if (IsInt64()) return handler.Int64(data_.n.i64);
+ else return handler.Uint64(data_.n.u64);
+ }
+ }
+
+private:
+ template <typename, typename> friend class GenericValue;
+ template <typename, typename, typename> friend class GenericDocument;
+
+ enum {
+ kBoolFlag = 0x0008,
+ kNumberFlag = 0x0010,
+ kIntFlag = 0x0020,
+ kUintFlag = 0x0040,
+ kInt64Flag = 0x0080,
+ kUint64Flag = 0x0100,
+ kDoubleFlag = 0x0200,
+ kStringFlag = 0x0400,
+ kCopyFlag = 0x0800,
+ kInlineStrFlag = 0x1000,
+
+ // Initial flags of different types.
+ kNullFlag = kNullType,
+ kTrueFlag = kTrueType | kBoolFlag,
+ kFalseFlag = kFalseType | kBoolFlag,
+ kNumberIntFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag,
+ kNumberUintFlag = kNumberType | kNumberFlag | kUintFlag | kUint64Flag | kInt64Flag,
+ kNumberInt64Flag = kNumberType | kNumberFlag | kInt64Flag,
+ kNumberUint64Flag = kNumberType | kNumberFlag | kUint64Flag,
+ kNumberDoubleFlag = kNumberType | kNumberFlag | kDoubleFlag,
+ kNumberAnyFlag = kNumberType | kNumberFlag | kIntFlag | kInt64Flag | kUintFlag | kUint64Flag | kDoubleFlag,
+ kConstStringFlag = kStringType | kStringFlag,
+ kCopyStringFlag = kStringType | kStringFlag | kCopyFlag,
+ kShortStringFlag = kStringType | kStringFlag | kCopyFlag | kInlineStrFlag,
+ kObjectFlag = kObjectType,
+ kArrayFlag = kArrayType,
+
+ kTypeMask = 0x07
+ };
+
+ static const SizeType kDefaultArrayCapacity = 16;
+ static const SizeType kDefaultObjectCapacity = 16;
+
+ struct Flag {
+#if RAPIDJSON_48BITPOINTER_OPTIMIZATION
+ char payload[sizeof(SizeType) * 2 + 6]; // 2 x SizeType + lower 48-bit pointer
+#elif RAPIDJSON_64BIT
+ char payload[sizeof(SizeType) * 2 + sizeof(void*) + 6]; // 6 padding bytes
+#else
+ char payload[sizeof(SizeType) * 2 + sizeof(void*) + 2]; // 2 padding bytes
+#endif
+ uint16_t flags;
+ };
+
+ struct String {
+ SizeType length;
+ SizeType hashcode; //!< reserved
+ const Ch* str;
+ }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
+
+ // implementation detail: ShortString can represent zero-terminated strings up to MaxSize chars
+ // (excluding the terminating zero) and store a value to determine the length of the contained
+ // string in the last character str[LenPos] by storing "MaxSize - length" there. If the string
+ // to store has the maximal length of MaxSize then str[LenPos] will be 0 and therefore act as
+ // the string terminator as well. For getting the string length back from that value just use
+ // "MaxSize - str[LenPos]".
+ // This allows to store 13-chars strings in 32-bit mode, 21-chars strings in 64-bit mode,
+ // 13-chars strings for RAPIDJSON_48BITPOINTER_OPTIMIZATION=1 inline (for `UTF8`-encoded strings).
+ struct ShortString {
+ enum { MaxChars = sizeof(static_cast<Flag*>(0)->payload) / sizeof(Ch), MaxSize = MaxChars - 1, LenPos = MaxSize };
+ Ch str[MaxChars];
+
+ inline static bool Usable(SizeType len) { return (MaxSize >= len); }
+ inline void SetLength(SizeType len) { str[LenPos] = static_cast<Ch>(MaxSize - len); }
+ inline SizeType GetLength() const { return static_cast<SizeType>(MaxSize - str[LenPos]); }
+ }; // at most as many bytes as "String" above => 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
+
+ // By using proper binary layout, retrieval of different integer types do not need conversions.
+ union Number {
+#if RAPIDJSON_ENDIAN == RAPIDJSON_LITTLEENDIAN
+ struct I {
+ int i;
+ char padding[4];
+ }i;
+ struct U {
+ unsigned u;
+ char padding2[4];
+ }u;
+#else
+ struct I {
+ char padding[4];
+ int i;
+ }i;
+ struct U {
+ char padding2[4];
+ unsigned u;
+ }u;
+#endif
+ int64_t i64;
+ uint64_t u64;
+ double d;
+ }; // 8 bytes
+
+ struct ObjectData {
+ SizeType size;
+ SizeType capacity;
+ Member* members;
+ }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
+
+ struct ArrayData {
+ SizeType size;
+ SizeType capacity;
+ GenericValue* elements;
+ }; // 12 bytes in 32-bit mode, 16 bytes in 64-bit mode
+
+ union Data {
+ String s;
+ ShortString ss;
+ Number n;
+ ObjectData o;
+ ArrayData a;
+ Flag f;
+ }; // 16 bytes in 32-bit mode, 24 bytes in 64-bit mode, 16 bytes in 64-bit with RAPIDJSON_48BITPOINTER_OPTIMIZATION
+
+ RAPIDJSON_FORCEINLINE const Ch* GetStringPointer() const { return RAPIDJSON_GETPOINTER(Ch, data_.s.str); }
+ RAPIDJSON_FORCEINLINE const Ch* SetStringPointer(const Ch* str) { return RAPIDJSON_SETPOINTER(Ch, data_.s.str, str); }
+ RAPIDJSON_FORCEINLINE GenericValue* GetElementsPointer() const { return RAPIDJSON_GETPOINTER(GenericValue, data_.a.elements); }
+ RAPIDJSON_FORCEINLINE GenericValue* SetElementsPointer(GenericValue* elements) { return RAPIDJSON_SETPOINTER(GenericValue, data_.a.elements, elements); }
+ RAPIDJSON_FORCEINLINE Member* GetMembersPointer() const { return RAPIDJSON_GETPOINTER(Member, data_.o.members); }
+ RAPIDJSON_FORCEINLINE Member* SetMembersPointer(Member* members) { return RAPIDJSON_SETPOINTER(Member, data_.o.members, members); }
+
+ // Initialize this value as array with initial data, without calling destructor.
+ void SetArrayRaw(GenericValue* values, SizeType count, Allocator& allocator) {
+ data_.f.flags = kArrayFlag;
+ if (count) {
+ GenericValue* e = static_cast<GenericValue*>(allocator.Malloc(count * sizeof(GenericValue)));
+ SetElementsPointer(e);
+ std::memcpy(e, values, count * sizeof(GenericValue));
+ }
+ else
+ SetElementsPointer(0);
+ data_.a.size = data_.a.capacity = count;
+ }
+
+ //! Initialize this value as object with initial data, without calling destructor.
+ void SetObjectRaw(Member* members, SizeType count, Allocator& allocator) {
+ data_.f.flags = kObjectFlag;
+ if (count) {
+ Member* m = static_cast<Member*>(allocator.Malloc(count * sizeof(Member)));
+ SetMembersPointer(m);
+ std::memcpy(m, members, count * sizeof(Member));
+ }
+ else
+ SetMembersPointer(0);
+ data_.o.size = data_.o.capacity = count;
+ }
+
+ //! Initialize this value as constant string, without calling destructor.
+ void SetStringRaw(StringRefType s) RAPIDJSON_NOEXCEPT {
+ data_.f.flags = kConstStringFlag;
+ SetStringPointer(s);
+ data_.s.length = s.length;
+ }
+
+ //! Initialize this value as copy string with initial data, without calling destructor.
+ void SetStringRaw(StringRefType s, Allocator& allocator) {
+ Ch* str = 0;
+ if (ShortString::Usable(s.length)) {
+ data_.f.flags = kShortStringFlag;
+ data_.ss.SetLength(s.length);
+ str = data_.ss.str;
+ } else {
+ data_.f.flags = kCopyStringFlag;
+ data_.s.length = s.length;
+ str = static_cast<Ch *>(allocator.Malloc((s.length + 1) * sizeof(Ch)));
+ SetStringPointer(str);
+ }
+ std::memcpy(str, s, s.length * sizeof(Ch));
+ str[s.length] = '\0';
+ }
+
+ //! Assignment without calling destructor
+ void RawAssign(GenericValue& rhs) RAPIDJSON_NOEXCEPT {
+ data_ = rhs.data_;
+ // data_.f.flags = rhs.data_.f.flags;
+ rhs.data_.f.flags = kNullFlag;
+ }
+
+ template <typename SourceAllocator>
+ bool StringEqual(const GenericValue<Encoding, SourceAllocator>& rhs) const {
+ RAPIDJSON_ASSERT(IsString());
+ RAPIDJSON_ASSERT(rhs.IsString());
+
+ const SizeType len1 = GetStringLength();
+ const SizeType len2 = rhs.GetStringLength();
+ if(len1 != len2) { return false; }
+
+ const Ch* const str1 = GetString();
+ const Ch* const str2 = rhs.GetString();
+ if(str1 == str2) { return true; } // fast path for constant string
+
+ return (std::memcmp(str1, str2, sizeof(Ch) * len1) == 0);
+ }
+
+ Data data_;
+};
+
+//! GenericValue with UTF8 encoding
+typedef GenericValue<UTF8<> > Value;
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericDocument
+
+//! A document for parsing JSON text as DOM.
+/*!
+ \note implements Handler concept
+ \tparam Encoding Encoding for both parsing and string storage.
+ \tparam Allocator Allocator for allocating memory for the DOM
+ \tparam StackAllocator Allocator for allocating memory for stack during parsing.
+ \warning Although GenericDocument inherits from GenericValue, the API does \b not provide any virtual functions, especially no virtual destructor. To avoid memory leaks, do not \c delete a GenericDocument object via a pointer to a GenericValue.
+*/
+template <typename Encoding, typename Allocator = MemoryPoolAllocator<>, typename StackAllocator = CrtAllocator>
+class GenericDocument : public GenericValue<Encoding, Allocator> {
+public:
+ typedef typename Encoding::Ch Ch; //!< Character type derived from Encoding.
+ typedef GenericValue<Encoding, Allocator> ValueType; //!< Value type of the document.
+ typedef Allocator AllocatorType; //!< Allocator type from template parameter.
+
+ //! Constructor
+ /*! Creates an empty document of specified type.
+ \param type Mandatory type of object to create.
+ \param allocator Optional allocator for allocating memory.
+ \param stackCapacity Optional initial capacity of stack in bytes.
+ \param stackAllocator Optional allocator for allocating memory for stack.
+ */
+ explicit GenericDocument(Type type, Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :
+ GenericValue<Encoding, Allocator>(type), allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
+ {
+ if (!allocator_)
+ ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
+ }
+
+ //! Constructor
+ /*! Creates an empty document which type is Null.
+ \param allocator Optional allocator for allocating memory.
+ \param stackCapacity Optional initial capacity of stack in bytes.
+ \param stackAllocator Optional allocator for allocating memory for stack.
+ */
+ GenericDocument(Allocator* allocator = 0, size_t stackCapacity = kDefaultStackCapacity, StackAllocator* stackAllocator = 0) :
+ allocator_(allocator), ownAllocator_(0), stack_(stackAllocator, stackCapacity), parseResult_()
+ {
+ if (!allocator_)
+ ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ //! Move constructor in C++11
+ GenericDocument(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT
+ : ValueType(std::forward<ValueType>(rhs)), // explicit cast to avoid prohibited move from Document
+ allocator_(rhs.allocator_),
+ ownAllocator_(rhs.ownAllocator_),
+ stack_(std::move(rhs.stack_)),
+ parseResult_(rhs.parseResult_)
+ {
+ rhs.allocator_ = 0;
+ rhs.ownAllocator_ = 0;
+ rhs.parseResult_ = ParseResult();
+ }
+#endif
+
+ ~GenericDocument() {
+ Destroy();
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ //! Move assignment in C++11
+ GenericDocument& operator=(GenericDocument&& rhs) RAPIDJSON_NOEXCEPT
+ {
+ // The cast to ValueType is necessary here, because otherwise it would
+ // attempt to call GenericValue's templated assignment operator.
+ ValueType::operator=(std::forward<ValueType>(rhs));
+
+ // Calling the destructor here would prematurely call stack_'s destructor
+ Destroy();
+
+ allocator_ = rhs.allocator_;
+ ownAllocator_ = rhs.ownAllocator_;
+ stack_ = std::move(rhs.stack_);
+ parseResult_ = rhs.parseResult_;
+
+ rhs.allocator_ = 0;
+ rhs.ownAllocator_ = 0;
+ rhs.parseResult_ = ParseResult();
+
+ return *this;
+ }
+#endif
+
+ //! Exchange the contents of this document with those of another.
+ /*!
+ \param rhs Another document.
+ \note Constant complexity.
+ \see GenericValue::Swap
+ */
+ GenericDocument& Swap(GenericDocument& rhs) RAPIDJSON_NOEXCEPT {
+ ValueType::Swap(rhs);
+ stack_.Swap(rhs.stack_);
+ internal::Swap(allocator_, rhs.allocator_);
+ internal::Swap(ownAllocator_, rhs.ownAllocator_);
+ internal::Swap(parseResult_, rhs.parseResult_);
+ return *this;
+ }
+
+ //! free-standing swap function helper
+ /*!
+ Helper function to enable support for common swap implementation pattern based on \c std::swap:
+ \code
+ void swap(MyClass& a, MyClass& b) {
+ using std::swap;
+ swap(a.doc, b.doc);
+ // ...
+ }
+ \endcode
+ \see Swap()
+ */
+ friend inline void swap(GenericDocument& a, GenericDocument& b) RAPIDJSON_NOEXCEPT { a.Swap(b); }
+
+ //! Populate this document by a generator which produces SAX events.
+ /*! \tparam Generator A functor with <tt>bool f(Handler)</tt> prototype.
+ \param g Generator functor which sends SAX events to the parameter.
+ \return The document itself for fluent API.
+ */
+ template <typename Generator>
+ GenericDocument& Populate(Generator& g) {
+ ClearStackOnExit scope(*this);
+ if (g(*this)) {
+ RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
+ ValueType::operator=(*stack_.template Pop<ValueType>(1));// Move value from stack to document
+ }
+ return *this;
+ }
+
+ //!@name Parse from stream
+ //!@{
+
+ //! Parse JSON text from an input stream (with Encoding conversion)
+ /*! \tparam parseFlags Combination of \ref ParseFlag.
+ \tparam SourceEncoding Encoding of input stream
+ \tparam InputStream Type of input stream, implementing Stream concept
+ \param is Input stream to be parsed.
+ \return The document itself for fluent API.
+ */
+ template <unsigned parseFlags, typename SourceEncoding, typename InputStream>
+ GenericDocument& ParseStream(InputStream& is) {
+ GenericReader<SourceEncoding, Encoding, StackAllocator> reader(
+ stack_.HasAllocator() ? &stack_.GetAllocator() : 0);
+ ClearStackOnExit scope(*this);
+ parseResult_ = reader.template Parse<parseFlags>(is, *this);
+ if (parseResult_) {
+ RAPIDJSON_ASSERT(stack_.GetSize() == sizeof(ValueType)); // Got one and only one root object
+ ValueType::operator=(*stack_.template Pop<ValueType>(1));// Move value from stack to document
+ }
+ return *this;
+ }
+
+ //! Parse JSON text from an input stream
+ /*! \tparam parseFlags Combination of \ref ParseFlag.
+ \tparam InputStream Type of input stream, implementing Stream concept
+ \param is Input stream to be parsed.
+ \return The document itself for fluent API.
+ */
+ template <unsigned parseFlags, typename InputStream>
+ GenericDocument& ParseStream(InputStream& is) {
+ return ParseStream<parseFlags, Encoding, InputStream>(is);
+ }
+
+ //! Parse JSON text from an input stream (with \ref kParseDefaultFlags)
+ /*! \tparam InputStream Type of input stream, implementing Stream concept
+ \param is Input stream to be parsed.
+ \return The document itself for fluent API.
+ */
+ template <typename InputStream>
+ GenericDocument& ParseStream(InputStream& is) {
+ return ParseStream<kParseDefaultFlags, Encoding, InputStream>(is);
+ }
+ //!@}
+
+ //!@name Parse in-place from mutable string
+ //!@{
+
+ //! Parse JSON text from a mutable string
+ /*! \tparam parseFlags Combination of \ref ParseFlag.
+ \param str Mutable zero-terminated string to be parsed.
+ \return The document itself for fluent API.
+ */
+ template <unsigned parseFlags>
+ GenericDocument& ParseInsitu(Ch* str) {
+ GenericInsituStringStream<Encoding> s(str);
+ return ParseStream<parseFlags | kParseInsituFlag>(s);
+ }
+
+ //! Parse JSON text from a mutable string (with \ref kParseDefaultFlags)
+ /*! \param str Mutable zero-terminated string to be parsed.
+ \return The document itself for fluent API.
+ */
+ GenericDocument& ParseInsitu(Ch* str) {
+ return ParseInsitu<kParseDefaultFlags>(str);
+ }
+ //!@}
+
+ //!@name Parse from read-only string
+ //!@{
+
+ //! Parse JSON text from a read-only string (with Encoding conversion)
+ /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
+ \tparam SourceEncoding Transcoding from input Encoding
+ \param str Read-only zero-terminated string to be parsed.
+ */
+ template <unsigned parseFlags, typename SourceEncoding>
+ GenericDocument& Parse(const typename SourceEncoding::Ch* str) {
+ RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
+ GenericStringStream<SourceEncoding> s(str);
+ return ParseStream<parseFlags, SourceEncoding>(s);
+ }
+
+ //! Parse JSON text from a read-only string
+ /*! \tparam parseFlags Combination of \ref ParseFlag (must not contain \ref kParseInsituFlag).
+ \param str Read-only zero-terminated string to be parsed.
+ */
+ template <unsigned parseFlags>
+ GenericDocument& Parse(const Ch* str) {
+ return Parse<parseFlags, Encoding>(str);
+ }
+
+ //! Parse JSON text from a read-only string (with \ref kParseDefaultFlags)
+ /*! \param str Read-only zero-terminated string to be parsed.
+ */
+ GenericDocument& Parse(const Ch* str) {
+ return Parse<kParseDefaultFlags>(str);
+ }
+
+ template <unsigned parseFlags, typename SourceEncoding>
+ GenericDocument& Parse(const typename SourceEncoding::Ch* str, size_t length) {
+ RAPIDJSON_ASSERT(!(parseFlags & kParseInsituFlag));
+ MemoryStream ms(static_cast<const char*>(str), length * sizeof(typename SourceEncoding::Ch));
+ EncodedInputStream<SourceEncoding, MemoryStream> is(ms);
+ ParseStream<parseFlags, SourceEncoding>(is);
+ return *this;
+ }
+
+ template <unsigned parseFlags>
+ GenericDocument& Parse(const Ch* str, size_t length) {
+ return Parse<parseFlags, Encoding>(str, length);
+ }
+
+ GenericDocument& Parse(const Ch* str, size_t length) {
+ return Parse<kParseDefaultFlags>(str, length);
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ template <unsigned parseFlags, typename SourceEncoding>
+ GenericDocument& Parse(const std::basic_string<typename SourceEncoding::Ch>& str) {
+ // c_str() is constant complexity according to standard. Should be faster than Parse(const char*, size_t)
+ return Parse<parseFlags, SourceEncoding>(str.c_str());
+ }
+
+ template <unsigned parseFlags>
+ GenericDocument& Parse(const std::basic_string<Ch>& str) {
+ return Parse<parseFlags, Encoding>(str.c_str());
+ }
+
+ GenericDocument& Parse(const std::basic_string<Ch>& str) {
+ return Parse<kParseDefaultFlags>(str);
+ }
+#endif // RAPIDJSON_HAS_STDSTRING
+
+ //!@}
+
+ //!@name Handling parse errors
+ //!@{
+
+ //! Whether a parse error has occured in the last parsing.
+ bool HasParseError() const { return parseResult_.IsError(); }
+
+ //! Get the \ref ParseErrorCode of last parsing.
+ ParseErrorCode GetParseError() const { return parseResult_.Code(); }
+
+ //! Get the position of last parsing error in input, 0 otherwise.
+ size_t GetErrorOffset() const { return parseResult_.Offset(); }
+
+ //! Implicit conversion to get the last parse result
+#ifndef __clang // -Wdocumentation
+ /*! \return \ref ParseResult of the last parse operation
+
+ \code
+ Document doc;
+ ParseResult ok = doc.Parse(json);
+ if (!ok)
+ printf( "JSON parse error: %s (%u)\n", GetParseError_En(ok.Code()), ok.Offset());
+ \endcode
+ */
+#endif
+ operator ParseResult() const { return parseResult_; }
+ //!@}
+
+ //! Get the allocator of this document.
+ Allocator& GetAllocator() {
+ RAPIDJSON_ASSERT(allocator_);
+ return *allocator_;
+ }
+
+ //! Get the capacity of stack in bytes.
+ size_t GetStackCapacity() const { return stack_.GetCapacity(); }
+
+private:
+ // clear stack on any exit from ParseStream, e.g. due to exception
+ struct ClearStackOnExit {
+ explicit ClearStackOnExit(GenericDocument& d) : d_(d) {}
+ ~ClearStackOnExit() { d_.ClearStack(); }
+ private:
+ ClearStackOnExit(const ClearStackOnExit&);
+ ClearStackOnExit& operator=(const ClearStackOnExit&);
+ GenericDocument& d_;
+ };
+
+ // callers of the following private Handler functions
+ // template <typename,typename,typename> friend class GenericReader; // for parsing
+ template <typename, typename> friend class GenericValue; // for deep copying
+
+public:
+ // Implementation of Handler
+ bool Null() { new (stack_.template Push<ValueType>()) ValueType(); return true; }
+ bool Bool(bool b) { new (stack_.template Push<ValueType>()) ValueType(b); return true; }
+ bool Int(int i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
+ bool Uint(unsigned i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
+ bool Int64(int64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
+ bool Uint64(uint64_t i) { new (stack_.template Push<ValueType>()) ValueType(i); return true; }
+ bool Double(double d) { new (stack_.template Push<ValueType>()) ValueType(d); return true; }
+
+ bool RawNumber(const Ch* str, SizeType length, bool copy) {
+ if (copy)
+ new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator());
+ else
+ new (stack_.template Push<ValueType>()) ValueType(str, length);
+ return true;
+ }
+
+ bool String(const Ch* str, SizeType length, bool copy) {
+ if (copy)
+ new (stack_.template Push<ValueType>()) ValueType(str, length, GetAllocator());
+ else
+ new (stack_.template Push<ValueType>()) ValueType(str, length);
+ return true;
+ }
+
+ bool StartObject() { new (stack_.template Push<ValueType>()) ValueType(kObjectType); return true; }
+
+ bool Key(const Ch* str, SizeType length, bool copy) { return String(str, length, copy); }
+
+ bool EndObject(SizeType memberCount) {
+ typename ValueType::Member* members = stack_.template Pop<typename ValueType::Member>(memberCount);
+ stack_.template Top<ValueType>()->SetObjectRaw(members, memberCount, GetAllocator());
+ return true;
+ }
+
+ bool StartArray() { new (stack_.template Push<ValueType>()) ValueType(kArrayType); return true; }
+
+ bool EndArray(SizeType elementCount) {
+ ValueType* elements = stack_.template Pop<ValueType>(elementCount);
+ stack_.template Top<ValueType>()->SetArrayRaw(elements, elementCount, GetAllocator());
+ return true;
+ }
+
+private:
+ //! Prohibit copying
+ GenericDocument(const GenericDocument&);
+ //! Prohibit assignment
+ GenericDocument& operator=(const GenericDocument&);
+
+ void ClearStack() {
+ if (Allocator::kNeedFree)
+ while (stack_.GetSize() > 0) // Here assumes all elements in stack array are GenericValue (Member is actually 2 GenericValue objects)
+ (stack_.template Pop<ValueType>(1))->~ValueType();
+ else
+ stack_.Clear();
+ stack_.ShrinkToFit();
+ }
+
+ void Destroy() {
+ RAPIDJSON_DELETE(ownAllocator_);
+ }
+
+ static const size_t kDefaultStackCapacity = 1024;
+ Allocator* allocator_;
+ Allocator* ownAllocator_;
+ internal::Stack<StackAllocator> stack_;
+ ParseResult parseResult_;
+};
+
+//! GenericDocument with UTF8 encoding
+typedef GenericDocument<UTF8<> > Document;
+
+// defined here due to the dependency on GenericDocument
+template <typename Encoding, typename Allocator>
+template <typename SourceAllocator>
+inline
+GenericValue<Encoding,Allocator>::GenericValue(const GenericValue<Encoding,SourceAllocator>& rhs, Allocator& allocator)
+{
+ switch (rhs.GetType()) {
+ case kObjectType:
+ case kArrayType: { // perform deep copy via SAX Handler
+ GenericDocument<Encoding,Allocator> d(&allocator);
+ rhs.Accept(d);
+ RawAssign(*d.stack_.template Pop<GenericValue>(1));
+ }
+ break;
+ case kStringType:
+ if (rhs.data_.f.flags == kConstStringFlag) {
+ data_.f.flags = rhs.data_.f.flags;
+ data_ = *reinterpret_cast<const Data*>(&rhs.data_);
+ } else {
+ SetStringRaw(StringRef(rhs.GetString(), rhs.GetStringLength()), allocator);
+ }
+ break;
+ default:
+ data_.f.flags = rhs.data_.f.flags;
+ data_ = *reinterpret_cast<const Data*>(&rhs.data_);
+ break;
+ }
+}
+
+//! Helper class for accessing Value of array type.
+/*!
+ Instance of this helper class is obtained by \c GenericValue::GetArray().
+ In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1.
+*/
+template <bool Const, typename ValueT>
+class GenericArray {
+public:
+ typedef GenericArray<true, ValueT> ConstArray;
+ typedef GenericArray<false, ValueT> Array;
+ typedef ValueT PlainType;
+ typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
+ typedef ValueType* ValueIterator; // This may be const or non-const iterator
+ typedef const ValueT* ConstValueIterator;
+ typedef typename ValueType::AllocatorType AllocatorType;
+ typedef typename ValueType::StringRefType StringRefType;
+
+ template <typename, typename>
+ friend class GenericValue;
+
+ GenericArray(const GenericArray& rhs) : value_(rhs.value_) {}
+ GenericArray& operator=(const GenericArray& rhs) { value_ = rhs.value_; return *this; }
+ ~GenericArray() {}
+
+ SizeType Size() const { return value_.Size(); }
+ SizeType Capacity() const { return value_.Capacity(); }
+ bool Empty() const { return value_.Empty(); }
+ void Clear() const { value_.Clear(); }
+ ValueType& operator[](SizeType index) const { return value_[index]; }
+ ValueIterator Begin() const { return value_.Begin(); }
+ ValueIterator End() const { return value_.End(); }
+ GenericArray Reserve(SizeType newCapacity, AllocatorType &allocator) const { value_.Reserve(newCapacity, allocator); return *this; }
+ GenericArray PushBack(ValueType& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ GenericArray PushBack(ValueType&& value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
+#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ GenericArray PushBack(StringRefType value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
+ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (const GenericArray&)) PushBack(T value, AllocatorType& allocator) const { value_.PushBack(value, allocator); return *this; }
+ GenericArray PopBack() const { value_.PopBack(); return *this; }
+ ValueIterator Erase(ConstValueIterator pos) const { return value_.Erase(pos); }
+ ValueIterator Erase(ConstValueIterator first, ConstValueIterator last) const { return value_.Erase(first, last); }
+
+#if RAPIDJSON_HAS_CXX11_RANGE_FOR
+ ValueIterator begin() const { return value_.Begin(); }
+ ValueIterator end() const { return value_.End(); }
+#endif
+
+private:
+ GenericArray();
+ GenericArray(ValueType& value) : value_(value) {}
+ ValueType& value_;
+};
+
+//! Helper class for accessing Value of object type.
+/*!
+ Instance of this helper class is obtained by \c GenericValue::GetObject().
+ In addition to all APIs for array type, it provides range-based for loop if \c RAPIDJSON_HAS_CXX11_RANGE_FOR=1.
+*/
+template <bool Const, typename ValueT>
+class GenericObject {
+public:
+ typedef GenericObject<true, ValueT> ConstObject;
+ typedef GenericObject<false, ValueT> Object;
+ typedef ValueT PlainType;
+ typedef typename internal::MaybeAddConst<Const,PlainType>::Type ValueType;
+ typedef GenericMemberIterator<Const, typename ValueT::EncodingType, typename ValueT::AllocatorType> MemberIterator; // This may be const or non-const iterator
+ typedef GenericMemberIterator<true, typename ValueT::EncodingType, typename ValueT::AllocatorType> ConstMemberIterator;
+ typedef typename ValueType::AllocatorType AllocatorType;
+ typedef typename ValueType::StringRefType StringRefType;
+ typedef typename ValueType::EncodingType EncodingType;
+ typedef typename ValueType::Ch Ch;
+
+ template <typename, typename>
+ friend class GenericValue;
+
+ GenericObject(const GenericObject& rhs) : value_(rhs.value_) {}
+ GenericObject& operator=(const GenericObject& rhs) { value_ = rhs.value_; return *this; }
+ ~GenericObject() {}
+
+ SizeType MemberCount() const { return value_.MemberCount(); }
+ bool ObjectEmpty() const { return value_.ObjectEmpty(); }
+ template <typename T> ValueType& operator[](T* name) const { return value_[name]; }
+ template <typename SourceAllocator> ValueType& operator[](const GenericValue<EncodingType, SourceAllocator>& name) const { return value_[name]; }
+#if RAPIDJSON_HAS_STDSTRING
+ ValueType& operator[](const std::basic_string<Ch>& name) const { return value_[name]; }
+#endif
+ MemberIterator MemberBegin() const { return value_.MemberBegin(); }
+ MemberIterator MemberEnd() const { return value_.MemberEnd(); }
+ bool HasMember(const Ch* name) const { return value_.HasMember(name); }
+#if RAPIDJSON_HAS_STDSTRING
+ bool HasMember(const std::basic_string<Ch>& name) const { return value_.HasMember(name); }
+#endif
+ template <typename SourceAllocator> bool HasMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.HasMember(name); }
+ MemberIterator FindMember(const Ch* name) const { return value_.FindMember(name); }
+ template <typename SourceAllocator> MemberIterator FindMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.FindMember(name); }
+#if RAPIDJSON_HAS_STDSTRING
+ MemberIterator FindMember(const std::basic_string<Ch>& name) const { return value_.FindMember(name); }
+#endif
+ GenericObject AddMember(ValueType& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+ GenericObject AddMember(ValueType& name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+#if RAPIDJSON_HAS_STDSTRING
+ GenericObject AddMember(ValueType& name, std::basic_string<Ch>& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+#endif
+ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&)) AddMember(ValueType& name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ GenericObject AddMember(ValueType&& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+ GenericObject AddMember(ValueType&& name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+ GenericObject AddMember(ValueType& name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+ GenericObject AddMember(StringRefType name, ValueType&& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ GenericObject AddMember(StringRefType name, ValueType& value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+ GenericObject AddMember(StringRefType name, StringRefType value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+ template <typename T> RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (GenericObject)) AddMember(StringRefType name, T value, AllocatorType& allocator) const { value_.AddMember(name, value, allocator); return *this; }
+ void RemoveAllMembers() { return value_.RemoveAllMembers(); }
+ bool RemoveMember(const Ch* name) const { return value_.RemoveMember(name); }
+#if RAPIDJSON_HAS_STDSTRING
+ bool RemoveMember(const std::basic_string<Ch>& name) const { return value_.RemoveMember(name); }
+#endif
+ template <typename SourceAllocator> bool RemoveMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.RemoveMember(name); }
+ MemberIterator RemoveMember(MemberIterator m) const { return value_.RemoveMember(m); }
+ MemberIterator EraseMember(ConstMemberIterator pos) const { return value_.EraseMember(pos); }
+ MemberIterator EraseMember(ConstMemberIterator first, ConstMemberIterator last) const { return value_.EraseMember(first, last); }
+ bool EraseMember(const Ch* name) const { return value_.EraseMember(name); }
+#if RAPIDJSON_HAS_STDSTRING
+ bool EraseMember(const std::basic_string<Ch>& name) const { return EraseMember(ValueType(StringRef(name))); }
+#endif
+ template <typename SourceAllocator> bool EraseMember(const GenericValue<EncodingType, SourceAllocator>& name) const { return value_.EraseMember(name); }
+
+#if RAPIDJSON_HAS_CXX11_RANGE_FOR
+ MemberIterator begin() const { return value_.MemberBegin(); }
+ MemberIterator end() const { return value_.MemberEnd(); }
+#endif
+
+private:
+ GenericObject();
+ GenericObject(ValueType& value) : value_(value) {}
+ ValueType& value_;
+};
+
+RAPIDJSON_NAMESPACE_END
+RAPIDJSON_DIAG_POP
+
+#endif // RAPIDJSON_DOCUMENT_H_
diff --git a/include/rapidjson/encodedstream.h b/include/rapidjson/encodedstream.h
new file mode 100644
index 00000000..14506838
--- /dev/null
+++ b/include/rapidjson/encodedstream.h
@@ -0,0 +1,299 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_ENCODEDSTREAM_H_
+#define RAPIDJSON_ENCODEDSTREAM_H_
+
+#include "stream.h"
+#include "memorystream.h"
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Input byte stream wrapper with a statically bound encoding.
+/*!
+ \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
+ \tparam InputByteStream Type of input byte stream. For example, FileReadStream.
+*/
+template <typename Encoding, typename InputByteStream>
+class EncodedInputStream {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+public:
+ typedef typename Encoding::Ch Ch;
+
+ EncodedInputStream(InputByteStream& is) : is_(is) {
+ current_ = Encoding::TakeBOM(is_);
+ }
+
+ Ch Peek() const { return current_; }
+ Ch Take() { Ch c = current_; current_ = Encoding::Take(is_); return c; }
+ size_t Tell() const { return is_.Tell(); }
+
+ // Not implemented
+ void Put(Ch) { RAPIDJSON_ASSERT(false); }
+ void Flush() { RAPIDJSON_ASSERT(false); }
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+private:
+ EncodedInputStream(const EncodedInputStream&);
+ EncodedInputStream& operator=(const EncodedInputStream&);
+
+ InputByteStream& is_;
+ Ch current_;
+};
+
+//! Specialized for UTF8 MemoryStream.
+template <>
+class EncodedInputStream<UTF8<>, MemoryStream> {
+public:
+ typedef UTF8<>::Ch Ch;
+
+ EncodedInputStream(MemoryStream& is) : is_(is) {
+ if (static_cast<unsigned char>(is_.Peek()) == 0xEFu) is_.Take();
+ if (static_cast<unsigned char>(is_.Peek()) == 0xBBu) is_.Take();
+ if (static_cast<unsigned char>(is_.Peek()) == 0xBFu) is_.Take();
+ }
+ Ch Peek() const { return is_.Peek(); }
+ Ch Take() { return is_.Take(); }
+ size_t Tell() const { return is_.Tell(); }
+
+ // Not implemented
+ void Put(Ch) {}
+ void Flush() {}
+ Ch* PutBegin() { return 0; }
+ size_t PutEnd(Ch*) { return 0; }
+
+ MemoryStream& is_;
+
+private:
+ EncodedInputStream(const EncodedInputStream&);
+ EncodedInputStream& operator=(const EncodedInputStream&);
+};
+
+//! Output byte stream wrapper with statically bound encoding.
+/*!
+ \tparam Encoding The interpretation of encoding of the stream. Either UTF8, UTF16LE, UTF16BE, UTF32LE, UTF32BE.
+ \tparam OutputByteStream Type of input byte stream. For example, FileWriteStream.
+*/
+template <typename Encoding, typename OutputByteStream>
+class EncodedOutputStream {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+public:
+ typedef typename Encoding::Ch Ch;
+
+ EncodedOutputStream(OutputByteStream& os, bool putBOM = true) : os_(os) {
+ if (putBOM)
+ Encoding::PutBOM(os_);
+ }
+
+ void Put(Ch c) { Encoding::Put(os_, c); }
+ void Flush() { os_.Flush(); }
+
+ // Not implemented
+ Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;}
+ Ch Take() { RAPIDJSON_ASSERT(false); return 0;}
+ size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+private:
+ EncodedOutputStream(const EncodedOutputStream&);
+ EncodedOutputStream& operator=(const EncodedOutputStream&);
+
+ OutputByteStream& os_;
+};
+
+#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
+
+//! Input stream wrapper with dynamically bound encoding and automatic encoding detection.
+/*!
+ \tparam CharType Type of character for reading.
+ \tparam InputByteStream type of input byte stream to be wrapped.
+*/
+template <typename CharType, typename InputByteStream>
+class AutoUTFInputStream {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+public:
+ typedef CharType Ch;
+
+ //! Constructor.
+ /*!
+ \param is input stream to be wrapped.
+ \param type UTF encoding type if it is not detected from the stream.
+ */
+ AutoUTFInputStream(InputByteStream& is, UTFType type = kUTF8) : is_(&is), type_(type), hasBOM_(false) {
+ RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
+ DetectType();
+ static const TakeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Take) };
+ takeFunc_ = f[type_];
+ current_ = takeFunc_(*is_);
+ }
+
+ UTFType GetType() const { return type_; }
+ bool HasBOM() const { return hasBOM_; }
+
+ Ch Peek() const { return current_; }
+ Ch Take() { Ch c = current_; current_ = takeFunc_(*is_); return c; }
+ size_t Tell() const { return is_->Tell(); }
+
+ // Not implemented
+ void Put(Ch) { RAPIDJSON_ASSERT(false); }
+ void Flush() { RAPIDJSON_ASSERT(false); }
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+private:
+ AutoUTFInputStream(const AutoUTFInputStream&);
+ AutoUTFInputStream& operator=(const AutoUTFInputStream&);
+
+ // Detect encoding type with BOM or RFC 4627
+ void DetectType() {
+ // BOM (Byte Order Mark):
+ // 00 00 FE FF UTF-32BE
+ // FF FE 00 00 UTF-32LE
+ // FE FF UTF-16BE
+ // FF FE UTF-16LE
+ // EF BB BF UTF-8
+
+ const unsigned char* c = reinterpret_cast<const unsigned char *>(is_->Peek4());
+ if (!c)
+ return;
+
+ unsigned bom = static_cast<unsigned>(c[0] | (c[1] << 8) | (c[2] << 16) | (c[3] << 24));
+ hasBOM_ = false;
+ if (bom == 0xFFFE0000) { type_ = kUTF32BE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
+ else if (bom == 0x0000FEFF) { type_ = kUTF32LE; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); is_->Take(); }
+ else if ((bom & 0xFFFF) == 0xFFFE) { type_ = kUTF16BE; hasBOM_ = true; is_->Take(); is_->Take(); }
+ else if ((bom & 0xFFFF) == 0xFEFF) { type_ = kUTF16LE; hasBOM_ = true; is_->Take(); is_->Take(); }
+ else if ((bom & 0xFFFFFF) == 0xBFBBEF) { type_ = kUTF8; hasBOM_ = true; is_->Take(); is_->Take(); is_->Take(); }
+
+ // RFC 4627: Section 3
+ // "Since the first two characters of a JSON text will always be ASCII
+ // characters [RFC0020], it is possible to determine whether an octet
+ // stream is UTF-8, UTF-16 (BE or LE), or UTF-32 (BE or LE) by looking
+ // at the pattern of nulls in the first four octets."
+ // 00 00 00 xx UTF-32BE
+ // 00 xx 00 xx UTF-16BE
+ // xx 00 00 00 UTF-32LE
+ // xx 00 xx 00 UTF-16LE
+ // xx xx xx xx UTF-8
+
+ if (!hasBOM_) {
+ unsigned pattern = (c[0] ? 1 : 0) | (c[1] ? 2 : 0) | (c[2] ? 4 : 0) | (c[3] ? 8 : 0);
+ switch (pattern) {
+ case 0x08: type_ = kUTF32BE; break;
+ case 0x0A: type_ = kUTF16BE; break;
+ case 0x01: type_ = kUTF32LE; break;
+ case 0x05: type_ = kUTF16LE; break;
+ case 0x0F: type_ = kUTF8; break;
+ default: break; // Use type defined by user.
+ }
+ }
+
+ // Runtime check whether the size of character type is sufficient. It only perform checks with assertion.
+ if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
+ if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
+ }
+
+ typedef Ch (*TakeFunc)(InputByteStream& is);
+ InputByteStream* is_;
+ UTFType type_;
+ Ch current_;
+ TakeFunc takeFunc_;
+ bool hasBOM_;
+};
+
+//! Output stream wrapper with dynamically bound encoding and automatic encoding detection.
+/*!
+ \tparam CharType Type of character for writing.
+ \tparam OutputByteStream type of output byte stream to be wrapped.
+*/
+template <typename CharType, typename OutputByteStream>
+class AutoUTFOutputStream {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+public:
+ typedef CharType Ch;
+
+ //! Constructor.
+ /*!
+ \param os output stream to be wrapped.
+ \param type UTF encoding type.
+ \param putBOM Whether to write BOM at the beginning of the stream.
+ */
+ AutoUTFOutputStream(OutputByteStream& os, UTFType type, bool putBOM) : os_(&os), type_(type) {
+ RAPIDJSON_ASSERT(type >= kUTF8 && type <= kUTF32BE);
+
+ // Runtime check whether the size of character type is sufficient. It only perform checks with assertion.
+ if (type_ == kUTF16LE || type_ == kUTF16BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 2);
+ if (type_ == kUTF32LE || type_ == kUTF32BE) RAPIDJSON_ASSERT(sizeof(Ch) >= 4);
+
+ static const PutFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Put) };
+ putFunc_ = f[type_];
+
+ if (putBOM)
+ PutBOM();
+ }
+
+ UTFType GetType() const { return type_; }
+
+ void Put(Ch c) { putFunc_(*os_, c); }
+ void Flush() { os_->Flush(); }
+
+ // Not implemented
+ Ch Peek() const { RAPIDJSON_ASSERT(false); return 0;}
+ Ch Take() { RAPIDJSON_ASSERT(false); return 0;}
+ size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+private:
+ AutoUTFOutputStream(const AutoUTFOutputStream&);
+ AutoUTFOutputStream& operator=(const AutoUTFOutputStream&);
+
+ void PutBOM() {
+ typedef void (*PutBOMFunc)(OutputByteStream&);
+ static const PutBOMFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(PutBOM) };
+ f[type_](*os_);
+ }
+
+ typedef void (*PutFunc)(OutputByteStream&, Ch);
+
+ OutputByteStream* os_;
+ UTFType type_;
+ PutFunc putFunc_;
+};
+
+#undef RAPIDJSON_ENCODINGS_FUNC
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_FILESTREAM_H_
diff --git a/include/rapidjson/encodings.h b/include/rapidjson/encodings.h
new file mode 100644
index 00000000..baa7c2b1
--- /dev/null
+++ b/include/rapidjson/encodings.h
@@ -0,0 +1,716 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_ENCODINGS_H_
+#define RAPIDJSON_ENCODINGS_H_
+
+#include "rapidjson.h"
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(4244) // conversion from 'type1' to 'type2', possible loss of data
+RAPIDJSON_DIAG_OFF(4702) // unreachable code
+#elif defined(__GNUC__)
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+RAPIDJSON_DIAG_OFF(overflow)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+///////////////////////////////////////////////////////////////////////////////
+// Encoding
+
+/*! \class rapidjson::Encoding
+ \brief Concept for encoding of Unicode characters.
+
+\code
+concept Encoding {
+ typename Ch; //! Type of character. A "character" is actually a code unit in unicode's definition.
+
+ enum { supportUnicode = 1 }; // or 0 if not supporting unicode
+
+ //! \brief Encode a Unicode codepoint to an output stream.
+ //! \param os Output stream.
+ //! \param codepoint An unicode codepoint, ranging from 0x0 to 0x10FFFF inclusively.
+ template<typename OutputStream>
+ static void Encode(OutputStream& os, unsigned codepoint);
+
+ //! \brief Decode a Unicode codepoint from an input stream.
+ //! \param is Input stream.
+ //! \param codepoint Output of the unicode codepoint.
+ //! \return true if a valid codepoint can be decoded from the stream.
+ template <typename InputStream>
+ static bool Decode(InputStream& is, unsigned* codepoint);
+
+ //! \brief Validate one Unicode codepoint from an encoded stream.
+ //! \param is Input stream to obtain codepoint.
+ //! \param os Output for copying one codepoint.
+ //! \return true if it is valid.
+ //! \note This function just validating and copying the codepoint without actually decode it.
+ template <typename InputStream, typename OutputStream>
+ static bool Validate(InputStream& is, OutputStream& os);
+
+ // The following functions are deal with byte streams.
+
+ //! Take a character from input byte stream, skip BOM if exist.
+ template <typename InputByteStream>
+ static CharType TakeBOM(InputByteStream& is);
+
+ //! Take a character from input byte stream.
+ template <typename InputByteStream>
+ static Ch Take(InputByteStream& is);
+
+ //! Put BOM to output byte stream.
+ template <typename OutputByteStream>
+ static void PutBOM(OutputByteStream& os);
+
+ //! Put a character to output byte stream.
+ template <typename OutputByteStream>
+ static void Put(OutputByteStream& os, Ch c);
+};
+\endcode
+*/
+
+///////////////////////////////////////////////////////////////////////////////
+// UTF8
+
+//! UTF-8 encoding.
+/*! http://en.wikipedia.org/wiki/UTF-8
+ http://tools.ietf.org/html/rfc3629
+ \tparam CharType Code unit for storing 8-bit UTF-8 data. Default is char.
+ \note implements Encoding concept
+*/
+template<typename CharType = char>
+struct UTF8 {
+ typedef CharType Ch;
+
+ enum { supportUnicode = 1 };
+
+ template<typename OutputStream>
+ static void Encode(OutputStream& os, unsigned codepoint) {
+ if (codepoint <= 0x7F)
+ os.Put(static_cast<Ch>(codepoint & 0xFF));
+ else if (codepoint <= 0x7FF) {
+ os.Put(static_cast<Ch>(0xC0 | ((codepoint >> 6) & 0xFF)));
+ os.Put(static_cast<Ch>(0x80 | ((codepoint & 0x3F))));
+ }
+ else if (codepoint <= 0xFFFF) {
+ os.Put(static_cast<Ch>(0xE0 | ((codepoint >> 12) & 0xFF)));
+ os.Put(static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F)));
+ os.Put(static_cast<Ch>(0x80 | (codepoint & 0x3F)));
+ }
+ else {
+ RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
+ os.Put(static_cast<Ch>(0xF0 | ((codepoint >> 18) & 0xFF)));
+ os.Put(static_cast<Ch>(0x80 | ((codepoint >> 12) & 0x3F)));
+ os.Put(static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F)));
+ os.Put(static_cast<Ch>(0x80 | (codepoint & 0x3F)));
+ }
+ }
+
+ template<typename OutputStream>
+ static void EncodeUnsafe(OutputStream& os, unsigned codepoint) {
+ if (codepoint <= 0x7F)
+ PutUnsafe(os, static_cast<Ch>(codepoint & 0xFF));
+ else if (codepoint <= 0x7FF) {
+ PutUnsafe(os, static_cast<Ch>(0xC0 | ((codepoint >> 6) & 0xFF)));
+ PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint & 0x3F))));
+ }
+ else if (codepoint <= 0xFFFF) {
+ PutUnsafe(os, static_cast<Ch>(0xE0 | ((codepoint >> 12) & 0xFF)));
+ PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F)));
+ PutUnsafe(os, static_cast<Ch>(0x80 | (codepoint & 0x3F)));
+ }
+ else {
+ RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
+ PutUnsafe(os, static_cast<Ch>(0xF0 | ((codepoint >> 18) & 0xFF)));
+ PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint >> 12) & 0x3F)));
+ PutUnsafe(os, static_cast<Ch>(0x80 | ((codepoint >> 6) & 0x3F)));
+ PutUnsafe(os, static_cast<Ch>(0x80 | (codepoint & 0x3F)));
+ }
+ }
+
+ template <typename InputStream>
+ static bool Decode(InputStream& is, unsigned* codepoint) {
+#define COPY() c = is.Take(); *codepoint = (*codepoint << 6) | (static_cast<unsigned char>(c) & 0x3Fu)
+#define TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0)
+#define TAIL() COPY(); TRANS(0x70)
+ typename InputStream::Ch c = is.Take();
+ if (!(c & 0x80)) {
+ *codepoint = static_cast<unsigned char>(c);
+ return true;
+ }
+
+ unsigned char type = GetRange(static_cast<unsigned char>(c));
+ if (type >= 32) {
+ *codepoint = 0;
+ } else {
+ *codepoint = (0xFF >> type) & static_cast<unsigned char>(c);
+ }
+ bool result = true;
+ switch (type) {
+ case 2: TAIL(); return result;
+ case 3: TAIL(); TAIL(); return result;
+ case 4: COPY(); TRANS(0x50); TAIL(); return result;
+ case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result;
+ case 6: TAIL(); TAIL(); TAIL(); return result;
+ case 10: COPY(); TRANS(0x20); TAIL(); return result;
+ case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result;
+ default: return false;
+ }
+#undef COPY
+#undef TRANS
+#undef TAIL
+ }
+
+ template <typename InputStream, typename OutputStream>
+ static bool Validate(InputStream& is, OutputStream& os) {
+#define COPY() os.Put(c = is.Take())
+#define TRANS(mask) result &= ((GetRange(static_cast<unsigned char>(c)) & mask) != 0)
+#define TAIL() COPY(); TRANS(0x70)
+ Ch c;
+ COPY();
+ if (!(c & 0x80))
+ return true;
+
+ bool result = true;
+ switch (GetRange(static_cast<unsigned char>(c))) {
+ case 2: TAIL(); return result;
+ case 3: TAIL(); TAIL(); return result;
+ case 4: COPY(); TRANS(0x50); TAIL(); return result;
+ case 5: COPY(); TRANS(0x10); TAIL(); TAIL(); return result;
+ case 6: TAIL(); TAIL(); TAIL(); return result;
+ case 10: COPY(); TRANS(0x20); TAIL(); return result;
+ case 11: COPY(); TRANS(0x60); TAIL(); TAIL(); return result;
+ default: return false;
+ }
+#undef COPY
+#undef TRANS
+#undef TAIL
+ }
+
+ static unsigned char GetRange(unsigned char c) {
+ // Referring to DFA of http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
+ // With new mapping 1 -> 0x10, 7 -> 0x20, 9 -> 0x40, such that AND operation can test multiple types.
+ static const unsigned char type[] = {
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,0x10,
+ 0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,
+ 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
+ 0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,0x20,
+ 8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+ 10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
+ };
+ return type[c];
+ }
+
+ template <typename InputByteStream>
+ static CharType TakeBOM(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ typename InputByteStream::Ch c = Take(is);
+ if (static_cast<unsigned char>(c) != 0xEFu) return c;
+ c = is.Take();
+ if (static_cast<unsigned char>(c) != 0xBBu) return c;
+ c = is.Take();
+ if (static_cast<unsigned char>(c) != 0xBFu) return c;
+ c = is.Take();
+ return c;
+ }
+
+ template <typename InputByteStream>
+ static Ch Take(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ return static_cast<Ch>(is.Take());
+ }
+
+ template <typename OutputByteStream>
+ static void PutBOM(OutputByteStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xEFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xBBu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xBFu));
+ }
+
+ template <typename OutputByteStream>
+ static void Put(OutputByteStream& os, Ch c) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(c));
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// UTF16
+
+//! UTF-16 encoding.
+/*! http://en.wikipedia.org/wiki/UTF-16
+ http://tools.ietf.org/html/rfc2781
+ \tparam CharType Type for storing 16-bit UTF-16 data. Default is wchar_t. C++11 may use char16_t instead.
+ \note implements Encoding concept
+
+ \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness.
+ For streaming, use UTF16LE and UTF16BE, which handle endianness.
+*/
+template<typename CharType = wchar_t>
+struct UTF16 {
+ typedef CharType Ch;
+ RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 2);
+
+ enum { supportUnicode = 1 };
+
+ template<typename OutputStream>
+ static void Encode(OutputStream& os, unsigned codepoint) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2);
+ if (codepoint <= 0xFFFF) {
+ RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair
+ os.Put(static_cast<typename OutputStream::Ch>(codepoint));
+ }
+ else {
+ RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
+ unsigned v = codepoint - 0x10000;
+ os.Put(static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800));
+ os.Put((v & 0x3FF) | 0xDC00);
+ }
+ }
+
+
+ template<typename OutputStream>
+ static void EncodeUnsafe(OutputStream& os, unsigned codepoint) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2);
+ if (codepoint <= 0xFFFF) {
+ RAPIDJSON_ASSERT(codepoint < 0xD800 || codepoint > 0xDFFF); // Code point itself cannot be surrogate pair
+ PutUnsafe(os, static_cast<typename OutputStream::Ch>(codepoint));
+ }
+ else {
+ RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
+ unsigned v = codepoint - 0x10000;
+ PutUnsafe(os, static_cast<typename OutputStream::Ch>((v >> 10) | 0xD800));
+ PutUnsafe(os, (v & 0x3FF) | 0xDC00);
+ }
+ }
+
+ template <typename InputStream>
+ static bool Decode(InputStream& is, unsigned* codepoint) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2);
+ typename InputStream::Ch c = is.Take();
+ if (c < 0xD800 || c > 0xDFFF) {
+ *codepoint = static_cast<unsigned>(c);
+ return true;
+ }
+ else if (c <= 0xDBFF) {
+ *codepoint = (static_cast<unsigned>(c) & 0x3FF) << 10;
+ c = is.Take();
+ *codepoint |= (static_cast<unsigned>(c) & 0x3FF);
+ *codepoint += 0x10000;
+ return c >= 0xDC00 && c <= 0xDFFF;
+ }
+ return false;
+ }
+
+ template <typename InputStream, typename OutputStream>
+ static bool Validate(InputStream& is, OutputStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 2);
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 2);
+ typename InputStream::Ch c;
+ os.Put(static_cast<typename OutputStream::Ch>(c = is.Take()));
+ if (c < 0xD800 || c > 0xDFFF)
+ return true;
+ else if (c <= 0xDBFF) {
+ os.Put(c = is.Take());
+ return c >= 0xDC00 && c <= 0xDFFF;
+ }
+ return false;
+ }
+};
+
+//! UTF-16 little endian encoding.
+template<typename CharType = wchar_t>
+struct UTF16LE : UTF16<CharType> {
+ template <typename InputByteStream>
+ static CharType TakeBOM(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ CharType c = Take(is);
+ return static_cast<uint16_t>(c) == 0xFEFFu ? Take(is) : c;
+ }
+
+ template <typename InputByteStream>
+ static CharType Take(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ unsigned c = static_cast<uint8_t>(is.Take());
+ c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8;
+ return static_cast<CharType>(c);
+ }
+
+ template <typename OutputByteStream>
+ static void PutBOM(OutputByteStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu));
+ }
+
+ template <typename OutputByteStream>
+ static void Put(OutputByteStream& os, CharType c) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(static_cast<unsigned>(c) & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>((static_cast<unsigned>(c) >> 8) & 0xFFu));
+ }
+};
+
+//! UTF-16 big endian encoding.
+template<typename CharType = wchar_t>
+struct UTF16BE : UTF16<CharType> {
+ template <typename InputByteStream>
+ static CharType TakeBOM(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ CharType c = Take(is);
+ return static_cast<uint16_t>(c) == 0xFEFFu ? Take(is) : c;
+ }
+
+ template <typename InputByteStream>
+ static CharType Take(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ unsigned c = static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8;
+ c |= static_cast<uint8_t>(is.Take());
+ return static_cast<CharType>(c);
+ }
+
+ template <typename OutputByteStream>
+ static void PutBOM(OutputByteStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu));
+ }
+
+ template <typename OutputByteStream>
+ static void Put(OutputByteStream& os, CharType c) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>((static_cast<unsigned>(c) >> 8) & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(static_cast<unsigned>(c) & 0xFFu));
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// UTF32
+
+//! UTF-32 encoding.
+/*! http://en.wikipedia.org/wiki/UTF-32
+ \tparam CharType Type for storing 32-bit UTF-32 data. Default is unsigned. C++11 may use char32_t instead.
+ \note implements Encoding concept
+
+ \note For in-memory access, no need to concern endianness. The code units and code points are represented by CPU's endianness.
+ For streaming, use UTF32LE and UTF32BE, which handle endianness.
+*/
+template<typename CharType = unsigned>
+struct UTF32 {
+ typedef CharType Ch;
+ RAPIDJSON_STATIC_ASSERT(sizeof(Ch) >= 4);
+
+ enum { supportUnicode = 1 };
+
+ template<typename OutputStream>
+ static void Encode(OutputStream& os, unsigned codepoint) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4);
+ RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
+ os.Put(codepoint);
+ }
+
+ template<typename OutputStream>
+ static void EncodeUnsafe(OutputStream& os, unsigned codepoint) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputStream::Ch) >= 4);
+ RAPIDJSON_ASSERT(codepoint <= 0x10FFFF);
+ PutUnsafe(os, codepoint);
+ }
+
+ template <typename InputStream>
+ static bool Decode(InputStream& is, unsigned* codepoint) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4);
+ Ch c = is.Take();
+ *codepoint = c;
+ return c <= 0x10FFFF;
+ }
+
+ template <typename InputStream, typename OutputStream>
+ static bool Validate(InputStream& is, OutputStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputStream::Ch) >= 4);
+ Ch c;
+ os.Put(c = is.Take());
+ return c <= 0x10FFFF;
+ }
+};
+
+//! UTF-32 little endian enocoding.
+template<typename CharType = unsigned>
+struct UTF32LE : UTF32<CharType> {
+ template <typename InputByteStream>
+ static CharType TakeBOM(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ CharType c = Take(is);
+ return static_cast<uint32_t>(c) == 0x0000FEFFu ? Take(is) : c;
+ }
+
+ template <typename InputByteStream>
+ static CharType Take(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ unsigned c = static_cast<uint8_t>(is.Take());
+ c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8;
+ c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 16;
+ c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 24;
+ return static_cast<CharType>(c);
+ }
+
+ template <typename OutputByteStream>
+ static void PutBOM(OutputByteStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0x00u));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0x00u));
+ }
+
+ template <typename OutputByteStream>
+ static void Put(OutputByteStream& os, CharType c) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(c & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>((c >> 8) & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>((c >> 16) & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>((c >> 24) & 0xFFu));
+ }
+};
+
+//! UTF-32 big endian encoding.
+template<typename CharType = unsigned>
+struct UTF32BE : UTF32<CharType> {
+ template <typename InputByteStream>
+ static CharType TakeBOM(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ CharType c = Take(is);
+ return static_cast<uint32_t>(c) == 0x0000FEFFu ? Take(is) : c;
+ }
+
+ template <typename InputByteStream>
+ static CharType Take(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ unsigned c = static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 24;
+ c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 16;
+ c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take())) << 8;
+ c |= static_cast<unsigned>(static_cast<uint8_t>(is.Take()));
+ return static_cast<CharType>(c);
+ }
+
+ template <typename OutputByteStream>
+ static void PutBOM(OutputByteStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(0x00u));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0x00u));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFEu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(0xFFu));
+ }
+
+ template <typename OutputByteStream>
+ static void Put(OutputByteStream& os, CharType c) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>((c >> 24) & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>((c >> 16) & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>((c >> 8) & 0xFFu));
+ os.Put(static_cast<typename OutputByteStream::Ch>(c & 0xFFu));
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// ASCII
+
+//! ASCII encoding.
+/*! http://en.wikipedia.org/wiki/ASCII
+ \tparam CharType Code unit for storing 7-bit ASCII data. Default is char.
+ \note implements Encoding concept
+*/
+template<typename CharType = char>
+struct ASCII {
+ typedef CharType Ch;
+
+ enum { supportUnicode = 0 };
+
+ template<typename OutputStream>
+ static void Encode(OutputStream& os, unsigned codepoint) {
+ RAPIDJSON_ASSERT(codepoint <= 0x7F);
+ os.Put(static_cast<Ch>(codepoint & 0xFF));
+ }
+
+ template<typename OutputStream>
+ static void EncodeUnsafe(OutputStream& os, unsigned codepoint) {
+ RAPIDJSON_ASSERT(codepoint <= 0x7F);
+ PutUnsafe(os, static_cast<Ch>(codepoint & 0xFF));
+ }
+
+ template <typename InputStream>
+ static bool Decode(InputStream& is, unsigned* codepoint) {
+ uint8_t c = static_cast<uint8_t>(is.Take());
+ *codepoint = c;
+ return c <= 0X7F;
+ }
+
+ template <typename InputStream, typename OutputStream>
+ static bool Validate(InputStream& is, OutputStream& os) {
+ uint8_t c = static_cast<uint8_t>(is.Take());
+ os.Put(static_cast<typename OutputStream::Ch>(c));
+ return c <= 0x7F;
+ }
+
+ template <typename InputByteStream>
+ static CharType TakeBOM(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ uint8_t c = static_cast<uint8_t>(Take(is));
+ return static_cast<Ch>(c);
+ }
+
+ template <typename InputByteStream>
+ static Ch Take(InputByteStream& is) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename InputByteStream::Ch) == 1);
+ return static_cast<Ch>(is.Take());
+ }
+
+ template <typename OutputByteStream>
+ static void PutBOM(OutputByteStream& os) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ (void)os;
+ }
+
+ template <typename OutputByteStream>
+ static void Put(OutputByteStream& os, Ch c) {
+ RAPIDJSON_STATIC_ASSERT(sizeof(typename OutputByteStream::Ch) == 1);
+ os.Put(static_cast<typename OutputByteStream::Ch>(c));
+ }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// AutoUTF
+
+//! Runtime-specified UTF encoding type of a stream.
+enum UTFType {
+ kUTF8 = 0, //!< UTF-8.
+ kUTF16LE = 1, //!< UTF-16 little endian.
+ kUTF16BE = 2, //!< UTF-16 big endian.
+ kUTF32LE = 3, //!< UTF-32 little endian.
+ kUTF32BE = 4 //!< UTF-32 big endian.
+};
+
+//! Dynamically select encoding according to stream's runtime-specified UTF encoding type.
+/*! \note This class can be used with AutoUTFInputtStream and AutoUTFOutputStream, which provides GetType().
+*/
+template<typename CharType>
+struct AutoUTF {
+ typedef CharType Ch;
+
+ enum { supportUnicode = 1 };
+
+#define RAPIDJSON_ENCODINGS_FUNC(x) UTF8<Ch>::x, UTF16LE<Ch>::x, UTF16BE<Ch>::x, UTF32LE<Ch>::x, UTF32BE<Ch>::x
+
+ template<typename OutputStream>
+ RAPIDJSON_FORCEINLINE static void Encode(OutputStream& os, unsigned codepoint) {
+ typedef void (*EncodeFunc)(OutputStream&, unsigned);
+ static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Encode) };
+ (*f[os.GetType()])(os, codepoint);
+ }
+
+ template<typename OutputStream>
+ RAPIDJSON_FORCEINLINE static void EncodeUnsafe(OutputStream& os, unsigned codepoint) {
+ typedef void (*EncodeFunc)(OutputStream&, unsigned);
+ static const EncodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(EncodeUnsafe) };
+ (*f[os.GetType()])(os, codepoint);
+ }
+
+ template <typename InputStream>
+ RAPIDJSON_FORCEINLINE static bool Decode(InputStream& is, unsigned* codepoint) {
+ typedef bool (*DecodeFunc)(InputStream&, unsigned*);
+ static const DecodeFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Decode) };
+ return (*f[is.GetType()])(is, codepoint);
+ }
+
+ template <typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
+ typedef bool (*ValidateFunc)(InputStream&, OutputStream&);
+ static const ValidateFunc f[] = { RAPIDJSON_ENCODINGS_FUNC(Validate) };
+ return (*f[is.GetType()])(is, os);
+ }
+
+#undef RAPIDJSON_ENCODINGS_FUNC
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Transcoder
+
+//! Encoding conversion.
+template<typename SourceEncoding, typename TargetEncoding>
+struct Transcoder {
+ //! Take one Unicode codepoint from source encoding, convert it to target encoding and put it to the output stream.
+ template<typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
+ unsigned codepoint;
+ if (!SourceEncoding::Decode(is, &codepoint))
+ return false;
+ TargetEncoding::Encode(os, codepoint);
+ return true;
+ }
+
+ template<typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) {
+ unsigned codepoint;
+ if (!SourceEncoding::Decode(is, &codepoint))
+ return false;
+ TargetEncoding::EncodeUnsafe(os, codepoint);
+ return true;
+ }
+
+ //! Validate one Unicode codepoint from an encoded stream.
+ template<typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
+ return Transcode(is, os); // Since source/target encoding is different, must transcode.
+ }
+};
+
+// Forward declaration.
+template<typename Stream>
+inline void PutUnsafe(Stream& stream, typename Stream::Ch c);
+
+//! Specialization of Transcoder with same source and target encoding.
+template<typename Encoding>
+struct Transcoder<Encoding, Encoding> {
+ template<typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE static bool Transcode(InputStream& is, OutputStream& os) {
+ os.Put(is.Take()); // Just copy one code unit. This semantic is different from primary template class.
+ return true;
+ }
+
+ template<typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE static bool TranscodeUnsafe(InputStream& is, OutputStream& os) {
+ PutUnsafe(os, is.Take()); // Just copy one code unit. This semantic is different from primary template class.
+ return true;
+ }
+
+ template<typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE static bool Validate(InputStream& is, OutputStream& os) {
+ return Encoding::Validate(is, os); // source/target encoding are the same
+ }
+};
+
+RAPIDJSON_NAMESPACE_END
+
+#if defined(__GNUC__) || defined(_MSC_VER)
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_ENCODINGS_H_
diff --git a/include/rapidjson/error/en.h b/include/rapidjson/error/en.h
new file mode 100644
index 00000000..2db838bf
--- /dev/null
+++ b/include/rapidjson/error/en.h
@@ -0,0 +1,74 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_ERROR_EN_H_
+#define RAPIDJSON_ERROR_EN_H_
+
+#include "error.h"
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(switch-enum)
+RAPIDJSON_DIAG_OFF(covered-switch-default)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Maps error code of parsing into error message.
+/*!
+ \ingroup RAPIDJSON_ERRORS
+ \param parseErrorCode Error code obtained in parsing.
+ \return the error message.
+ \note User can make a copy of this function for localization.
+ Using switch-case is safer for future modification of error codes.
+*/
+inline const RAPIDJSON_ERROR_CHARTYPE* GetParseError_En(ParseErrorCode parseErrorCode) {
+ switch (parseErrorCode) {
+ case kParseErrorNone: return RAPIDJSON_ERROR_STRING("No error.");
+
+ case kParseErrorDocumentEmpty: return RAPIDJSON_ERROR_STRING("The document is empty.");
+ case kParseErrorDocumentRootNotSingular: return RAPIDJSON_ERROR_STRING("The document root must not be followed by other values.");
+
+ case kParseErrorValueInvalid: return RAPIDJSON_ERROR_STRING("Invalid value.");
+
+ case kParseErrorObjectMissName: return RAPIDJSON_ERROR_STRING("Missing a name for object member.");
+ case kParseErrorObjectMissColon: return RAPIDJSON_ERROR_STRING("Missing a colon after a name of object member.");
+ case kParseErrorObjectMissCommaOrCurlyBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or '}' after an object member.");
+
+ case kParseErrorArrayMissCommaOrSquareBracket: return RAPIDJSON_ERROR_STRING("Missing a comma or ']' after an array element.");
+
+ case kParseErrorStringUnicodeEscapeInvalidHex: return RAPIDJSON_ERROR_STRING("Incorrect hex digit after \\u escape in string.");
+ case kParseErrorStringUnicodeSurrogateInvalid: return RAPIDJSON_ERROR_STRING("The surrogate pair in string is invalid.");
+ case kParseErrorStringEscapeInvalid: return RAPIDJSON_ERROR_STRING("Invalid escape character in string.");
+ case kParseErrorStringMissQuotationMark: return RAPIDJSON_ERROR_STRING("Missing a closing quotation mark in string.");
+ case kParseErrorStringInvalidEncoding: return RAPIDJSON_ERROR_STRING("Invalid encoding in string.");
+
+ case kParseErrorNumberTooBig: return RAPIDJSON_ERROR_STRING("Number too big to be stored in double.");
+ case kParseErrorNumberMissFraction: return RAPIDJSON_ERROR_STRING("Miss fraction part in number.");
+ case kParseErrorNumberMissExponent: return RAPIDJSON_ERROR_STRING("Miss exponent in number.");
+
+ case kParseErrorTermination: return RAPIDJSON_ERROR_STRING("Terminate parsing due to Handler error.");
+ case kParseErrorUnspecificSyntaxError: return RAPIDJSON_ERROR_STRING("Unspecific syntax error.");
+
+ default: return RAPIDJSON_ERROR_STRING("Unknown error.");
+ }
+}
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_ERROR_EN_H_
diff --git a/include/rapidjson/error/error.h b/include/rapidjson/error/error.h
new file mode 100644
index 00000000..95cb31a7
--- /dev/null
+++ b/include/rapidjson/error/error.h
@@ -0,0 +1,155 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_ERROR_ERROR_H_
+#define RAPIDJSON_ERROR_ERROR_H_
+
+#include "../rapidjson.h"
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+#endif
+
+/*! \file error.h */
+
+/*! \defgroup RAPIDJSON_ERRORS RapidJSON error handling */
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_ERROR_CHARTYPE
+
+//! Character type of error messages.
+/*! \ingroup RAPIDJSON_ERRORS
+ The default character type is \c char.
+ On Windows, user can define this macro as \c TCHAR for supporting both
+ unicode/non-unicode settings.
+*/
+#ifndef RAPIDJSON_ERROR_CHARTYPE
+#define RAPIDJSON_ERROR_CHARTYPE char
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_ERROR_STRING
+
+//! Macro for converting string literial to \ref RAPIDJSON_ERROR_CHARTYPE[].
+/*! \ingroup RAPIDJSON_ERRORS
+ By default this conversion macro does nothing.
+ On Windows, user can define this macro as \c _T(x) for supporting both
+ unicode/non-unicode settings.
+*/
+#ifndef RAPIDJSON_ERROR_STRING
+#define RAPIDJSON_ERROR_STRING(x) x
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+///////////////////////////////////////////////////////////////////////////////
+// ParseErrorCode
+
+//! Error code of parsing.
+/*! \ingroup RAPIDJSON_ERRORS
+ \see GenericReader::Parse, GenericReader::GetParseErrorCode
+*/
+enum ParseErrorCode {
+ kParseErrorNone = 0, //!< No error.
+
+ kParseErrorDocumentEmpty, //!< The document is empty.
+ kParseErrorDocumentRootNotSingular, //!< The document root must not follow by other values.
+
+ kParseErrorValueInvalid, //!< Invalid value.
+
+ kParseErrorObjectMissName, //!< Missing a name for object member.
+ kParseErrorObjectMissColon, //!< Missing a colon after a name of object member.
+ kParseErrorObjectMissCommaOrCurlyBracket, //!< Missing a comma or '}' after an object member.
+
+ kParseErrorArrayMissCommaOrSquareBracket, //!< Missing a comma or ']' after an array element.
+
+ kParseErrorStringUnicodeEscapeInvalidHex, //!< Incorrect hex digit after \\u escape in string.
+ kParseErrorStringUnicodeSurrogateInvalid, //!< The surrogate pair in string is invalid.
+ kParseErrorStringEscapeInvalid, //!< Invalid escape character in string.
+ kParseErrorStringMissQuotationMark, //!< Missing a closing quotation mark in string.
+ kParseErrorStringInvalidEncoding, //!< Invalid encoding in string.
+
+ kParseErrorNumberTooBig, //!< Number too big to be stored in double.
+ kParseErrorNumberMissFraction, //!< Miss fraction part in number.
+ kParseErrorNumberMissExponent, //!< Miss exponent in number.
+
+ kParseErrorTermination, //!< Parsing was terminated.
+ kParseErrorUnspecificSyntaxError //!< Unspecific syntax error.
+};
+
+//! Result of parsing (wraps ParseErrorCode)
+/*!
+ \ingroup RAPIDJSON_ERRORS
+ \code
+ Document doc;
+ ParseResult ok = doc.Parse("[42]");
+ if (!ok) {
+ fprintf(stderr, "JSON parse error: %s (%u)",
+ GetParseError_En(ok.Code()), ok.Offset());
+ exit(EXIT_FAILURE);
+ }
+ \endcode
+ \see GenericReader::Parse, GenericDocument::Parse
+*/
+struct ParseResult {
+public:
+ //! Default constructor, no error.
+ ParseResult() : code_(kParseErrorNone), offset_(0) {}
+ //! Constructor to set an error.
+ ParseResult(ParseErrorCode code, size_t offset) : code_(code), offset_(offset) {}
+
+ //! Get the error code.
+ ParseErrorCode Code() const { return code_; }
+ //! Get the error offset, if \ref IsError(), 0 otherwise.
+ size_t Offset() const { return offset_; }
+
+ //! Conversion to \c bool, returns \c true, iff !\ref IsError().
+ operator bool() const { return !IsError(); }
+ //! Whether the result is an error.
+ bool IsError() const { return code_ != kParseErrorNone; }
+
+ bool operator==(const ParseResult& that) const { return code_ == that.code_; }
+ bool operator==(ParseErrorCode code) const { return code_ == code; }
+ friend bool operator==(ParseErrorCode code, const ParseResult & err) { return code == err.code_; }
+
+ //! Reset error code.
+ void Clear() { Set(kParseErrorNone); }
+ //! Update error code and offset.
+ void Set(ParseErrorCode code, size_t offset = 0) { code_ = code; offset_ = offset; }
+
+private:
+ ParseErrorCode code_;
+ size_t offset_;
+};
+
+//! Function pointer type of GetParseError().
+/*! \ingroup RAPIDJSON_ERRORS
+
+ This is the prototype for \c GetParseError_X(), where \c X is a locale.
+ User can dynamically change locale in runtime, e.g.:
+\code
+ GetParseErrorFunc GetParseError = GetParseError_En; // or whatever
+ const RAPIDJSON_ERROR_CHARTYPE* s = GetParseError(document.GetParseErrorCode());
+\endcode
+*/
+typedef const RAPIDJSON_ERROR_CHARTYPE* (*GetParseErrorFunc)(ParseErrorCode);
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_ERROR_ERROR_H_
diff --git a/include/rapidjson/filereadstream.h b/include/rapidjson/filereadstream.h
new file mode 100644
index 00000000..b56ea13b
--- /dev/null
+++ b/include/rapidjson/filereadstream.h
@@ -0,0 +1,99 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_FILEREADSTREAM_H_
+#define RAPIDJSON_FILEREADSTREAM_H_
+
+#include "stream.h"
+#include <cstdio>
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+RAPIDJSON_DIAG_OFF(unreachable-code)
+RAPIDJSON_DIAG_OFF(missing-noreturn)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! File byte stream for input using fread().
+/*!
+ \note implements Stream concept
+*/
+class FileReadStream {
+public:
+ typedef char Ch; //!< Character type (byte).
+
+ //! Constructor.
+ /*!
+ \param fp File pointer opened for read.
+ \param buffer user-supplied buffer.
+ \param bufferSize size of buffer in bytes. Must >=4 bytes.
+ */
+ FileReadStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferSize_(bufferSize), bufferLast_(0), current_(buffer_), readCount_(0), count_(0), eof_(false) {
+ RAPIDJSON_ASSERT(fp_ != 0);
+ RAPIDJSON_ASSERT(bufferSize >= 4);
+ Read();
+ }
+
+ Ch Peek() const { return *current_; }
+ Ch Take() { Ch c = *current_; Read(); return c; }
+ size_t Tell() const { return count_ + static_cast<size_t>(current_ - buffer_); }
+
+ // Not implemented
+ void Put(Ch) { RAPIDJSON_ASSERT(false); }
+ void Flush() { RAPIDJSON_ASSERT(false); }
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+ // For encoding detection only.
+ const Ch* Peek4() const {
+ return (current_ + 4 <= bufferLast_) ? current_ : 0;
+ }
+
+private:
+ void Read() {
+ if (current_ < bufferLast_)
+ ++current_;
+ else if (!eof_) {
+ count_ += readCount_;
+ readCount_ = fread(buffer_, 1, bufferSize_, fp_);
+ bufferLast_ = buffer_ + readCount_ - 1;
+ current_ = buffer_;
+
+ if (readCount_ < bufferSize_) {
+ buffer_[readCount_] = '\0';
+ ++bufferLast_;
+ eof_ = true;
+ }
+ }
+ }
+
+ std::FILE* fp_;
+ Ch *buffer_;
+ size_t bufferSize_;
+ Ch *bufferLast_;
+ Ch *current_;
+ size_t readCount_;
+ size_t count_; //!< Number of characters read
+ bool eof_;
+};
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_FILESTREAM_H_
diff --git a/include/rapidjson/filewritestream.h b/include/rapidjson/filewritestream.h
new file mode 100644
index 00000000..6378dd60
--- /dev/null
+++ b/include/rapidjson/filewritestream.h
@@ -0,0 +1,104 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_FILEWRITESTREAM_H_
+#define RAPIDJSON_FILEWRITESTREAM_H_
+
+#include "stream.h"
+#include <cstdio>
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(unreachable-code)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Wrapper of C file stream for input using fread().
+/*!
+ \note implements Stream concept
+*/
+class FileWriteStream {
+public:
+ typedef char Ch; //!< Character type. Only support char.
+
+ FileWriteStream(std::FILE* fp, char* buffer, size_t bufferSize) : fp_(fp), buffer_(buffer), bufferEnd_(buffer + bufferSize), current_(buffer_) {
+ RAPIDJSON_ASSERT(fp_ != 0);
+ }
+
+ void Put(char c) {
+ if (current_ >= bufferEnd_)
+ Flush();
+
+ *current_++ = c;
+ }
+
+ void PutN(char c, size_t n) {
+ size_t avail = static_cast<size_t>(bufferEnd_ - current_);
+ while (n > avail) {
+ std::memset(current_, c, avail);
+ current_ += avail;
+ Flush();
+ n -= avail;
+ avail = static_cast<size_t>(bufferEnd_ - current_);
+ }
+
+ if (n > 0) {
+ std::memset(current_, c, n);
+ current_ += n;
+ }
+ }
+
+ void Flush() {
+ if (current_ != buffer_) {
+ size_t result = fwrite(buffer_, 1, static_cast<size_t>(current_ - buffer_), fp_);
+ if (result < static_cast<size_t>(current_ - buffer_)) {
+ // failure deliberately ignored at this time
+ // added to avoid warn_unused_result build errors
+ }
+ current_ = buffer_;
+ }
+ }
+
+ // Not implemented
+ char Peek() const { RAPIDJSON_ASSERT(false); return 0; }
+ char Take() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
+ char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; }
+
+private:
+ // Prohibit copy constructor & assignment operator.
+ FileWriteStream(const FileWriteStream&);
+ FileWriteStream& operator=(const FileWriteStream&);
+
+ std::FILE* fp_;
+ char *buffer_;
+ char *bufferEnd_;
+ char *current_;
+};
+
+//! Implement specialized version of PutN() with memset() for better performance.
+template<>
+inline void PutN(FileWriteStream& stream, char c, size_t n) {
+ stream.PutN(c, n);
+}
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_FILESTREAM_H_
diff --git a/include/rapidjson/fwd.h b/include/rapidjson/fwd.h
new file mode 100644
index 00000000..e8104e84
--- /dev/null
+++ b/include/rapidjson/fwd.h
@@ -0,0 +1,151 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_FWD_H_
+#define RAPIDJSON_FWD_H_
+
+#include "rapidjson.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+// encodings.h
+
+template<typename CharType> struct UTF8;
+template<typename CharType> struct UTF16;
+template<typename CharType> struct UTF16BE;
+template<typename CharType> struct UTF16LE;
+template<typename CharType> struct UTF32;
+template<typename CharType> struct UTF32BE;
+template<typename CharType> struct UTF32LE;
+template<typename CharType> struct ASCII;
+template<typename CharType> struct AutoUTF;
+
+template<typename SourceEncoding, typename TargetEncoding>
+struct Transcoder;
+
+// allocators.h
+
+class CrtAllocator;
+
+template <typename BaseAllocator>
+class MemoryPoolAllocator;
+
+// stream.h
+
+template <typename Encoding>
+struct GenericStringStream;
+
+typedef GenericStringStream<UTF8<char> > StringStream;
+
+template <typename Encoding>
+struct GenericInsituStringStream;
+
+typedef GenericInsituStringStream<UTF8<char> > InsituStringStream;
+
+// stringbuffer.h
+
+template <typename Encoding, typename Allocator>
+class GenericStringBuffer;
+
+typedef GenericStringBuffer<UTF8<char>, CrtAllocator> StringBuffer;
+
+// filereadstream.h
+
+class FileReadStream;
+
+// filewritestream.h
+
+class FileWriteStream;
+
+// memorybuffer.h
+
+template <typename Allocator>
+struct GenericMemoryBuffer;
+
+typedef GenericMemoryBuffer<CrtAllocator> MemoryBuffer;
+
+// memorystream.h
+
+struct MemoryStream;
+
+// reader.h
+
+template<typename Encoding, typename Derived>
+struct BaseReaderHandler;
+
+template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator>
+class GenericReader;
+
+typedef GenericReader<UTF8<char>, UTF8<char>, CrtAllocator> Reader;
+
+// writer.h
+
+template<typename OutputStream, typename SourceEncoding, typename TargetEncoding, typename StackAllocator, unsigned writeFlags>
+class Writer;
+
+// prettywriter.h
+
+template<typename OutputStream, typename SourceEncoding, typename TargetEncoding, typename StackAllocator, unsigned writeFlags>
+class PrettyWriter;
+
+// document.h
+
+template <typename Encoding, typename Allocator>
+struct GenericMember;
+
+template <bool Const, typename Encoding, typename Allocator>
+class GenericMemberIterator;
+
+template<typename CharType>
+struct GenericStringRef;
+
+template <typename Encoding, typename Allocator>
+class GenericValue;
+
+typedef GenericValue<UTF8<char>, MemoryPoolAllocator<CrtAllocator> > Value;
+
+template <typename Encoding, typename Allocator, typename StackAllocator>
+class GenericDocument;
+
+typedef GenericDocument<UTF8<char>, MemoryPoolAllocator<CrtAllocator>, CrtAllocator> Document;
+
+// pointer.h
+
+template <typename ValueType, typename Allocator>
+class GenericPointer;
+
+typedef GenericPointer<Value, CrtAllocator> Pointer;
+
+// schema.h
+
+template <typename SchemaDocumentType>
+class IGenericRemoteSchemaDocumentProvider;
+
+template <typename ValueT, typename Allocator>
+class GenericSchemaDocument;
+
+typedef GenericSchemaDocument<Value, CrtAllocator> SchemaDocument;
+typedef IGenericRemoteSchemaDocumentProvider<SchemaDocument> IRemoteSchemaDocumentProvider;
+
+template <
+ typename SchemaDocumentType,
+ typename OutputHandler,
+ typename StateAllocator>
+class GenericSchemaValidator;
+
+typedef GenericSchemaValidator<SchemaDocument, BaseReaderHandler<UTF8<char>, void>, CrtAllocator> SchemaValidator;
+
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_RAPIDJSONFWD_H_
diff --git a/include/rapidjson/internal/biginteger.h b/include/rapidjson/internal/biginteger.h
new file mode 100644
index 00000000..9d3e88c9
--- /dev/null
+++ b/include/rapidjson/internal/biginteger.h
@@ -0,0 +1,290 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_BIGINTEGER_H_
+#define RAPIDJSON_BIGINTEGER_H_
+
+#include "../rapidjson.h"
+
+#if defined(_MSC_VER) && defined(_M_AMD64)
+#include <intrin.h> // for _umul128
+#pragma intrinsic(_umul128)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+class BigInteger {
+public:
+ typedef uint64_t Type;
+
+ BigInteger(const BigInteger& rhs) : count_(rhs.count_) {
+ std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
+ }
+
+ explicit BigInteger(uint64_t u) : count_(1) {
+ digits_[0] = u;
+ }
+
+ BigInteger(const char* decimals, size_t length) : count_(1) {
+ RAPIDJSON_ASSERT(length > 0);
+ digits_[0] = 0;
+ size_t i = 0;
+ const size_t kMaxDigitPerIteration = 19; // 2^64 = 18446744073709551616 > 10^19
+ while (length >= kMaxDigitPerIteration) {
+ AppendDecimal64(decimals + i, decimals + i + kMaxDigitPerIteration);
+ length -= kMaxDigitPerIteration;
+ i += kMaxDigitPerIteration;
+ }
+
+ if (length > 0)
+ AppendDecimal64(decimals + i, decimals + i + length);
+ }
+
+ BigInteger& operator=(const BigInteger &rhs)
+ {
+ if (this != &rhs) {
+ count_ = rhs.count_;
+ std::memcpy(digits_, rhs.digits_, count_ * sizeof(Type));
+ }
+ return *this;
+ }
+
+ BigInteger& operator=(uint64_t u) {
+ digits_[0] = u;
+ count_ = 1;
+ return *this;
+ }
+
+ BigInteger& operator+=(uint64_t u) {
+ Type backup = digits_[0];
+ digits_[0] += u;
+ for (size_t i = 0; i < count_ - 1; i++) {
+ if (digits_[i] >= backup)
+ return *this; // no carry
+ backup = digits_[i + 1];
+ digits_[i + 1] += 1;
+ }
+
+ // Last carry
+ if (digits_[count_ - 1] < backup)
+ PushBack(1);
+
+ return *this;
+ }
+
+ BigInteger& operator*=(uint64_t u) {
+ if (u == 0) return *this = 0;
+ if (u == 1) return *this;
+ if (*this == 1) return *this = u;
+
+ uint64_t k = 0;
+ for (size_t i = 0; i < count_; i++) {
+ uint64_t hi;
+ digits_[i] = MulAdd64(digits_[i], u, k, &hi);
+ k = hi;
+ }
+
+ if (k > 0)
+ PushBack(k);
+
+ return *this;
+ }
+
+ BigInteger& operator*=(uint32_t u) {
+ if (u == 0) return *this = 0;
+ if (u == 1) return *this;
+ if (*this == 1) return *this = u;
+
+ uint64_t k = 0;
+ for (size_t i = 0; i < count_; i++) {
+ const uint64_t c = digits_[i] >> 32;
+ const uint64_t d = digits_[i] & 0xFFFFFFFF;
+ const uint64_t uc = u * c;
+ const uint64_t ud = u * d;
+ const uint64_t p0 = ud + k;
+ const uint64_t p1 = uc + (p0 >> 32);
+ digits_[i] = (p0 & 0xFFFFFFFF) | (p1 << 32);
+ k = p1 >> 32;
+ }
+
+ if (k > 0)
+ PushBack(k);
+
+ return *this;
+ }
+
+ BigInteger& operator<<=(size_t shift) {
+ if (IsZero() || shift == 0) return *this;
+
+ size_t offset = shift / kTypeBit;
+ size_t interShift = shift % kTypeBit;
+ RAPIDJSON_ASSERT(count_ + offset <= kCapacity);
+
+ if (interShift == 0) {
+ std::memmove(&digits_[count_ - 1 + offset], &digits_[count_ - 1], count_ * sizeof(Type));
+ count_ += offset;
+ }
+ else {
+ digits_[count_] = 0;
+ for (size_t i = count_; i > 0; i--)
+ digits_[i + offset] = (digits_[i] << interShift) | (digits_[i - 1] >> (kTypeBit - interShift));
+ digits_[offset] = digits_[0] << interShift;
+ count_ += offset;
+ if (digits_[count_])
+ count_++;
+ }
+
+ std::memset(digits_, 0, offset * sizeof(Type));
+
+ return *this;
+ }
+
+ bool operator==(const BigInteger& rhs) const {
+ return count_ == rhs.count_ && std::memcmp(digits_, rhs.digits_, count_ * sizeof(Type)) == 0;
+ }
+
+ bool operator==(const Type rhs) const {
+ return count_ == 1 && digits_[0] == rhs;
+ }
+
+ BigInteger& MultiplyPow5(unsigned exp) {
+ static const uint32_t kPow5[12] = {
+ 5,
+ 5 * 5,
+ 5 * 5 * 5,
+ 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5,
+ 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
+ };
+ if (exp == 0) return *this;
+ for (; exp >= 27; exp -= 27) *this *= RAPIDJSON_UINT64_C2(0X6765C793, 0XFA10079D); // 5^27
+ for (; exp >= 13; exp -= 13) *this *= static_cast<uint32_t>(1220703125u); // 5^13
+ if (exp > 0) *this *= kPow5[exp - 1];
+ return *this;
+ }
+
+ // Compute absolute difference of this and rhs.
+ // Assume this != rhs
+ bool Difference(const BigInteger& rhs, BigInteger* out) const {
+ int cmp = Compare(rhs);
+ RAPIDJSON_ASSERT(cmp != 0);
+ const BigInteger *a, *b; // Makes a > b
+ bool ret;
+ if (cmp < 0) { a = &rhs; b = this; ret = true; }
+ else { a = this; b = &rhs; ret = false; }
+
+ Type borrow = 0;
+ for (size_t i = 0; i < a->count_; i++) {
+ Type d = a->digits_[i] - borrow;
+ if (i < b->count_)
+ d -= b->digits_[i];
+ borrow = (d > a->digits_[i]) ? 1 : 0;
+ out->digits_[i] = d;
+ if (d != 0)
+ out->count_ = i + 1;
+ }
+
+ return ret;
+ }
+
+ int Compare(const BigInteger& rhs) const {
+ if (count_ != rhs.count_)
+ return count_ < rhs.count_ ? -1 : 1;
+
+ for (size_t i = count_; i-- > 0;)
+ if (digits_[i] != rhs.digits_[i])
+ return digits_[i] < rhs.digits_[i] ? -1 : 1;
+
+ return 0;
+ }
+
+ size_t GetCount() const { return count_; }
+ Type GetDigit(size_t index) const { RAPIDJSON_ASSERT(index < count_); return digits_[index]; }
+ bool IsZero() const { return count_ == 1 && digits_[0] == 0; }
+
+private:
+ void AppendDecimal64(const char* begin, const char* end) {
+ uint64_t u = ParseUint64(begin, end);
+ if (IsZero())
+ *this = u;
+ else {
+ unsigned exp = static_cast<unsigned>(end - begin);
+ (MultiplyPow5(exp) <<= exp) += u; // *this = *this * 10^exp + u
+ }
+ }
+
+ void PushBack(Type digit) {
+ RAPIDJSON_ASSERT(count_ < kCapacity);
+ digits_[count_++] = digit;
+ }
+
+ static uint64_t ParseUint64(const char* begin, const char* end) {
+ uint64_t r = 0;
+ for (const char* p = begin; p != end; ++p) {
+ RAPIDJSON_ASSERT(*p >= '0' && *p <= '9');
+ r = r * 10u + static_cast<unsigned>(*p - '0');
+ }
+ return r;
+ }
+
+ // Assume a * b + k < 2^128
+ static uint64_t MulAdd64(uint64_t a, uint64_t b, uint64_t k, uint64_t* outHigh) {
+#if defined(_MSC_VER) && defined(_M_AMD64)
+ uint64_t low = _umul128(a, b, outHigh) + k;
+ if (low < k)
+ (*outHigh)++;
+ return low;
+#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__)
+ __extension__ typedef unsigned __int128 uint128;
+ uint128 p = static_cast<uint128>(a) * static_cast<uint128>(b);
+ p += k;
+ *outHigh = static_cast<uint64_t>(p >> 64);
+ return static_cast<uint64_t>(p);
+#else
+ const uint64_t a0 = a & 0xFFFFFFFF, a1 = a >> 32, b0 = b & 0xFFFFFFFF, b1 = b >> 32;
+ uint64_t x0 = a0 * b0, x1 = a0 * b1, x2 = a1 * b0, x3 = a1 * b1;
+ x1 += (x0 >> 32); // can't give carry
+ x1 += x2;
+ if (x1 < x2)
+ x3 += (static_cast<uint64_t>(1) << 32);
+ uint64_t lo = (x1 << 32) + (x0 & 0xFFFFFFFF);
+ uint64_t hi = x3 + (x1 >> 32);
+
+ lo += k;
+ if (lo < k)
+ hi++;
+ *outHigh = hi;
+ return lo;
+#endif
+ }
+
+ static const size_t kBitCount = 3328; // 64bit * 54 > 10^1000
+ static const size_t kCapacity = kBitCount / sizeof(Type);
+ static const size_t kTypeBit = sizeof(Type) * 8;
+
+ Type digits_[kCapacity];
+ size_t count_;
+};
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_BIGINTEGER_H_
diff --git a/include/rapidjson/internal/diyfp.h b/include/rapidjson/internal/diyfp.h
new file mode 100644
index 00000000..c9fefdc6
--- /dev/null
+++ b/include/rapidjson/internal/diyfp.h
@@ -0,0 +1,258 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+// This is a C++ header-only implementation of Grisu2 algorithm from the publication:
+// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with
+// integers." ACM Sigplan Notices 45.6 (2010): 233-243.
+
+#ifndef RAPIDJSON_DIYFP_H_
+#define RAPIDJSON_DIYFP_H_
+
+#include "../rapidjson.h"
+
+#if defined(_MSC_VER) && defined(_M_AMD64)
+#include <intrin.h>
+#pragma intrinsic(_BitScanReverse64)
+#pragma intrinsic(_umul128)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+#endif
+
+struct DiyFp {
+ DiyFp() : f(), e() {}
+
+ DiyFp(uint64_t fp, int exp) : f(fp), e(exp) {}
+
+ explicit DiyFp(double d) {
+ union {
+ double d;
+ uint64_t u64;
+ } u = { d };
+
+ int biased_e = static_cast<int>((u.u64 & kDpExponentMask) >> kDpSignificandSize);
+ uint64_t significand = (u.u64 & kDpSignificandMask);
+ if (biased_e != 0) {
+ f = significand + kDpHiddenBit;
+ e = biased_e - kDpExponentBias;
+ }
+ else {
+ f = significand;
+ e = kDpMinExponent + 1;
+ }
+ }
+
+ DiyFp operator-(const DiyFp& rhs) const {
+ return DiyFp(f - rhs.f, e);
+ }
+
+ DiyFp operator*(const DiyFp& rhs) const {
+#if defined(_MSC_VER) && defined(_M_AMD64)
+ uint64_t h;
+ uint64_t l = _umul128(f, rhs.f, &h);
+ if (l & (uint64_t(1) << 63)) // rounding
+ h++;
+ return DiyFp(h, e + rhs.e + 64);
+#elif (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6)) && defined(__x86_64__)
+ __extension__ typedef unsigned __int128 uint128;
+ uint128 p = static_cast<uint128>(f) * static_cast<uint128>(rhs.f);
+ uint64_t h = static_cast<uint64_t>(p >> 64);
+ uint64_t l = static_cast<uint64_t>(p);
+ if (l & (uint64_t(1) << 63)) // rounding
+ h++;
+ return DiyFp(h, e + rhs.e + 64);
+#else
+ const uint64_t M32 = 0xFFFFFFFF;
+ const uint64_t a = f >> 32;
+ const uint64_t b = f & M32;
+ const uint64_t c = rhs.f >> 32;
+ const uint64_t d = rhs.f & M32;
+ const uint64_t ac = a * c;
+ const uint64_t bc = b * c;
+ const uint64_t ad = a * d;
+ const uint64_t bd = b * d;
+ uint64_t tmp = (bd >> 32) + (ad & M32) + (bc & M32);
+ tmp += 1U << 31; /// mult_round
+ return DiyFp(ac + (ad >> 32) + (bc >> 32) + (tmp >> 32), e + rhs.e + 64);
+#endif
+ }
+
+ DiyFp Normalize() const {
+#if defined(_MSC_VER) && defined(_M_AMD64)
+ unsigned long index;
+ _BitScanReverse64(&index, f);
+ return DiyFp(f << (63 - index), e - (63 - index));
+#elif defined(__GNUC__) && __GNUC__ >= 4
+ int s = __builtin_clzll(f);
+ return DiyFp(f << s, e - s);
+#else
+ DiyFp res = *this;
+ while (!(res.f & (static_cast<uint64_t>(1) << 63))) {
+ res.f <<= 1;
+ res.e--;
+ }
+ return res;
+#endif
+ }
+
+ DiyFp NormalizeBoundary() const {
+ DiyFp res = *this;
+ while (!(res.f & (kDpHiddenBit << 1))) {
+ res.f <<= 1;
+ res.e--;
+ }
+ res.f <<= (kDiySignificandSize - kDpSignificandSize - 2);
+ res.e = res.e - (kDiySignificandSize - kDpSignificandSize - 2);
+ return res;
+ }
+
+ void NormalizedBoundaries(DiyFp* minus, DiyFp* plus) const {
+ DiyFp pl = DiyFp((f << 1) + 1, e - 1).NormalizeBoundary();
+ DiyFp mi = (f == kDpHiddenBit) ? DiyFp((f << 2) - 1, e - 2) : DiyFp((f << 1) - 1, e - 1);
+ mi.f <<= mi.e - pl.e;
+ mi.e = pl.e;
+ *plus = pl;
+ *minus = mi;
+ }
+
+ double ToDouble() const {
+ union {
+ double d;
+ uint64_t u64;
+ }u;
+ const uint64_t be = (e == kDpDenormalExponent && (f & kDpHiddenBit) == 0) ? 0 :
+ static_cast<uint64_t>(e + kDpExponentBias);
+ u.u64 = (f & kDpSignificandMask) | (be << kDpSignificandSize);
+ return u.d;
+ }
+
+ static const int kDiySignificandSize = 64;
+ static const int kDpSignificandSize = 52;
+ static const int kDpExponentBias = 0x3FF + kDpSignificandSize;
+ static const int kDpMaxExponent = 0x7FF - kDpExponentBias;
+ static const int kDpMinExponent = -kDpExponentBias;
+ static const int kDpDenormalExponent = -kDpExponentBias + 1;
+ static const uint64_t kDpExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000);
+ static const uint64_t kDpSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF);
+ static const uint64_t kDpHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000);
+
+ uint64_t f;
+ int e;
+};
+
+inline DiyFp GetCachedPowerByIndex(size_t index) {
+ // 10^-348, 10^-340, ..., 10^340
+ static const uint64_t kCachedPowers_F[] = {
+ RAPIDJSON_UINT64_C2(0xfa8fd5a0, 0x081c0288), RAPIDJSON_UINT64_C2(0xbaaee17f, 0xa23ebf76),
+ RAPIDJSON_UINT64_C2(0x8b16fb20, 0x3055ac76), RAPIDJSON_UINT64_C2(0xcf42894a, 0x5dce35ea),
+ RAPIDJSON_UINT64_C2(0x9a6bb0aa, 0x55653b2d), RAPIDJSON_UINT64_C2(0xe61acf03, 0x3d1a45df),
+ RAPIDJSON_UINT64_C2(0xab70fe17, 0xc79ac6ca), RAPIDJSON_UINT64_C2(0xff77b1fc, 0xbebcdc4f),
+ RAPIDJSON_UINT64_C2(0xbe5691ef, 0x416bd60c), RAPIDJSON_UINT64_C2(0x8dd01fad, 0x907ffc3c),
+ RAPIDJSON_UINT64_C2(0xd3515c28, 0x31559a83), RAPIDJSON_UINT64_C2(0x9d71ac8f, 0xada6c9b5),
+ RAPIDJSON_UINT64_C2(0xea9c2277, 0x23ee8bcb), RAPIDJSON_UINT64_C2(0xaecc4991, 0x4078536d),
+ RAPIDJSON_UINT64_C2(0x823c1279, 0x5db6ce57), RAPIDJSON_UINT64_C2(0xc2109436, 0x4dfb5637),
+ RAPIDJSON_UINT64_C2(0x9096ea6f, 0x3848984f), RAPIDJSON_UINT64_C2(0xd77485cb, 0x25823ac7),
+ RAPIDJSON_UINT64_C2(0xa086cfcd, 0x97bf97f4), RAPIDJSON_UINT64_C2(0xef340a98, 0x172aace5),
+ RAPIDJSON_UINT64_C2(0xb23867fb, 0x2a35b28e), RAPIDJSON_UINT64_C2(0x84c8d4df, 0xd2c63f3b),
+ RAPIDJSON_UINT64_C2(0xc5dd4427, 0x1ad3cdba), RAPIDJSON_UINT64_C2(0x936b9fce, 0xbb25c996),
+ RAPIDJSON_UINT64_C2(0xdbac6c24, 0x7d62a584), RAPIDJSON_UINT64_C2(0xa3ab6658, 0x0d5fdaf6),
+ RAPIDJSON_UINT64_C2(0xf3e2f893, 0xdec3f126), RAPIDJSON_UINT64_C2(0xb5b5ada8, 0xaaff80b8),
+ RAPIDJSON_UINT64_C2(0x87625f05, 0x6c7c4a8b), RAPIDJSON_UINT64_C2(0xc9bcff60, 0x34c13053),
+ RAPIDJSON_UINT64_C2(0x964e858c, 0x91ba2655), RAPIDJSON_UINT64_C2(0xdff97724, 0x70297ebd),
+ RAPIDJSON_UINT64_C2(0xa6dfbd9f, 0xb8e5b88f), RAPIDJSON_UINT64_C2(0xf8a95fcf, 0x88747d94),
+ RAPIDJSON_UINT64_C2(0xb9447093, 0x8fa89bcf), RAPIDJSON_UINT64_C2(0x8a08f0f8, 0xbf0f156b),
+ RAPIDJSON_UINT64_C2(0xcdb02555, 0x653131b6), RAPIDJSON_UINT64_C2(0x993fe2c6, 0xd07b7fac),
+ RAPIDJSON_UINT64_C2(0xe45c10c4, 0x2a2b3b06), RAPIDJSON_UINT64_C2(0xaa242499, 0x697392d3),
+ RAPIDJSON_UINT64_C2(0xfd87b5f2, 0x8300ca0e), RAPIDJSON_UINT64_C2(0xbce50864, 0x92111aeb),
+ RAPIDJSON_UINT64_C2(0x8cbccc09, 0x6f5088cc), RAPIDJSON_UINT64_C2(0xd1b71758, 0xe219652c),
+ RAPIDJSON_UINT64_C2(0x9c400000, 0x00000000), RAPIDJSON_UINT64_C2(0xe8d4a510, 0x00000000),
+ RAPIDJSON_UINT64_C2(0xad78ebc5, 0xac620000), RAPIDJSON_UINT64_C2(0x813f3978, 0xf8940984),
+ RAPIDJSON_UINT64_C2(0xc097ce7b, 0xc90715b3), RAPIDJSON_UINT64_C2(0x8f7e32ce, 0x7bea5c70),
+ RAPIDJSON_UINT64_C2(0xd5d238a4, 0xabe98068), RAPIDJSON_UINT64_C2(0x9f4f2726, 0x179a2245),
+ RAPIDJSON_UINT64_C2(0xed63a231, 0xd4c4fb27), RAPIDJSON_UINT64_C2(0xb0de6538, 0x8cc8ada8),
+ RAPIDJSON_UINT64_C2(0x83c7088e, 0x1aab65db), RAPIDJSON_UINT64_C2(0xc45d1df9, 0x42711d9a),
+ RAPIDJSON_UINT64_C2(0x924d692c, 0xa61be758), RAPIDJSON_UINT64_C2(0xda01ee64, 0x1a708dea),
+ RAPIDJSON_UINT64_C2(0xa26da399, 0x9aef774a), RAPIDJSON_UINT64_C2(0xf209787b, 0xb47d6b85),
+ RAPIDJSON_UINT64_C2(0xb454e4a1, 0x79dd1877), RAPIDJSON_UINT64_C2(0x865b8692, 0x5b9bc5c2),
+ RAPIDJSON_UINT64_C2(0xc83553c5, 0xc8965d3d), RAPIDJSON_UINT64_C2(0x952ab45c, 0xfa97a0b3),
+ RAPIDJSON_UINT64_C2(0xde469fbd, 0x99a05fe3), RAPIDJSON_UINT64_C2(0xa59bc234, 0xdb398c25),
+ RAPIDJSON_UINT64_C2(0xf6c69a72, 0xa3989f5c), RAPIDJSON_UINT64_C2(0xb7dcbf53, 0x54e9bece),
+ RAPIDJSON_UINT64_C2(0x88fcf317, 0xf22241e2), RAPIDJSON_UINT64_C2(0xcc20ce9b, 0xd35c78a5),
+ RAPIDJSON_UINT64_C2(0x98165af3, 0x7b2153df), RAPIDJSON_UINT64_C2(0xe2a0b5dc, 0x971f303a),
+ RAPIDJSON_UINT64_C2(0xa8d9d153, 0x5ce3b396), RAPIDJSON_UINT64_C2(0xfb9b7cd9, 0xa4a7443c),
+ RAPIDJSON_UINT64_C2(0xbb764c4c, 0xa7a44410), RAPIDJSON_UINT64_C2(0x8bab8eef, 0xb6409c1a),
+ RAPIDJSON_UINT64_C2(0xd01fef10, 0xa657842c), RAPIDJSON_UINT64_C2(0x9b10a4e5, 0xe9913129),
+ RAPIDJSON_UINT64_C2(0xe7109bfb, 0xa19c0c9d), RAPIDJSON_UINT64_C2(0xac2820d9, 0x623bf429),
+ RAPIDJSON_UINT64_C2(0x80444b5e, 0x7aa7cf85), RAPIDJSON_UINT64_C2(0xbf21e440, 0x03acdd2d),
+ RAPIDJSON_UINT64_C2(0x8e679c2f, 0x5e44ff8f), RAPIDJSON_UINT64_C2(0xd433179d, 0x9c8cb841),
+ RAPIDJSON_UINT64_C2(0x9e19db92, 0xb4e31ba9), RAPIDJSON_UINT64_C2(0xeb96bf6e, 0xbadf77d9),
+ RAPIDJSON_UINT64_C2(0xaf87023b, 0x9bf0ee6b)
+ };
+ static const int16_t kCachedPowers_E[] = {
+ -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980,
+ -954, -927, -901, -874, -847, -821, -794, -768, -741, -715,
+ -688, -661, -635, -608, -582, -555, -529, -502, -475, -449,
+ -422, -396, -369, -343, -316, -289, -263, -236, -210, -183,
+ -157, -130, -103, -77, -50, -24, 3, 30, 56, 83,
+ 109, 136, 162, 189, 216, 242, 269, 295, 322, 348,
+ 375, 402, 428, 455, 481, 508, 534, 561, 588, 614,
+ 641, 667, 694, 720, 747, 774, 800, 827, 853, 880,
+ 907, 933, 960, 986, 1013, 1039, 1066
+ };
+ return DiyFp(kCachedPowers_F[index], kCachedPowers_E[index]);
+}
+
+inline DiyFp GetCachedPower(int e, int* K) {
+
+ //int k = static_cast<int>(ceil((-61 - e) * 0.30102999566398114)) + 374;
+ double dk = (-61 - e) * 0.30102999566398114 + 347; // dk must be positive, so can do ceiling in positive
+ int k = static_cast<int>(dk);
+ if (dk - k > 0.0)
+ k++;
+
+ unsigned index = static_cast<unsigned>((k >> 3) + 1);
+ *K = -(-348 + static_cast<int>(index << 3)); // decimal exponent no need lookup table
+
+ return GetCachedPowerByIndex(index);
+}
+
+inline DiyFp GetCachedPower10(int exp, int *outExp) {
+ unsigned index = (static_cast<unsigned>(exp) + 348u) / 8u;
+ *outExp = -348 + static_cast<int>(index) * 8;
+ return GetCachedPowerByIndex(index);
+ }
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_POP
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+RAPIDJSON_DIAG_OFF(padded)
+#endif
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_DIYFP_H_
diff --git a/include/rapidjson/internal/dtoa.h b/include/rapidjson/internal/dtoa.h
new file mode 100644
index 00000000..8d6350e6
--- /dev/null
+++ b/include/rapidjson/internal/dtoa.h
@@ -0,0 +1,245 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+// This is a C++ header-only implementation of Grisu2 algorithm from the publication:
+// Loitsch, Florian. "Printing floating-point numbers quickly and accurately with
+// integers." ACM Sigplan Notices 45.6 (2010): 233-243.
+
+#ifndef RAPIDJSON_DTOA_
+#define RAPIDJSON_DTOA_
+
+#include "itoa.h" // GetDigitsLut()
+#include "diyfp.h"
+#include "ieee754.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+RAPIDJSON_DIAG_OFF(array-bounds) // some gcc versions generate wrong warnings https://gcc.gnu.org/bugzilla/show_bug.cgi?id=59124
+#endif
+
+inline void GrisuRound(char* buffer, int len, uint64_t delta, uint64_t rest, uint64_t ten_kappa, uint64_t wp_w) {
+ while (rest < wp_w && delta - rest >= ten_kappa &&
+ (rest + ten_kappa < wp_w || /// closer
+ wp_w - rest > rest + ten_kappa - wp_w)) {
+ buffer[len - 1]--;
+ rest += ten_kappa;
+ }
+}
+
+inline unsigned CountDecimalDigit32(uint32_t n) {
+ // Simple pure C++ implementation was faster than __builtin_clz version in this situation.
+ if (n < 10) return 1;
+ if (n < 100) return 2;
+ if (n < 1000) return 3;
+ if (n < 10000) return 4;
+ if (n < 100000) return 5;
+ if (n < 1000000) return 6;
+ if (n < 10000000) return 7;
+ if (n < 100000000) return 8;
+ // Will not reach 10 digits in DigitGen()
+ //if (n < 1000000000) return 9;
+ //return 10;
+ return 9;
+}
+
+inline void DigitGen(const DiyFp& W, const DiyFp& Mp, uint64_t delta, char* buffer, int* len, int* K) {
+ static const uint32_t kPow10[] = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 };
+ const DiyFp one(uint64_t(1) << -Mp.e, Mp.e);
+ const DiyFp wp_w = Mp - W;
+ uint32_t p1 = static_cast<uint32_t>(Mp.f >> -one.e);
+ uint64_t p2 = Mp.f & (one.f - 1);
+ unsigned kappa = CountDecimalDigit32(p1); // kappa in [0, 9]
+ *len = 0;
+
+ while (kappa > 0) {
+ uint32_t d = 0;
+ switch (kappa) {
+ case 9: d = p1 / 100000000; p1 %= 100000000; break;
+ case 8: d = p1 / 10000000; p1 %= 10000000; break;
+ case 7: d = p1 / 1000000; p1 %= 1000000; break;
+ case 6: d = p1 / 100000; p1 %= 100000; break;
+ case 5: d = p1 / 10000; p1 %= 10000; break;
+ case 4: d = p1 / 1000; p1 %= 1000; break;
+ case 3: d = p1 / 100; p1 %= 100; break;
+ case 2: d = p1 / 10; p1 %= 10; break;
+ case 1: d = p1; p1 = 0; break;
+ default:;
+ }
+ if (d || *len)
+ buffer[(*len)++] = static_cast<char>('0' + static_cast<char>(d));
+ kappa--;
+ uint64_t tmp = (static_cast<uint64_t>(p1) << -one.e) + p2;
+ if (tmp <= delta) {
+ *K += kappa;
+ GrisuRound(buffer, *len, delta, tmp, static_cast<uint64_t>(kPow10[kappa]) << -one.e, wp_w.f);
+ return;
+ }
+ }
+
+ // kappa = 0
+ for (;;) {
+ p2 *= 10;
+ delta *= 10;
+ char d = static_cast<char>(p2 >> -one.e);
+ if (d || *len)
+ buffer[(*len)++] = static_cast<char>('0' + d);
+ p2 &= one.f - 1;
+ kappa--;
+ if (p2 < delta) {
+ *K += kappa;
+ int index = -static_cast<int>(kappa);
+ GrisuRound(buffer, *len, delta, p2, one.f, wp_w.f * (index < 9 ? kPow10[-static_cast<int>(kappa)] : 0));
+ return;
+ }
+ }
+}
+
+inline void Grisu2(double value, char* buffer, int* length, int* K) {
+ const DiyFp v(value);
+ DiyFp w_m, w_p;
+ v.NormalizedBoundaries(&w_m, &w_p);
+
+ const DiyFp c_mk = GetCachedPower(w_p.e, K);
+ const DiyFp W = v.Normalize() * c_mk;
+ DiyFp Wp = w_p * c_mk;
+ DiyFp Wm = w_m * c_mk;
+ Wm.f++;
+ Wp.f--;
+ DigitGen(W, Wp, Wp.f - Wm.f, buffer, length, K);
+}
+
+inline char* WriteExponent(int K, char* buffer) {
+ if (K < 0) {
+ *buffer++ = '-';
+ K = -K;
+ }
+
+ if (K >= 100) {
+ *buffer++ = static_cast<char>('0' + static_cast<char>(K / 100));
+ K %= 100;
+ const char* d = GetDigitsLut() + K * 2;
+ *buffer++ = d[0];
+ *buffer++ = d[1];
+ }
+ else if (K >= 10) {
+ const char* d = GetDigitsLut() + K * 2;
+ *buffer++ = d[0];
+ *buffer++ = d[1];
+ }
+ else
+ *buffer++ = static_cast<char>('0' + static_cast<char>(K));
+
+ return buffer;
+}
+
+inline char* Prettify(char* buffer, int length, int k, int maxDecimalPlaces) {
+ const int kk = length + k; // 10^(kk-1) <= v < 10^kk
+
+ if (0 <= k && kk <= 21) {
+ // 1234e7 -> 12340000000
+ for (int i = length; i < kk; i++)
+ buffer[i] = '0';
+ buffer[kk] = '.';
+ buffer[kk + 1] = '0';
+ return &buffer[kk + 2];
+ }
+ else if (0 < kk && kk <= 21) {
+ // 1234e-2 -> 12.34
+ std::memmove(&buffer[kk + 1], &buffer[kk], static_cast<size_t>(length - kk));
+ buffer[kk] = '.';
+ if (0 > k + maxDecimalPlaces) {
+ // When maxDecimalPlaces = 2, 1.2345 -> 1.23, 1.102 -> 1.1
+ // Remove extra trailing zeros (at least one) after truncation.
+ for (int i = kk + maxDecimalPlaces; i > kk + 1; i--)
+ if (buffer[i] != '0')
+ return &buffer[i + 1];
+ return &buffer[kk + 2]; // Reserve one zero
+ }
+ else
+ return &buffer[length + 1];
+ }
+ else if (-6 < kk && kk <= 0) {
+ // 1234e-6 -> 0.001234
+ const int offset = 2 - kk;
+ std::memmove(&buffer[offset], &buffer[0], static_cast<size_t>(length));
+ buffer[0] = '0';
+ buffer[1] = '.';
+ for (int i = 2; i < offset; i++)
+ buffer[i] = '0';
+ if (length - kk > maxDecimalPlaces) {
+ // When maxDecimalPlaces = 2, 0.123 -> 0.12, 0.102 -> 0.1
+ // Remove extra trailing zeros (at least one) after truncation.
+ for (int i = maxDecimalPlaces + 1; i > 2; i--)
+ if (buffer[i] != '0')
+ return &buffer[i + 1];
+ return &buffer[3]; // Reserve one zero
+ }
+ else
+ return &buffer[length + offset];
+ }
+ else if (kk < -maxDecimalPlaces) {
+ // Truncate to zero
+ buffer[0] = '0';
+ buffer[1] = '.';
+ buffer[2] = '0';
+ return &buffer[3];
+ }
+ else if (length == 1) {
+ // 1e30
+ buffer[1] = 'e';
+ return WriteExponent(kk - 1, &buffer[2]);
+ }
+ else {
+ // 1234e30 -> 1.234e33
+ std::memmove(&buffer[2], &buffer[1], static_cast<size_t>(length - 1));
+ buffer[1] = '.';
+ buffer[length + 1] = 'e';
+ return WriteExponent(kk - 1, &buffer[0 + length + 2]);
+ }
+}
+
+inline char* dtoa(double value, char* buffer, int maxDecimalPlaces = 324) {
+ RAPIDJSON_ASSERT(maxDecimalPlaces >= 1);
+ Double d(value);
+ if (d.IsZero()) {
+ if (d.Sign())
+ *buffer++ = '-'; // -0.0, Issue #289
+ buffer[0] = '0';
+ buffer[1] = '.';
+ buffer[2] = '0';
+ return &buffer[3];
+ }
+ else {
+ if (value < 0) {
+ *buffer++ = '-';
+ value = -value;
+ }
+ int length, K;
+ Grisu2(value, buffer, &length, &K);
+ return Prettify(buffer, length, K, maxDecimalPlaces);
+ }
+}
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_POP
+#endif
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_DTOA_
diff --git a/include/rapidjson/internal/ieee754.h b/include/rapidjson/internal/ieee754.h
new file mode 100644
index 00000000..82bb0b99
--- /dev/null
+++ b/include/rapidjson/internal/ieee754.h
@@ -0,0 +1,78 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_IEEE754_
+#define RAPIDJSON_IEEE754_
+
+#include "../rapidjson.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+class Double {
+public:
+ Double() {}
+ Double(double d) : d_(d) {}
+ Double(uint64_t u) : u_(u) {}
+
+ double Value() const { return d_; }
+ uint64_t Uint64Value() const { return u_; }
+
+ double NextPositiveDouble() const {
+ RAPIDJSON_ASSERT(!Sign());
+ return Double(u_ + 1).Value();
+ }
+
+ bool Sign() const { return (u_ & kSignMask) != 0; }
+ uint64_t Significand() const { return u_ & kSignificandMask; }
+ int Exponent() const { return static_cast<int>(((u_ & kExponentMask) >> kSignificandSize) - kExponentBias); }
+
+ bool IsNan() const { return (u_ & kExponentMask) == kExponentMask && Significand() != 0; }
+ bool IsInf() const { return (u_ & kExponentMask) == kExponentMask && Significand() == 0; }
+ bool IsNanOrInf() const { return (u_ & kExponentMask) == kExponentMask; }
+ bool IsNormal() const { return (u_ & kExponentMask) != 0 || Significand() == 0; }
+ bool IsZero() const { return (u_ & (kExponentMask | kSignificandMask)) == 0; }
+
+ uint64_t IntegerSignificand() const { return IsNormal() ? Significand() | kHiddenBit : Significand(); }
+ int IntegerExponent() const { return (IsNormal() ? Exponent() : kDenormalExponent) - kSignificandSize; }
+ uint64_t ToBias() const { return (u_ & kSignMask) ? ~u_ + 1 : u_ | kSignMask; }
+
+ static unsigned EffectiveSignificandSize(int order) {
+ if (order >= -1021)
+ return 53;
+ else if (order <= -1074)
+ return 0;
+ else
+ return static_cast<unsigned>(order) + 1074;
+ }
+
+private:
+ static const int kSignificandSize = 52;
+ static const int kExponentBias = 0x3FF;
+ static const int kDenormalExponent = 1 - kExponentBias;
+ static const uint64_t kSignMask = RAPIDJSON_UINT64_C2(0x80000000, 0x00000000);
+ static const uint64_t kExponentMask = RAPIDJSON_UINT64_C2(0x7FF00000, 0x00000000);
+ static const uint64_t kSignificandMask = RAPIDJSON_UINT64_C2(0x000FFFFF, 0xFFFFFFFF);
+ static const uint64_t kHiddenBit = RAPIDJSON_UINT64_C2(0x00100000, 0x00000000);
+
+ union {
+ double d_;
+ uint64_t u_;
+ };
+};
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_IEEE754_
diff --git a/include/rapidjson/internal/itoa.h b/include/rapidjson/internal/itoa.h
new file mode 100644
index 00000000..01a4e7e7
--- /dev/null
+++ b/include/rapidjson/internal/itoa.h
@@ -0,0 +1,304 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_ITOA_
+#define RAPIDJSON_ITOA_
+
+#include "../rapidjson.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+inline const char* GetDigitsLut() {
+ static const char cDigitsLut[200] = {
+ '0','0','0','1','0','2','0','3','0','4','0','5','0','6','0','7','0','8','0','9',
+ '1','0','1','1','1','2','1','3','1','4','1','5','1','6','1','7','1','8','1','9',
+ '2','0','2','1','2','2','2','3','2','4','2','5','2','6','2','7','2','8','2','9',
+ '3','0','3','1','3','2','3','3','3','4','3','5','3','6','3','7','3','8','3','9',
+ '4','0','4','1','4','2','4','3','4','4','4','5','4','6','4','7','4','8','4','9',
+ '5','0','5','1','5','2','5','3','5','4','5','5','5','6','5','7','5','8','5','9',
+ '6','0','6','1','6','2','6','3','6','4','6','5','6','6','6','7','6','8','6','9',
+ '7','0','7','1','7','2','7','3','7','4','7','5','7','6','7','7','7','8','7','9',
+ '8','0','8','1','8','2','8','3','8','4','8','5','8','6','8','7','8','8','8','9',
+ '9','0','9','1','9','2','9','3','9','4','9','5','9','6','9','7','9','8','9','9'
+ };
+ return cDigitsLut;
+}
+
+inline char* u32toa(uint32_t value, char* buffer) {
+ const char* cDigitsLut = GetDigitsLut();
+
+ if (value < 10000) {
+ const uint32_t d1 = (value / 100) << 1;
+ const uint32_t d2 = (value % 100) << 1;
+
+ if (value >= 1000)
+ *buffer++ = cDigitsLut[d1];
+ if (value >= 100)
+ *buffer++ = cDigitsLut[d1 + 1];
+ if (value >= 10)
+ *buffer++ = cDigitsLut[d2];
+ *buffer++ = cDigitsLut[d2 + 1];
+ }
+ else if (value < 100000000) {
+ // value = bbbbcccc
+ const uint32_t b = value / 10000;
+ const uint32_t c = value % 10000;
+
+ const uint32_t d1 = (b / 100) << 1;
+ const uint32_t d2 = (b % 100) << 1;
+
+ const uint32_t d3 = (c / 100) << 1;
+ const uint32_t d4 = (c % 100) << 1;
+
+ if (value >= 10000000)
+ *buffer++ = cDigitsLut[d1];
+ if (value >= 1000000)
+ *buffer++ = cDigitsLut[d1 + 1];
+ if (value >= 100000)
+ *buffer++ = cDigitsLut[d2];
+ *buffer++ = cDigitsLut[d2 + 1];
+
+ *buffer++ = cDigitsLut[d3];
+ *buffer++ = cDigitsLut[d3 + 1];
+ *buffer++ = cDigitsLut[d4];
+ *buffer++ = cDigitsLut[d4 + 1];
+ }
+ else {
+ // value = aabbbbcccc in decimal
+
+ const uint32_t a = value / 100000000; // 1 to 42
+ value %= 100000000;
+
+ if (a >= 10) {
+ const unsigned i = a << 1;
+ *buffer++ = cDigitsLut[i];
+ *buffer++ = cDigitsLut[i + 1];
+ }
+ else
+ *buffer++ = static_cast<char>('0' + static_cast<char>(a));
+
+ const uint32_t b = value / 10000; // 0 to 9999
+ const uint32_t c = value % 10000; // 0 to 9999
+
+ const uint32_t d1 = (b / 100) << 1;
+ const uint32_t d2 = (b % 100) << 1;
+
+ const uint32_t d3 = (c / 100) << 1;
+ const uint32_t d4 = (c % 100) << 1;
+
+ *buffer++ = cDigitsLut[d1];
+ *buffer++ = cDigitsLut[d1 + 1];
+ *buffer++ = cDigitsLut[d2];
+ *buffer++ = cDigitsLut[d2 + 1];
+ *buffer++ = cDigitsLut[d3];
+ *buffer++ = cDigitsLut[d3 + 1];
+ *buffer++ = cDigitsLut[d4];
+ *buffer++ = cDigitsLut[d4 + 1];
+ }
+ return buffer;
+}
+
+inline char* i32toa(int32_t value, char* buffer) {
+ uint32_t u = static_cast<uint32_t>(value);
+ if (value < 0) {
+ *buffer++ = '-';
+ u = ~u + 1;
+ }
+
+ return u32toa(u, buffer);
+}
+
+inline char* u64toa(uint64_t value, char* buffer) {
+ const char* cDigitsLut = GetDigitsLut();
+ const uint64_t kTen8 = 100000000;
+ const uint64_t kTen9 = kTen8 * 10;
+ const uint64_t kTen10 = kTen8 * 100;
+ const uint64_t kTen11 = kTen8 * 1000;
+ const uint64_t kTen12 = kTen8 * 10000;
+ const uint64_t kTen13 = kTen8 * 100000;
+ const uint64_t kTen14 = kTen8 * 1000000;
+ const uint64_t kTen15 = kTen8 * 10000000;
+ const uint64_t kTen16 = kTen8 * kTen8;
+
+ if (value < kTen8) {
+ uint32_t v = static_cast<uint32_t>(value);
+ if (v < 10000) {
+ const uint32_t d1 = (v / 100) << 1;
+ const uint32_t d2 = (v % 100) << 1;
+
+ if (v >= 1000)
+ *buffer++ = cDigitsLut[d1];
+ if (v >= 100)
+ *buffer++ = cDigitsLut[d1 + 1];
+ if (v >= 10)
+ *buffer++ = cDigitsLut[d2];
+ *buffer++ = cDigitsLut[d2 + 1];
+ }
+ else {
+ // value = bbbbcccc
+ const uint32_t b = v / 10000;
+ const uint32_t c = v % 10000;
+
+ const uint32_t d1 = (b / 100) << 1;
+ const uint32_t d2 = (b % 100) << 1;
+
+ const uint32_t d3 = (c / 100) << 1;
+ const uint32_t d4 = (c % 100) << 1;
+
+ if (value >= 10000000)
+ *buffer++ = cDigitsLut[d1];
+ if (value >= 1000000)
+ *buffer++ = cDigitsLut[d1 + 1];
+ if (value >= 100000)
+ *buffer++ = cDigitsLut[d2];
+ *buffer++ = cDigitsLut[d2 + 1];
+
+ *buffer++ = cDigitsLut[d3];
+ *buffer++ = cDigitsLut[d3 + 1];
+ *buffer++ = cDigitsLut[d4];
+ *buffer++ = cDigitsLut[d4 + 1];
+ }
+ }
+ else if (value < kTen16) {
+ const uint32_t v0 = static_cast<uint32_t>(value / kTen8);
+ const uint32_t v1 = static_cast<uint32_t>(value % kTen8);
+
+ const uint32_t b0 = v0 / 10000;
+ const uint32_t c0 = v0 % 10000;
+
+ const uint32_t d1 = (b0 / 100) << 1;
+ const uint32_t d2 = (b0 % 100) << 1;
+
+ const uint32_t d3 = (c0 / 100) << 1;
+ const uint32_t d4 = (c0 % 100) << 1;
+
+ const uint32_t b1 = v1 / 10000;
+ const uint32_t c1 = v1 % 10000;
+
+ const uint32_t d5 = (b1 / 100) << 1;
+ const uint32_t d6 = (b1 % 100) << 1;
+
+ const uint32_t d7 = (c1 / 100) << 1;
+ const uint32_t d8 = (c1 % 100) << 1;
+
+ if (value >= kTen15)
+ *buffer++ = cDigitsLut[d1];
+ if (value >= kTen14)
+ *buffer++ = cDigitsLut[d1 + 1];
+ if (value >= kTen13)
+ *buffer++ = cDigitsLut[d2];
+ if (value >= kTen12)
+ *buffer++ = cDigitsLut[d2 + 1];
+ if (value >= kTen11)
+ *buffer++ = cDigitsLut[d3];
+ if (value >= kTen10)
+ *buffer++ = cDigitsLut[d3 + 1];
+ if (value >= kTen9)
+ *buffer++ = cDigitsLut[d4];
+ if (value >= kTen8)
+ *buffer++ = cDigitsLut[d4 + 1];
+
+ *buffer++ = cDigitsLut[d5];
+ *buffer++ = cDigitsLut[d5 + 1];
+ *buffer++ = cDigitsLut[d6];
+ *buffer++ = cDigitsLut[d6 + 1];
+ *buffer++ = cDigitsLut[d7];
+ *buffer++ = cDigitsLut[d7 + 1];
+ *buffer++ = cDigitsLut[d8];
+ *buffer++ = cDigitsLut[d8 + 1];
+ }
+ else {
+ const uint32_t a = static_cast<uint32_t>(value / kTen16); // 1 to 1844
+ value %= kTen16;
+
+ if (a < 10)
+ *buffer++ = static_cast<char>('0' + static_cast<char>(a));
+ else if (a < 100) {
+ const uint32_t i = a << 1;
+ *buffer++ = cDigitsLut[i];
+ *buffer++ = cDigitsLut[i + 1];
+ }
+ else if (a < 1000) {
+ *buffer++ = static_cast<char>('0' + static_cast<char>(a / 100));
+
+ const uint32_t i = (a % 100) << 1;
+ *buffer++ = cDigitsLut[i];
+ *buffer++ = cDigitsLut[i + 1];
+ }
+ else {
+ const uint32_t i = (a / 100) << 1;
+ const uint32_t j = (a % 100) << 1;
+ *buffer++ = cDigitsLut[i];
+ *buffer++ = cDigitsLut[i + 1];
+ *buffer++ = cDigitsLut[j];
+ *buffer++ = cDigitsLut[j + 1];
+ }
+
+ const uint32_t v0 = static_cast<uint32_t>(value / kTen8);
+ const uint32_t v1 = static_cast<uint32_t>(value % kTen8);
+
+ const uint32_t b0 = v0 / 10000;
+ const uint32_t c0 = v0 % 10000;
+
+ const uint32_t d1 = (b0 / 100) << 1;
+ const uint32_t d2 = (b0 % 100) << 1;
+
+ const uint32_t d3 = (c0 / 100) << 1;
+ const uint32_t d4 = (c0 % 100) << 1;
+
+ const uint32_t b1 = v1 / 10000;
+ const uint32_t c1 = v1 % 10000;
+
+ const uint32_t d5 = (b1 / 100) << 1;
+ const uint32_t d6 = (b1 % 100) << 1;
+
+ const uint32_t d7 = (c1 / 100) << 1;
+ const uint32_t d8 = (c1 % 100) << 1;
+
+ *buffer++ = cDigitsLut[d1];
+ *buffer++ = cDigitsLut[d1 + 1];
+ *buffer++ = cDigitsLut[d2];
+ *buffer++ = cDigitsLut[d2 + 1];
+ *buffer++ = cDigitsLut[d3];
+ *buffer++ = cDigitsLut[d3 + 1];
+ *buffer++ = cDigitsLut[d4];
+ *buffer++ = cDigitsLut[d4 + 1];
+ *buffer++ = cDigitsLut[d5];
+ *buffer++ = cDigitsLut[d5 + 1];
+ *buffer++ = cDigitsLut[d6];
+ *buffer++ = cDigitsLut[d6 + 1];
+ *buffer++ = cDigitsLut[d7];
+ *buffer++ = cDigitsLut[d7 + 1];
+ *buffer++ = cDigitsLut[d8];
+ *buffer++ = cDigitsLut[d8 + 1];
+ }
+
+ return buffer;
+}
+
+inline char* i64toa(int64_t value, char* buffer) {
+ uint64_t u = static_cast<uint64_t>(value);
+ if (value < 0) {
+ *buffer++ = '-';
+ u = ~u + 1;
+ }
+
+ return u64toa(u, buffer);
+}
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_ITOA_
diff --git a/include/rapidjson/internal/meta.h b/include/rapidjson/internal/meta.h
new file mode 100644
index 00000000..5a9aaa42
--- /dev/null
+++ b/include/rapidjson/internal/meta.h
@@ -0,0 +1,181 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_INTERNAL_META_H_
+#define RAPIDJSON_INTERNAL_META_H_
+
+#include "../rapidjson.h"
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+#endif
+#if defined(_MSC_VER)
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(6334)
+#endif
+
+#if RAPIDJSON_HAS_CXX11_TYPETRAITS
+#include <type_traits>
+#endif
+
+//@cond RAPIDJSON_INTERNAL
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+// Helper to wrap/convert arbitrary types to void, useful for arbitrary type matching
+template <typename T> struct Void { typedef void Type; };
+
+///////////////////////////////////////////////////////////////////////////////
+// BoolType, TrueType, FalseType
+//
+template <bool Cond> struct BoolType {
+ static const bool Value = Cond;
+ typedef BoolType Type;
+};
+typedef BoolType<true> TrueType;
+typedef BoolType<false> FalseType;
+
+
+///////////////////////////////////////////////////////////////////////////////
+// SelectIf, BoolExpr, NotExpr, AndExpr, OrExpr
+//
+
+template <bool C> struct SelectIfImpl { template <typename T1, typename T2> struct Apply { typedef T1 Type; }; };
+template <> struct SelectIfImpl<false> { template <typename T1, typename T2> struct Apply { typedef T2 Type; }; };
+template <bool C, typename T1, typename T2> struct SelectIfCond : SelectIfImpl<C>::template Apply<T1,T2> {};
+template <typename C, typename T1, typename T2> struct SelectIf : SelectIfCond<C::Value, T1, T2> {};
+
+template <bool Cond1, bool Cond2> struct AndExprCond : FalseType {};
+template <> struct AndExprCond<true, true> : TrueType {};
+template <bool Cond1, bool Cond2> struct OrExprCond : TrueType {};
+template <> struct OrExprCond<false, false> : FalseType {};
+
+template <typename C> struct BoolExpr : SelectIf<C,TrueType,FalseType>::Type {};
+template <typename C> struct NotExpr : SelectIf<C,FalseType,TrueType>::Type {};
+template <typename C1, typename C2> struct AndExpr : AndExprCond<C1::Value, C2::Value>::Type {};
+template <typename C1, typename C2> struct OrExpr : OrExprCond<C1::Value, C2::Value>::Type {};
+
+
+///////////////////////////////////////////////////////////////////////////////
+// AddConst, MaybeAddConst, RemoveConst
+template <typename T> struct AddConst { typedef const T Type; };
+template <bool Constify, typename T> struct MaybeAddConst : SelectIfCond<Constify, const T, T> {};
+template <typename T> struct RemoveConst { typedef T Type; };
+template <typename T> struct RemoveConst<const T> { typedef T Type; };
+
+
+///////////////////////////////////////////////////////////////////////////////
+// IsSame, IsConst, IsMoreConst, IsPointer
+//
+template <typename T, typename U> struct IsSame : FalseType {};
+template <typename T> struct IsSame<T, T> : TrueType {};
+
+template <typename T> struct IsConst : FalseType {};
+template <typename T> struct IsConst<const T> : TrueType {};
+
+template <typename CT, typename T>
+struct IsMoreConst
+ : AndExpr<IsSame<typename RemoveConst<CT>::Type, typename RemoveConst<T>::Type>,
+ BoolType<IsConst<CT>::Value >= IsConst<T>::Value> >::Type {};
+
+template <typename T> struct IsPointer : FalseType {};
+template <typename T> struct IsPointer<T*> : TrueType {};
+
+///////////////////////////////////////////////////////////////////////////////
+// IsBaseOf
+//
+#if RAPIDJSON_HAS_CXX11_TYPETRAITS
+
+template <typename B, typename D> struct IsBaseOf
+ : BoolType< ::std::is_base_of<B,D>::value> {};
+
+#else // simplified version adopted from Boost
+
+template<typename B, typename D> struct IsBaseOfImpl {
+ RAPIDJSON_STATIC_ASSERT(sizeof(B) != 0);
+ RAPIDJSON_STATIC_ASSERT(sizeof(D) != 0);
+
+ typedef char (&Yes)[1];
+ typedef char (&No) [2];
+
+ template <typename T>
+ static Yes Check(const D*, T);
+ static No Check(const B*, int);
+
+ struct Host {
+ operator const B*() const;
+ operator const D*();
+ };
+
+ enum { Value = (sizeof(Check(Host(), 0)) == sizeof(Yes)) };
+};
+
+template <typename B, typename D> struct IsBaseOf
+ : OrExpr<IsSame<B, D>, BoolExpr<IsBaseOfImpl<B, D> > >::Type {};
+
+#endif // RAPIDJSON_HAS_CXX11_TYPETRAITS
+
+
+//////////////////////////////////////////////////////////////////////////
+// EnableIf / DisableIf
+//
+template <bool Condition, typename T = void> struct EnableIfCond { typedef T Type; };
+template <typename T> struct EnableIfCond<false, T> { /* empty */ };
+
+template <bool Condition, typename T = void> struct DisableIfCond { typedef T Type; };
+template <typename T> struct DisableIfCond<true, T> { /* empty */ };
+
+template <typename Condition, typename T = void>
+struct EnableIf : EnableIfCond<Condition::Value, T> {};
+
+template <typename Condition, typename T = void>
+struct DisableIf : DisableIfCond<Condition::Value, T> {};
+
+// SFINAE helpers
+struct SfinaeTag {};
+template <typename T> struct RemoveSfinaeTag;
+template <typename T> struct RemoveSfinaeTag<SfinaeTag&(*)(T)> { typedef T Type; };
+
+#define RAPIDJSON_REMOVEFPTR_(type) \
+ typename ::RAPIDJSON_NAMESPACE::internal::RemoveSfinaeTag \
+ < ::RAPIDJSON_NAMESPACE::internal::SfinaeTag&(*) type>::Type
+
+#define RAPIDJSON_ENABLEIF(cond) \
+ typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \
+ <RAPIDJSON_REMOVEFPTR_(cond)>::Type * = NULL
+
+#define RAPIDJSON_DISABLEIF(cond) \
+ typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \
+ <RAPIDJSON_REMOVEFPTR_(cond)>::Type * = NULL
+
+#define RAPIDJSON_ENABLEIF_RETURN(cond,returntype) \
+ typename ::RAPIDJSON_NAMESPACE::internal::EnableIf \
+ <RAPIDJSON_REMOVEFPTR_(cond), \
+ RAPIDJSON_REMOVEFPTR_(returntype)>::Type
+
+#define RAPIDJSON_DISABLEIF_RETURN(cond,returntype) \
+ typename ::RAPIDJSON_NAMESPACE::internal::DisableIf \
+ <RAPIDJSON_REMOVEFPTR_(cond), \
+ RAPIDJSON_REMOVEFPTR_(returntype)>::Type
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+//@endcond
+
+#if defined(__GNUC__) || defined(_MSC_VER)
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_INTERNAL_META_H_
diff --git a/include/rapidjson/internal/pow10.h b/include/rapidjson/internal/pow10.h
new file mode 100644
index 00000000..02f475d7
--- /dev/null
+++ b/include/rapidjson/internal/pow10.h
@@ -0,0 +1,55 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_POW10_
+#define RAPIDJSON_POW10_
+
+#include "../rapidjson.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+//! Computes integer powers of 10 in double (10.0^n).
+/*! This function uses lookup table for fast and accurate results.
+ \param n non-negative exponent. Must <= 308.
+ \return 10.0^n
+*/
+inline double Pow10(int n) {
+ static const double e[] = { // 1e-0...1e308: 309 * 8 bytes = 2472 bytes
+ 1e+0,
+ 1e+1, 1e+2, 1e+3, 1e+4, 1e+5, 1e+6, 1e+7, 1e+8, 1e+9, 1e+10, 1e+11, 1e+12, 1e+13, 1e+14, 1e+15, 1e+16, 1e+17, 1e+18, 1e+19, 1e+20,
+ 1e+21, 1e+22, 1e+23, 1e+24, 1e+25, 1e+26, 1e+27, 1e+28, 1e+29, 1e+30, 1e+31, 1e+32, 1e+33, 1e+34, 1e+35, 1e+36, 1e+37, 1e+38, 1e+39, 1e+40,
+ 1e+41, 1e+42, 1e+43, 1e+44, 1e+45, 1e+46, 1e+47, 1e+48, 1e+49, 1e+50, 1e+51, 1e+52, 1e+53, 1e+54, 1e+55, 1e+56, 1e+57, 1e+58, 1e+59, 1e+60,
+ 1e+61, 1e+62, 1e+63, 1e+64, 1e+65, 1e+66, 1e+67, 1e+68, 1e+69, 1e+70, 1e+71, 1e+72, 1e+73, 1e+74, 1e+75, 1e+76, 1e+77, 1e+78, 1e+79, 1e+80,
+ 1e+81, 1e+82, 1e+83, 1e+84, 1e+85, 1e+86, 1e+87, 1e+88, 1e+89, 1e+90, 1e+91, 1e+92, 1e+93, 1e+94, 1e+95, 1e+96, 1e+97, 1e+98, 1e+99, 1e+100,
+ 1e+101,1e+102,1e+103,1e+104,1e+105,1e+106,1e+107,1e+108,1e+109,1e+110,1e+111,1e+112,1e+113,1e+114,1e+115,1e+116,1e+117,1e+118,1e+119,1e+120,
+ 1e+121,1e+122,1e+123,1e+124,1e+125,1e+126,1e+127,1e+128,1e+129,1e+130,1e+131,1e+132,1e+133,1e+134,1e+135,1e+136,1e+137,1e+138,1e+139,1e+140,
+ 1e+141,1e+142,1e+143,1e+144,1e+145,1e+146,1e+147,1e+148,1e+149,1e+150,1e+151,1e+152,1e+153,1e+154,1e+155,1e+156,1e+157,1e+158,1e+159,1e+160,
+ 1e+161,1e+162,1e+163,1e+164,1e+165,1e+166,1e+167,1e+168,1e+169,1e+170,1e+171,1e+172,1e+173,1e+174,1e+175,1e+176,1e+177,1e+178,1e+179,1e+180,
+ 1e+181,1e+182,1e+183,1e+184,1e+185,1e+186,1e+187,1e+188,1e+189,1e+190,1e+191,1e+192,1e+193,1e+194,1e+195,1e+196,1e+197,1e+198,1e+199,1e+200,
+ 1e+201,1e+202,1e+203,1e+204,1e+205,1e+206,1e+207,1e+208,1e+209,1e+210,1e+211,1e+212,1e+213,1e+214,1e+215,1e+216,1e+217,1e+218,1e+219,1e+220,
+ 1e+221,1e+222,1e+223,1e+224,1e+225,1e+226,1e+227,1e+228,1e+229,1e+230,1e+231,1e+232,1e+233,1e+234,1e+235,1e+236,1e+237,1e+238,1e+239,1e+240,
+ 1e+241,1e+242,1e+243,1e+244,1e+245,1e+246,1e+247,1e+248,1e+249,1e+250,1e+251,1e+252,1e+253,1e+254,1e+255,1e+256,1e+257,1e+258,1e+259,1e+260,
+ 1e+261,1e+262,1e+263,1e+264,1e+265,1e+266,1e+267,1e+268,1e+269,1e+270,1e+271,1e+272,1e+273,1e+274,1e+275,1e+276,1e+277,1e+278,1e+279,1e+280,
+ 1e+281,1e+282,1e+283,1e+284,1e+285,1e+286,1e+287,1e+288,1e+289,1e+290,1e+291,1e+292,1e+293,1e+294,1e+295,1e+296,1e+297,1e+298,1e+299,1e+300,
+ 1e+301,1e+302,1e+303,1e+304,1e+305,1e+306,1e+307,1e+308
+ };
+ RAPIDJSON_ASSERT(n >= 0 && n <= 308);
+ return e[n];
+}
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_POW10_
diff --git a/include/rapidjson/internal/regex.h b/include/rapidjson/internal/regex.h
new file mode 100644
index 00000000..422a5240
--- /dev/null
+++ b/include/rapidjson/internal/regex.h
@@ -0,0 +1,701 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_INTERNAL_REGEX_H_
+#define RAPIDJSON_INTERNAL_REGEX_H_
+
+#include "../allocators.h"
+#include "../stream.h"
+#include "stack.h"
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+RAPIDJSON_DIAG_OFF(switch-enum)
+RAPIDJSON_DIAG_OFF(implicit-fallthrough)
+#endif
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
+#endif
+
+#ifndef RAPIDJSON_REGEX_VERBOSE
+#define RAPIDJSON_REGEX_VERBOSE 0
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericRegex
+
+static const SizeType kRegexInvalidState = ~SizeType(0); //!< Represents an invalid index in GenericRegex::State::out, out1
+static const SizeType kRegexInvalidRange = ~SizeType(0);
+
+//! Regular expression engine with subset of ECMAscript grammar.
+/*!
+ Supported regular expression syntax:
+ - \c ab Concatenation
+ - \c a|b Alternation
+ - \c a? Zero or one
+ - \c a* Zero or more
+ - \c a+ One or more
+ - \c a{3} Exactly 3 times
+ - \c a{3,} At least 3 times
+ - \c a{3,5} 3 to 5 times
+ - \c (ab) Grouping
+ - \c ^a At the beginning
+ - \c a$ At the end
+ - \c . Any character
+ - \c [abc] Character classes
+ - \c [a-c] Character class range
+ - \c [a-z0-9_] Character class combination
+ - \c [^abc] Negated character classes
+ - \c [^a-c] Negated character class range
+ - \c [\b] Backspace (U+0008)
+ - \c \\| \\\\ ... Escape characters
+ - \c \\f Form feed (U+000C)
+ - \c \\n Line feed (U+000A)
+ - \c \\r Carriage return (U+000D)
+ - \c \\t Tab (U+0009)
+ - \c \\v Vertical tab (U+000B)
+
+ \note This is a Thompson NFA engine, implemented with reference to
+ Cox, Russ. "Regular Expression Matching Can Be Simple And Fast (but is slow in Java, Perl, PHP, Python, Ruby,...).",
+ https://swtch.com/~rsc/regexp/regexp1.html
+*/
+template <typename Encoding, typename Allocator = CrtAllocator>
+class GenericRegex {
+public:
+ typedef typename Encoding::Ch Ch;
+
+ GenericRegex(const Ch* source, Allocator* allocator = 0) :
+ states_(allocator, 256), ranges_(allocator, 256), root_(kRegexInvalidState), stateCount_(), rangeCount_(),
+ stateSet_(), state0_(allocator, 0), state1_(allocator, 0), anchorBegin_(), anchorEnd_()
+ {
+ GenericStringStream<Encoding> ss(source);
+ DecodedStream<GenericStringStream<Encoding> > ds(ss);
+ Parse(ds);
+ }
+
+ ~GenericRegex() {
+ Allocator::Free(stateSet_);
+ }
+
+ bool IsValid() const {
+ return root_ != kRegexInvalidState;
+ }
+
+ template <typename InputStream>
+ bool Match(InputStream& is) const {
+ return SearchWithAnchoring(is, true, true);
+ }
+
+ bool Match(const Ch* s) const {
+ GenericStringStream<Encoding> is(s);
+ return Match(is);
+ }
+
+ template <typename InputStream>
+ bool Search(InputStream& is) const {
+ return SearchWithAnchoring(is, anchorBegin_, anchorEnd_);
+ }
+
+ bool Search(const Ch* s) const {
+ GenericStringStream<Encoding> is(s);
+ return Search(is);
+ }
+
+private:
+ enum Operator {
+ kZeroOrOne,
+ kZeroOrMore,
+ kOneOrMore,
+ kConcatenation,
+ kAlternation,
+ kLeftParenthesis
+ };
+
+ static const unsigned kAnyCharacterClass = 0xFFFFFFFF; //!< For '.'
+ static const unsigned kRangeCharacterClass = 0xFFFFFFFE;
+ static const unsigned kRangeNegationFlag = 0x80000000;
+
+ struct Range {
+ unsigned start; //
+ unsigned end;
+ SizeType next;
+ };
+
+ struct State {
+ SizeType out; //!< Equals to kInvalid for matching state
+ SizeType out1; //!< Equals to non-kInvalid for split
+ SizeType rangeStart;
+ unsigned codepoint;
+ };
+
+ struct Frag {
+ Frag(SizeType s, SizeType o, SizeType m) : start(s), out(o), minIndex(m) {}
+ SizeType start;
+ SizeType out; //!< link-list of all output states
+ SizeType minIndex;
+ };
+
+ template <typename SourceStream>
+ class DecodedStream {
+ public:
+ DecodedStream(SourceStream& ss) : ss_(ss), codepoint_() { Decode(); }
+ unsigned Peek() { return codepoint_; }
+ unsigned Take() {
+ unsigned c = codepoint_;
+ if (c) // No further decoding when '\0'
+ Decode();
+ return c;
+ }
+
+ private:
+ void Decode() {
+ if (!Encoding::Decode(ss_, &codepoint_))
+ codepoint_ = 0;
+ }
+
+ SourceStream& ss_;
+ unsigned codepoint_;
+ };
+
+ State& GetState(SizeType index) {
+ RAPIDJSON_ASSERT(index < stateCount_);
+ return states_.template Bottom<State>()[index];
+ }
+
+ const State& GetState(SizeType index) const {
+ RAPIDJSON_ASSERT(index < stateCount_);
+ return states_.template Bottom<State>()[index];
+ }
+
+ Range& GetRange(SizeType index) {
+ RAPIDJSON_ASSERT(index < rangeCount_);
+ return ranges_.template Bottom<Range>()[index];
+ }
+
+ const Range& GetRange(SizeType index) const {
+ RAPIDJSON_ASSERT(index < rangeCount_);
+ return ranges_.template Bottom<Range>()[index];
+ }
+
+ template <typename InputStream>
+ void Parse(DecodedStream<InputStream>& ds) {
+ Allocator allocator;
+ Stack<Allocator> operandStack(&allocator, 256); // Frag
+ Stack<Allocator> operatorStack(&allocator, 256); // Operator
+ Stack<Allocator> atomCountStack(&allocator, 256); // unsigned (Atom per parenthesis)
+
+ *atomCountStack.template Push<unsigned>() = 0;
+
+ unsigned codepoint;
+ while (ds.Peek() != 0) {
+ switch (codepoint = ds.Take()) {
+ case '^':
+ anchorBegin_ = true;
+ break;
+
+ case '$':
+ anchorEnd_ = true;
+ break;
+
+ case '|':
+ while (!operatorStack.Empty() && *operatorStack.template Top<Operator>() < kAlternation)
+ if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
+ return;
+ *operatorStack.template Push<Operator>() = kAlternation;
+ *atomCountStack.template Top<unsigned>() = 0;
+ break;
+
+ case '(':
+ *operatorStack.template Push<Operator>() = kLeftParenthesis;
+ *atomCountStack.template Push<unsigned>() = 0;
+ break;
+
+ case ')':
+ while (!operatorStack.Empty() && *operatorStack.template Top<Operator>() != kLeftParenthesis)
+ if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
+ return;
+ if (operatorStack.Empty())
+ return;
+ operatorStack.template Pop<Operator>(1);
+ atomCountStack.template Pop<unsigned>(1);
+ ImplicitConcatenation(atomCountStack, operatorStack);
+ break;
+
+ case '?':
+ if (!Eval(operandStack, kZeroOrOne))
+ return;
+ break;
+
+ case '*':
+ if (!Eval(operandStack, kZeroOrMore))
+ return;
+ break;
+
+ case '+':
+ if (!Eval(operandStack, kOneOrMore))
+ return;
+ break;
+
+ case '{':
+ {
+ unsigned n, m;
+ if (!ParseUnsigned(ds, &n))
+ return;
+
+ if (ds.Peek() == ',') {
+ ds.Take();
+ if (ds.Peek() == '}')
+ m = kInfinityQuantifier;
+ else if (!ParseUnsigned(ds, &m) || m < n)
+ return;
+ }
+ else
+ m = n;
+
+ if (!EvalQuantifier(operandStack, n, m) || ds.Peek() != '}')
+ return;
+ ds.Take();
+ }
+ break;
+
+ case '.':
+ PushOperand(operandStack, kAnyCharacterClass);
+ ImplicitConcatenation(atomCountStack, operatorStack);
+ break;
+
+ case '[':
+ {
+ SizeType range;
+ if (!ParseRange(ds, &range))
+ return;
+ SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, kRangeCharacterClass);
+ GetState(s).rangeStart = range;
+ *operandStack.template Push<Frag>() = Frag(s, s, s);
+ }
+ ImplicitConcatenation(atomCountStack, operatorStack);
+ break;
+
+ case '\\': // Escape character
+ if (!CharacterEscape(ds, &codepoint))
+ return; // Unsupported escape character
+ // fall through to default
+
+ default: // Pattern character
+ PushOperand(operandStack, codepoint);
+ ImplicitConcatenation(atomCountStack, operatorStack);
+ }
+ }
+
+ while (!operatorStack.Empty())
+ if (!Eval(operandStack, *operatorStack.template Pop<Operator>(1)))
+ return;
+
+ // Link the operand to matching state.
+ if (operandStack.GetSize() == sizeof(Frag)) {
+ Frag* e = operandStack.template Pop<Frag>(1);
+ Patch(e->out, NewState(kRegexInvalidState, kRegexInvalidState, 0));
+ root_ = e->start;
+
+#if RAPIDJSON_REGEX_VERBOSE
+ printf("root: %d\n", root_);
+ for (SizeType i = 0; i < stateCount_ ; i++) {
+ State& s = GetState(i);
+ printf("[%2d] out: %2d out1: %2d c: '%c'\n", i, s.out, s.out1, (char)s.codepoint);
+ }
+ printf("\n");
+#endif
+ }
+
+ // Preallocate buffer for SearchWithAnchoring()
+ RAPIDJSON_ASSERT(stateSet_ == 0);
+ if (stateCount_ > 0) {
+ stateSet_ = static_cast<unsigned*>(states_.GetAllocator().Malloc(GetStateSetSize()));
+ state0_.template Reserve<SizeType>(stateCount_);
+ state1_.template Reserve<SizeType>(stateCount_);
+ }
+ }
+
+ SizeType NewState(SizeType out, SizeType out1, unsigned codepoint) {
+ State* s = states_.template Push<State>();
+ s->out = out;
+ s->out1 = out1;
+ s->codepoint = codepoint;
+ s->rangeStart = kRegexInvalidRange;
+ return stateCount_++;
+ }
+
+ void PushOperand(Stack<Allocator>& operandStack, unsigned codepoint) {
+ SizeType s = NewState(kRegexInvalidState, kRegexInvalidState, codepoint);
+ *operandStack.template Push<Frag>() = Frag(s, s, s);
+ }
+
+ void ImplicitConcatenation(Stack<Allocator>& atomCountStack, Stack<Allocator>& operatorStack) {
+ if (*atomCountStack.template Top<unsigned>())
+ *operatorStack.template Push<Operator>() = kConcatenation;
+ (*atomCountStack.template Top<unsigned>())++;
+ }
+
+ SizeType Append(SizeType l1, SizeType l2) {
+ SizeType old = l1;
+ while (GetState(l1).out != kRegexInvalidState)
+ l1 = GetState(l1).out;
+ GetState(l1).out = l2;
+ return old;
+ }
+
+ void Patch(SizeType l, SizeType s) {
+ for (SizeType next; l != kRegexInvalidState; l = next) {
+ next = GetState(l).out;
+ GetState(l).out = s;
+ }
+ }
+
+ bool Eval(Stack<Allocator>& operandStack, Operator op) {
+ switch (op) {
+ case kConcatenation:
+ RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag) * 2);
+ {
+ Frag e2 = *operandStack.template Pop<Frag>(1);
+ Frag e1 = *operandStack.template Pop<Frag>(1);
+ Patch(e1.out, e2.start);
+ *operandStack.template Push<Frag>() = Frag(e1.start, e2.out, Min(e1.minIndex, e2.minIndex));
+ }
+ return true;
+
+ case kAlternation:
+ if (operandStack.GetSize() >= sizeof(Frag) * 2) {
+ Frag e2 = *operandStack.template Pop<Frag>(1);
+ Frag e1 = *operandStack.template Pop<Frag>(1);
+ SizeType s = NewState(e1.start, e2.start, 0);
+ *operandStack.template Push<Frag>() = Frag(s, Append(e1.out, e2.out), Min(e1.minIndex, e2.minIndex));
+ return true;
+ }
+ return false;
+
+ case kZeroOrOne:
+ if (operandStack.GetSize() >= sizeof(Frag)) {
+ Frag e = *operandStack.template Pop<Frag>(1);
+ SizeType s = NewState(kRegexInvalidState, e.start, 0);
+ *operandStack.template Push<Frag>() = Frag(s, Append(e.out, s), e.minIndex);
+ return true;
+ }
+ return false;
+
+ case kZeroOrMore:
+ if (operandStack.GetSize() >= sizeof(Frag)) {
+ Frag e = *operandStack.template Pop<Frag>(1);
+ SizeType s = NewState(kRegexInvalidState, e.start, 0);
+ Patch(e.out, s);
+ *operandStack.template Push<Frag>() = Frag(s, s, e.minIndex);
+ return true;
+ }
+ return false;
+
+ default:
+ RAPIDJSON_ASSERT(op == kOneOrMore);
+ if (operandStack.GetSize() >= sizeof(Frag)) {
+ Frag e = *operandStack.template Pop<Frag>(1);
+ SizeType s = NewState(kRegexInvalidState, e.start, 0);
+ Patch(e.out, s);
+ *operandStack.template Push<Frag>() = Frag(e.start, s, e.minIndex);
+ return true;
+ }
+ return false;
+ }
+ }
+
+ bool EvalQuantifier(Stack<Allocator>& operandStack, unsigned n, unsigned m) {
+ RAPIDJSON_ASSERT(n <= m);
+ RAPIDJSON_ASSERT(operandStack.GetSize() >= sizeof(Frag));
+
+ if (n == 0) {
+ if (m == 0) // a{0} not support
+ return false;
+ else if (m == kInfinityQuantifier)
+ Eval(operandStack, kZeroOrMore); // a{0,} -> a*
+ else {
+ Eval(operandStack, kZeroOrOne); // a{0,5} -> a?
+ for (unsigned i = 0; i < m - 1; i++)
+ CloneTopOperand(operandStack); // a{0,5} -> a? a? a? a? a?
+ for (unsigned i = 0; i < m - 1; i++)
+ Eval(operandStack, kConcatenation); // a{0,5} -> a?a?a?a?a?
+ }
+ return true;
+ }
+
+ for (unsigned i = 0; i < n - 1; i++) // a{3} -> a a a
+ CloneTopOperand(operandStack);
+
+ if (m == kInfinityQuantifier)
+ Eval(operandStack, kOneOrMore); // a{3,} -> a a a+
+ else if (m > n) {
+ CloneTopOperand(operandStack); // a{3,5} -> a a a a
+ Eval(operandStack, kZeroOrOne); // a{3,5} -> a a a a?
+ for (unsigned i = n; i < m - 1; i++)
+ CloneTopOperand(operandStack); // a{3,5} -> a a a a? a?
+ for (unsigned i = n; i < m; i++)
+ Eval(operandStack, kConcatenation); // a{3,5} -> a a aa?a?
+ }
+
+ for (unsigned i = 0; i < n - 1; i++)
+ Eval(operandStack, kConcatenation); // a{3} -> aaa, a{3,} -> aaa+, a{3.5} -> aaaa?a?
+
+ return true;
+ }
+
+ static SizeType Min(SizeType a, SizeType b) { return a < b ? a : b; }
+
+ void CloneTopOperand(Stack<Allocator>& operandStack) {
+ const Frag src = *operandStack.template Top<Frag>(); // Copy constructor to prevent invalidation
+ SizeType count = stateCount_ - src.minIndex; // Assumes top operand contains states in [src->minIndex, stateCount_)
+ State* s = states_.template Push<State>(count);
+ memcpy(s, &GetState(src.minIndex), count * sizeof(State));
+ for (SizeType j = 0; j < count; j++) {
+ if (s[j].out != kRegexInvalidState)
+ s[j].out += count;
+ if (s[j].out1 != kRegexInvalidState)
+ s[j].out1 += count;
+ }
+ *operandStack.template Push<Frag>() = Frag(src.start + count, src.out + count, src.minIndex + count);
+ stateCount_ += count;
+ }
+
+ template <typename InputStream>
+ bool ParseUnsigned(DecodedStream<InputStream>& ds, unsigned* u) {
+ unsigned r = 0;
+ if (ds.Peek() < '0' || ds.Peek() > '9')
+ return false;
+ while (ds.Peek() >= '0' && ds.Peek() <= '9') {
+ if (r >= 429496729 && ds.Peek() > '5') // 2^32 - 1 = 4294967295
+ return false; // overflow
+ r = r * 10 + (ds.Take() - '0');
+ }
+ *u = r;
+ return true;
+ }
+
+ template <typename InputStream>
+ bool ParseRange(DecodedStream<InputStream>& ds, SizeType* range) {
+ bool isBegin = true;
+ bool negate = false;
+ int step = 0;
+ SizeType start = kRegexInvalidRange;
+ SizeType current = kRegexInvalidRange;
+ unsigned codepoint;
+ while ((codepoint = ds.Take()) != 0) {
+ if (isBegin) {
+ isBegin = false;
+ if (codepoint == '^') {
+ negate = true;
+ continue;
+ }
+ }
+
+ switch (codepoint) {
+ case ']':
+ if (start == kRegexInvalidRange)
+ return false; // Error: nothing inside []
+ if (step == 2) { // Add trailing '-'
+ SizeType r = NewRange('-');
+ RAPIDJSON_ASSERT(current != kRegexInvalidRange);
+ GetRange(current).next = r;
+ }
+ if (negate)
+ GetRange(start).start |= kRangeNegationFlag;
+ *range = start;
+ return true;
+
+ case '\\':
+ if (ds.Peek() == 'b') {
+ ds.Take();
+ codepoint = 0x0008; // Escape backspace character
+ }
+ else if (!CharacterEscape(ds, &codepoint))
+ return false;
+ // fall through to default
+
+ default:
+ switch (step) {
+ case 1:
+ if (codepoint == '-') {
+ step++;
+ break;
+ }
+ // fall through to step 0 for other characters
+
+ case 0:
+ {
+ SizeType r = NewRange(codepoint);
+ if (current != kRegexInvalidRange)
+ GetRange(current).next = r;
+ if (start == kRegexInvalidRange)
+ start = r;
+ current = r;
+ }
+ step = 1;
+ break;
+
+ default:
+ RAPIDJSON_ASSERT(step == 2);
+ GetRange(current).end = codepoint;
+ step = 0;
+ }
+ }
+ }
+ return false;
+ }
+
+ SizeType NewRange(unsigned codepoint) {
+ Range* r = ranges_.template Push<Range>();
+ r->start = r->end = codepoint;
+ r->next = kRegexInvalidRange;
+ return rangeCount_++;
+ }
+
+ template <typename InputStream>
+ bool CharacterEscape(DecodedStream<InputStream>& ds, unsigned* escapedCodepoint) {
+ unsigned codepoint;
+ switch (codepoint = ds.Take()) {
+ case '^':
+ case '$':
+ case '|':
+ case '(':
+ case ')':
+ case '?':
+ case '*':
+ case '+':
+ case '.':
+ case '[':
+ case ']':
+ case '{':
+ case '}':
+ case '\\':
+ *escapedCodepoint = codepoint; return true;
+ case 'f': *escapedCodepoint = 0x000C; return true;
+ case 'n': *escapedCodepoint = 0x000A; return true;
+ case 'r': *escapedCodepoint = 0x000D; return true;
+ case 't': *escapedCodepoint = 0x0009; return true;
+ case 'v': *escapedCodepoint = 0x000B; return true;
+ default:
+ return false; // Unsupported escape character
+ }
+ }
+
+ template <typename InputStream>
+ bool SearchWithAnchoring(InputStream& is, bool anchorBegin, bool anchorEnd) const {
+ RAPIDJSON_ASSERT(IsValid());
+ DecodedStream<InputStream> ds(is);
+
+ state0_.Clear();
+ Stack<Allocator> *current = &state0_, *next = &state1_;
+ const size_t stateSetSize = GetStateSetSize();
+ std::memset(stateSet_, 0, stateSetSize);
+
+ bool matched = AddState(*current, root_);
+ unsigned codepoint;
+ while (!current->Empty() && (codepoint = ds.Take()) != 0) {
+ std::memset(stateSet_, 0, stateSetSize);
+ next->Clear();
+ matched = false;
+ for (const SizeType* s = current->template Bottom<SizeType>(); s != current->template End<SizeType>(); ++s) {
+ const State& sr = GetState(*s);
+ if (sr.codepoint == codepoint ||
+ sr.codepoint == kAnyCharacterClass ||
+ (sr.codepoint == kRangeCharacterClass && MatchRange(sr.rangeStart, codepoint)))
+ {
+ matched = AddState(*next, sr.out) || matched;
+ if (!anchorEnd && matched)
+ return true;
+ }
+ if (!anchorBegin)
+ AddState(*next, root_);
+ }
+ internal::Swap(current, next);
+ }
+
+ return matched;
+ }
+
+ size_t GetStateSetSize() const {
+ return (stateCount_ + 31) / 32 * 4;
+ }
+
+ // Return whether the added states is a match state
+ bool AddState(Stack<Allocator>& l, SizeType index) const {
+ RAPIDJSON_ASSERT(index != kRegexInvalidState);
+
+ const State& s = GetState(index);
+ if (s.out1 != kRegexInvalidState) { // Split
+ bool matched = AddState(l, s.out);
+ return AddState(l, s.out1) || matched;
+ }
+ else if (!(stateSet_[index >> 5] & (1 << (index & 31)))) {
+ stateSet_[index >> 5] |= (1 << (index & 31));
+ *l.template PushUnsafe<SizeType>() = index;
+ }
+ return s.out == kRegexInvalidState; // by using PushUnsafe() above, we can ensure s is not validated due to reallocation.
+ }
+
+ bool MatchRange(SizeType rangeIndex, unsigned codepoint) const {
+ bool yes = (GetRange(rangeIndex).start & kRangeNegationFlag) == 0;
+ while (rangeIndex != kRegexInvalidRange) {
+ const Range& r = GetRange(rangeIndex);
+ if (codepoint >= (r.start & ~kRangeNegationFlag) && codepoint <= r.end)
+ return yes;
+ rangeIndex = r.next;
+ }
+ return !yes;
+ }
+
+ Stack<Allocator> states_;
+ Stack<Allocator> ranges_;
+ SizeType root_;
+ SizeType stateCount_;
+ SizeType rangeCount_;
+
+ static const unsigned kInfinityQuantifier = ~0u;
+
+ // For SearchWithAnchoring()
+ uint32_t* stateSet_; // allocated by states_.GetAllocator()
+ mutable Stack<Allocator> state0_;
+ mutable Stack<Allocator> state1_;
+ bool anchorBegin_;
+ bool anchorEnd_;
+};
+
+typedef GenericRegex<UTF8<> > Regex;
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_INTERNAL_REGEX_H_
diff --git a/include/rapidjson/internal/stack.h b/include/rapidjson/internal/stack.h
new file mode 100644
index 00000000..022c9aab
--- /dev/null
+++ b/include/rapidjson/internal/stack.h
@@ -0,0 +1,230 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_INTERNAL_STACK_H_
+#define RAPIDJSON_INTERNAL_STACK_H_
+
+#include "../allocators.h"
+#include "swap.h"
+
+#if defined(__clang__)
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(c++98-compat)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+///////////////////////////////////////////////////////////////////////////////
+// Stack
+
+//! A type-unsafe stack for storing different types of data.
+/*! \tparam Allocator Allocator for allocating stack memory.
+*/
+template <typename Allocator>
+class Stack {
+public:
+ // Optimization note: Do not allocate memory for stack_ in constructor.
+ // Do it lazily when first Push() -> Expand() -> Resize().
+ Stack(Allocator* allocator, size_t stackCapacity) : allocator_(allocator), ownAllocator_(0), stack_(0), stackTop_(0), stackEnd_(0), initialCapacity_(stackCapacity) {
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ Stack(Stack&& rhs)
+ : allocator_(rhs.allocator_),
+ ownAllocator_(rhs.ownAllocator_),
+ stack_(rhs.stack_),
+ stackTop_(rhs.stackTop_),
+ stackEnd_(rhs.stackEnd_),
+ initialCapacity_(rhs.initialCapacity_)
+ {
+ rhs.allocator_ = 0;
+ rhs.ownAllocator_ = 0;
+ rhs.stack_ = 0;
+ rhs.stackTop_ = 0;
+ rhs.stackEnd_ = 0;
+ rhs.initialCapacity_ = 0;
+ }
+#endif
+
+ ~Stack() {
+ Destroy();
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ Stack& operator=(Stack&& rhs) {
+ if (&rhs != this)
+ {
+ Destroy();
+
+ allocator_ = rhs.allocator_;
+ ownAllocator_ = rhs.ownAllocator_;
+ stack_ = rhs.stack_;
+ stackTop_ = rhs.stackTop_;
+ stackEnd_ = rhs.stackEnd_;
+ initialCapacity_ = rhs.initialCapacity_;
+
+ rhs.allocator_ = 0;
+ rhs.ownAllocator_ = 0;
+ rhs.stack_ = 0;
+ rhs.stackTop_ = 0;
+ rhs.stackEnd_ = 0;
+ rhs.initialCapacity_ = 0;
+ }
+ return *this;
+ }
+#endif
+
+ void Swap(Stack& rhs) RAPIDJSON_NOEXCEPT {
+ internal::Swap(allocator_, rhs.allocator_);
+ internal::Swap(ownAllocator_, rhs.ownAllocator_);
+ internal::Swap(stack_, rhs.stack_);
+ internal::Swap(stackTop_, rhs.stackTop_);
+ internal::Swap(stackEnd_, rhs.stackEnd_);
+ internal::Swap(initialCapacity_, rhs.initialCapacity_);
+ }
+
+ void Clear() { stackTop_ = stack_; }
+
+ void ShrinkToFit() {
+ if (Empty()) {
+ // If the stack is empty, completely deallocate the memory.
+ Allocator::Free(stack_);
+ stack_ = 0;
+ stackTop_ = 0;
+ stackEnd_ = 0;
+ }
+ else
+ Resize(GetSize());
+ }
+
+ // Optimization note: try to minimize the size of this function for force inline.
+ // Expansion is run very infrequently, so it is moved to another (probably non-inline) function.
+ template<typename T>
+ RAPIDJSON_FORCEINLINE void Reserve(size_t count = 1) {
+ // Expand the stack if needed
+ if (RAPIDJSON_UNLIKELY(stackTop_ + sizeof(T) * count > stackEnd_))
+ Expand<T>(count);
+ }
+
+ template<typename T>
+ RAPIDJSON_FORCEINLINE T* Push(size_t count = 1) {
+ Reserve<T>(count);
+ return PushUnsafe<T>(count);
+ }
+
+ template<typename T>
+ RAPIDJSON_FORCEINLINE T* PushUnsafe(size_t count = 1) {
+ RAPIDJSON_ASSERT(stackTop_ + sizeof(T) * count <= stackEnd_);
+ T* ret = reinterpret_cast<T*>(stackTop_);
+ stackTop_ += sizeof(T) * count;
+ return ret;
+ }
+
+ template<typename T>
+ T* Pop(size_t count) {
+ RAPIDJSON_ASSERT(GetSize() >= count * sizeof(T));
+ stackTop_ -= count * sizeof(T);
+ return reinterpret_cast<T*>(stackTop_);
+ }
+
+ template<typename T>
+ T* Top() {
+ RAPIDJSON_ASSERT(GetSize() >= sizeof(T));
+ return reinterpret_cast<T*>(stackTop_ - sizeof(T));
+ }
+
+ template<typename T>
+ const T* Top() const {
+ RAPIDJSON_ASSERT(GetSize() >= sizeof(T));
+ return reinterpret_cast<T*>(stackTop_ - sizeof(T));
+ }
+
+ template<typename T>
+ T* End() { return reinterpret_cast<T*>(stackTop_); }
+
+ template<typename T>
+ const T* End() const { return reinterpret_cast<T*>(stackTop_); }
+
+ template<typename T>
+ T* Bottom() { return reinterpret_cast<T*>(stack_); }
+
+ template<typename T>
+ const T* Bottom() const { return reinterpret_cast<T*>(stack_); }
+
+ bool HasAllocator() const {
+ return allocator_ != 0;
+ }
+
+ Allocator& GetAllocator() {
+ RAPIDJSON_ASSERT(allocator_);
+ return *allocator_;
+ }
+
+ bool Empty() const { return stackTop_ == stack_; }
+ size_t GetSize() const { return static_cast<size_t>(stackTop_ - stack_); }
+ size_t GetCapacity() const { return static_cast<size_t>(stackEnd_ - stack_); }
+
+private:
+ template<typename T>
+ void Expand(size_t count) {
+ // Only expand the capacity if the current stack exists. Otherwise just create a stack with initial capacity.
+ size_t newCapacity;
+ if (stack_ == 0) {
+ if (!allocator_)
+ ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
+ newCapacity = initialCapacity_;
+ } else {
+ newCapacity = GetCapacity();
+ newCapacity += (newCapacity + 1) / 2;
+ }
+ size_t newSize = GetSize() + sizeof(T) * count;
+ if (newCapacity < newSize)
+ newCapacity = newSize;
+
+ Resize(newCapacity);
+ }
+
+ void Resize(size_t newCapacity) {
+ const size_t size = GetSize(); // Backup the current size
+ stack_ = static_cast<char*>(allocator_->Realloc(stack_, GetCapacity(), newCapacity));
+ stackTop_ = stack_ + size;
+ stackEnd_ = stack_ + newCapacity;
+ }
+
+ void Destroy() {
+ Allocator::Free(stack_);
+ RAPIDJSON_DELETE(ownAllocator_); // Only delete if it is owned by the stack
+ }
+
+ // Prohibit copy constructor & assignment operator.
+ Stack(const Stack&);
+ Stack& operator=(const Stack&);
+
+ Allocator* allocator_;
+ Allocator* ownAllocator_;
+ char *stack_;
+ char *stackTop_;
+ char *stackEnd_;
+ size_t initialCapacity_;
+};
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#if defined(__clang__)
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_STACK_H_
diff --git a/include/rapidjson/internal/strfunc.h b/include/rapidjson/internal/strfunc.h
new file mode 100644
index 00000000..2edfae52
--- /dev/null
+++ b/include/rapidjson/internal/strfunc.h
@@ -0,0 +1,55 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_INTERNAL_STRFUNC_H_
+#define RAPIDJSON_INTERNAL_STRFUNC_H_
+
+#include "../stream.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+//! Custom strlen() which works on different character types.
+/*! \tparam Ch Character type (e.g. char, wchar_t, short)
+ \param s Null-terminated input string.
+ \return Number of characters in the string.
+ \note This has the same semantics as strlen(), the return value is not number of Unicode codepoints.
+*/
+template <typename Ch>
+inline SizeType StrLen(const Ch* s) {
+ const Ch* p = s;
+ while (*p) ++p;
+ return SizeType(p - s);
+}
+
+//! Returns number of code points in a encoded string.
+template<typename Encoding>
+bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) {
+ GenericStringStream<Encoding> is(s);
+ const typename Encoding::Ch* end = s + length;
+ SizeType count = 0;
+ while (is.src_ < end) {
+ unsigned codepoint;
+ if (!Encoding::Decode(is, &codepoint))
+ return false;
+ count++;
+ }
+ *outCount = count;
+ return true;
+}
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_INTERNAL_STRFUNC_H_
diff --git a/include/rapidjson/internal/strtod.h b/include/rapidjson/internal/strtod.h
new file mode 100644
index 00000000..289c413b
--- /dev/null
+++ b/include/rapidjson/internal/strtod.h
@@ -0,0 +1,269 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_STRTOD_
+#define RAPIDJSON_STRTOD_
+
+#include "ieee754.h"
+#include "biginteger.h"
+#include "diyfp.h"
+#include "pow10.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+inline double FastPath(double significand, int exp) {
+ if (exp < -308)
+ return 0.0;
+ else if (exp >= 0)
+ return significand * internal::Pow10(exp);
+ else
+ return significand / internal::Pow10(-exp);
+}
+
+inline double StrtodNormalPrecision(double d, int p) {
+ if (p < -308) {
+ // Prevent expSum < -308, making Pow10(p) = 0
+ d = FastPath(d, -308);
+ d = FastPath(d, p + 308);
+ }
+ else
+ d = FastPath(d, p);
+ return d;
+}
+
+template <typename T>
+inline T Min3(T a, T b, T c) {
+ T m = a;
+ if (m > b) m = b;
+ if (m > c) m = c;
+ return m;
+}
+
+inline int CheckWithinHalfULP(double b, const BigInteger& d, int dExp) {
+ const Double db(b);
+ const uint64_t bInt = db.IntegerSignificand();
+ const int bExp = db.IntegerExponent();
+ const int hExp = bExp - 1;
+
+ int dS_Exp2 = 0, dS_Exp5 = 0, bS_Exp2 = 0, bS_Exp5 = 0, hS_Exp2 = 0, hS_Exp5 = 0;
+
+ // Adjust for decimal exponent
+ if (dExp >= 0) {
+ dS_Exp2 += dExp;
+ dS_Exp5 += dExp;
+ }
+ else {
+ bS_Exp2 -= dExp;
+ bS_Exp5 -= dExp;
+ hS_Exp2 -= dExp;
+ hS_Exp5 -= dExp;
+ }
+
+ // Adjust for binary exponent
+ if (bExp >= 0)
+ bS_Exp2 += bExp;
+ else {
+ dS_Exp2 -= bExp;
+ hS_Exp2 -= bExp;
+ }
+
+ // Adjust for half ulp exponent
+ if (hExp >= 0)
+ hS_Exp2 += hExp;
+ else {
+ dS_Exp2 -= hExp;
+ bS_Exp2 -= hExp;
+ }
+
+ // Remove common power of two factor from all three scaled values
+ int common_Exp2 = Min3(dS_Exp2, bS_Exp2, hS_Exp2);
+ dS_Exp2 -= common_Exp2;
+ bS_Exp2 -= common_Exp2;
+ hS_Exp2 -= common_Exp2;
+
+ BigInteger dS = d;
+ dS.MultiplyPow5(static_cast<unsigned>(dS_Exp5)) <<= static_cast<unsigned>(dS_Exp2);
+
+ BigInteger bS(bInt);
+ bS.MultiplyPow5(static_cast<unsigned>(bS_Exp5)) <<= static_cast<unsigned>(bS_Exp2);
+
+ BigInteger hS(1);
+ hS.MultiplyPow5(static_cast<unsigned>(hS_Exp5)) <<= static_cast<unsigned>(hS_Exp2);
+
+ BigInteger delta(0);
+ dS.Difference(bS, &delta);
+
+ return delta.Compare(hS);
+}
+
+inline bool StrtodFast(double d, int p, double* result) {
+ // Use fast path for string-to-double conversion if possible
+ // see http://www.exploringbinary.com/fast-path-decimal-to-floating-point-conversion/
+ if (p > 22 && p < 22 + 16) {
+ // Fast Path Cases In Disguise
+ d *= internal::Pow10(p - 22);
+ p = 22;
+ }
+
+ if (p >= -22 && p <= 22 && d <= 9007199254740991.0) { // 2^53 - 1
+ *result = FastPath(d, p);
+ return true;
+ }
+ else
+ return false;
+}
+
+// Compute an approximation and see if it is within 1/2 ULP
+inline bool StrtodDiyFp(const char* decimals, size_t length, size_t decimalPosition, int exp, double* result) {
+ uint64_t significand = 0;
+ size_t i = 0; // 2^64 - 1 = 18446744073709551615, 1844674407370955161 = 0x1999999999999999
+ for (; i < length; i++) {
+ if (significand > RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) ||
+ (significand == RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) && decimals[i] > '5'))
+ break;
+ significand = significand * 10u + static_cast<unsigned>(decimals[i] - '0');
+ }
+
+ if (i < length && decimals[i] >= '5') // Rounding
+ significand++;
+
+ size_t remaining = length - i;
+ const unsigned kUlpShift = 3;
+ const unsigned kUlp = 1 << kUlpShift;
+ int64_t error = (remaining == 0) ? 0 : kUlp / 2;
+
+ DiyFp v(significand, 0);
+ v = v.Normalize();
+ error <<= -v.e;
+
+ const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(i) + exp;
+
+ int actualExp;
+ DiyFp cachedPower = GetCachedPower10(dExp, &actualExp);
+ if (actualExp != dExp) {
+ static const DiyFp kPow10[] = {
+ DiyFp(RAPIDJSON_UINT64_C2(0xa0000000, 00000000), -60), // 10^1
+ DiyFp(RAPIDJSON_UINT64_C2(0xc8000000, 00000000), -57), // 10^2
+ DiyFp(RAPIDJSON_UINT64_C2(0xfa000000, 00000000), -54), // 10^3
+ DiyFp(RAPIDJSON_UINT64_C2(0x9c400000, 00000000), -50), // 10^4
+ DiyFp(RAPIDJSON_UINT64_C2(0xc3500000, 00000000), -47), // 10^5
+ DiyFp(RAPIDJSON_UINT64_C2(0xf4240000, 00000000), -44), // 10^6
+ DiyFp(RAPIDJSON_UINT64_C2(0x98968000, 00000000), -40) // 10^7
+ };
+ int adjustment = dExp - actualExp - 1;
+ RAPIDJSON_ASSERT(adjustment >= 0 && adjustment < 7);
+ v = v * kPow10[adjustment];
+ if (length + static_cast<unsigned>(adjustment)> 19u) // has more digits than decimal digits in 64-bit
+ error += kUlp / 2;
+ }
+
+ v = v * cachedPower;
+
+ error += kUlp + (error == 0 ? 0 : 1);
+
+ const int oldExp = v.e;
+ v = v.Normalize();
+ error <<= oldExp - v.e;
+
+ const unsigned effectiveSignificandSize = Double::EffectiveSignificandSize(64 + v.e);
+ unsigned precisionSize = 64 - effectiveSignificandSize;
+ if (precisionSize + kUlpShift >= 64) {
+ unsigned scaleExp = (precisionSize + kUlpShift) - 63;
+ v.f >>= scaleExp;
+ v.e += scaleExp;
+ error = (error >> scaleExp) + 1 + static_cast<int>(kUlp);
+ precisionSize -= scaleExp;
+ }
+
+ DiyFp rounded(v.f >> precisionSize, v.e + static_cast<int>(precisionSize));
+ const uint64_t precisionBits = (v.f & ((uint64_t(1) << precisionSize) - 1)) * kUlp;
+ const uint64_t halfWay = (uint64_t(1) << (precisionSize - 1)) * kUlp;
+ if (precisionBits >= halfWay + static_cast<unsigned>(error)) {
+ rounded.f++;
+ if (rounded.f & (DiyFp::kDpHiddenBit << 1)) { // rounding overflows mantissa (issue #340)
+ rounded.f >>= 1;
+ rounded.e++;
+ }
+ }
+
+ *result = rounded.ToDouble();
+
+ return halfWay - static_cast<unsigned>(error) >= precisionBits || precisionBits >= halfWay + static_cast<unsigned>(error);
+}
+
+inline double StrtodBigInteger(double approx, const char* decimals, size_t length, size_t decimalPosition, int exp) {
+ const BigInteger dInt(decimals, length);
+ const int dExp = static_cast<int>(decimalPosition) - static_cast<int>(length) + exp;
+ Double a(approx);
+ int cmp = CheckWithinHalfULP(a.Value(), dInt, dExp);
+ if (cmp < 0)
+ return a.Value(); // within half ULP
+ else if (cmp == 0) {
+ // Round towards even
+ if (a.Significand() & 1)
+ return a.NextPositiveDouble();
+ else
+ return a.Value();
+ }
+ else // adjustment
+ return a.NextPositiveDouble();
+}
+
+inline double StrtodFullPrecision(double d, int p, const char* decimals, size_t length, size_t decimalPosition, int exp) {
+ RAPIDJSON_ASSERT(d >= 0.0);
+ RAPIDJSON_ASSERT(length >= 1);
+
+ double result;
+ if (StrtodFast(d, p, &result))
+ return result;
+
+ // Trim leading zeros
+ while (*decimals == '0' && length > 1) {
+ length--;
+ decimals++;
+ decimalPosition--;
+ }
+
+ // Trim trailing zeros
+ while (decimals[length - 1] == '0' && length > 1) {
+ length--;
+ decimalPosition--;
+ exp++;
+ }
+
+ // Trim right-most digits
+ const int kMaxDecimalDigit = 780;
+ if (static_cast<int>(length) > kMaxDecimalDigit) {
+ int delta = (static_cast<int>(length) - kMaxDecimalDigit);
+ exp += delta;
+ decimalPosition -= static_cast<unsigned>(delta);
+ length = kMaxDecimalDigit;
+ }
+
+ // If too small, underflow to zero
+ if (int(length) + exp < -324)
+ return 0.0;
+
+ if (StrtodDiyFp(decimals, length, decimalPosition, exp, &result))
+ return result;
+
+ // Use approximation from StrtodDiyFp and make adjustment with BigInteger comparison
+ return StrtodBigInteger(result, decimals, length, decimalPosition, exp);
+}
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_STRTOD_
diff --git a/include/rapidjson/internal/swap.h b/include/rapidjson/internal/swap.h
new file mode 100644
index 00000000..666e49f9
--- /dev/null
+++ b/include/rapidjson/internal/swap.h
@@ -0,0 +1,46 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_INTERNAL_SWAP_H_
+#define RAPIDJSON_INTERNAL_SWAP_H_
+
+#include "../rapidjson.h"
+
+#if defined(__clang__)
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(c++98-compat)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+namespace internal {
+
+//! Custom swap() to avoid dependency on C++ <algorithm> header
+/*! \tparam T Type of the arguments to swap, should be instantiated with primitive C++ types only.
+ \note This has the same semantics as std::swap().
+*/
+template <typename T>
+inline void Swap(T& a, T& b) RAPIDJSON_NOEXCEPT {
+ T tmp = a;
+ a = b;
+ b = tmp;
+}
+
+} // namespace internal
+RAPIDJSON_NAMESPACE_END
+
+#if defined(__clang__)
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_INTERNAL_SWAP_H_
diff --git a/include/rapidjson/istreamwrapper.h b/include/rapidjson/istreamwrapper.h
new file mode 100644
index 00000000..f5fe2897
--- /dev/null
+++ b/include/rapidjson/istreamwrapper.h
@@ -0,0 +1,115 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_ISTREAMWRAPPER_H_
+#define RAPIDJSON_ISTREAMWRAPPER_H_
+
+#include "stream.h"
+#include <iosfwd>
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(4351) // new behavior: elements of array 'array' will be default initialized
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Wrapper of \c std::basic_istream into RapidJSON's Stream concept.
+/*!
+ The classes can be wrapped including but not limited to:
+
+ - \c std::istringstream
+ - \c std::stringstream
+ - \c std::wistringstream
+ - \c std::wstringstream
+ - \c std::ifstream
+ - \c std::fstream
+ - \c std::wifstream
+ - \c std::wfstream
+
+ \tparam StreamType Class derived from \c std::basic_istream.
+*/
+
+template <typename StreamType>
+class BasicIStreamWrapper {
+public:
+ typedef typename StreamType::char_type Ch;
+ BasicIStreamWrapper(StreamType& stream) : stream_(stream), count_(), peekBuffer_() {}
+
+ Ch Peek() const {
+ typename StreamType::int_type c = stream_.peek();
+ return RAPIDJSON_LIKELY(c != StreamType::traits_type::eof()) ? static_cast<Ch>(c) : '\0';
+ }
+
+ Ch Take() {
+ typename StreamType::int_type c = stream_.get();
+ if (RAPIDJSON_LIKELY(c != StreamType::traits_type::eof())) {
+ count_++;
+ return static_cast<Ch>(c);
+ }
+ else
+ return '\0';
+ }
+
+ // tellg() may return -1 when failed. So we count by ourself.
+ size_t Tell() const { return count_; }
+
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ void Put(Ch) { RAPIDJSON_ASSERT(false); }
+ void Flush() { RAPIDJSON_ASSERT(false); }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+ // For encoding detection only.
+ const Ch* Peek4() const {
+ RAPIDJSON_ASSERT(sizeof(Ch) == 1); // Only usable for byte stream.
+ int i;
+ bool hasError = false;
+ for (i = 0; i < 4; ++i) {
+ typename StreamType::int_type c = stream_.get();
+ if (c == StreamType::traits_type::eof()) {
+ hasError = true;
+ stream_.clear();
+ break;
+ }
+ peekBuffer_[i] = static_cast<Ch>(c);
+ }
+ for (--i; i >= 0; --i)
+ stream_.putback(peekBuffer_[i]);
+ return !hasError ? peekBuffer_ : 0;
+ }
+
+private:
+ BasicIStreamWrapper(const BasicIStreamWrapper&);
+ BasicIStreamWrapper& operator=(const BasicIStreamWrapper&);
+
+ StreamType& stream_;
+ size_t count_; //!< Number of characters read. Note:
+ mutable Ch peekBuffer_[4];
+};
+
+typedef BasicIStreamWrapper<std::istream> IStreamWrapper;
+typedef BasicIStreamWrapper<std::wistream> WIStreamWrapper;
+
+#if defined(__clang__) || defined(_MSC_VER)
+RAPIDJSON_DIAG_POP
+#endif
+
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_ISTREAMWRAPPER_H_
diff --git a/include/rapidjson/memorybuffer.h b/include/rapidjson/memorybuffer.h
new file mode 100644
index 00000000..39bee1de
--- /dev/null
+++ b/include/rapidjson/memorybuffer.h
@@ -0,0 +1,70 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_MEMORYBUFFER_H_
+#define RAPIDJSON_MEMORYBUFFER_H_
+
+#include "stream.h"
+#include "internal/stack.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Represents an in-memory output byte stream.
+/*!
+ This class is mainly for being wrapped by EncodedOutputStream or AutoUTFOutputStream.
+
+ It is similar to FileWriteBuffer but the destination is an in-memory buffer instead of a file.
+
+ Differences between MemoryBuffer and StringBuffer:
+ 1. StringBuffer has Encoding but MemoryBuffer is only a byte buffer.
+ 2. StringBuffer::GetString() returns a null-terminated string. MemoryBuffer::GetBuffer() returns a buffer without terminator.
+
+ \tparam Allocator type for allocating memory buffer.
+ \note implements Stream concept
+*/
+template <typename Allocator = CrtAllocator>
+struct GenericMemoryBuffer {
+ typedef char Ch; // byte
+
+ GenericMemoryBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
+
+ void Put(Ch c) { *stack_.template Push<Ch>() = c; }
+ void Flush() {}
+
+ void Clear() { stack_.Clear(); }
+ void ShrinkToFit() { stack_.ShrinkToFit(); }
+ Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
+ void Pop(size_t count) { stack_.template Pop<Ch>(count); }
+
+ const Ch* GetBuffer() const {
+ return stack_.template Bottom<Ch>();
+ }
+
+ size_t GetSize() const { return stack_.GetSize(); }
+
+ static const size_t kDefaultCapacity = 256;
+ mutable internal::Stack<Allocator> stack_;
+};
+
+typedef GenericMemoryBuffer<> MemoryBuffer;
+
+//! Implement specialized version of PutN() with memset() for better performance.
+template<>
+inline void PutN(MemoryBuffer& memoryBuffer, char c, size_t n) {
+ std::memset(memoryBuffer.stack_.Push<char>(n), c, n * sizeof(c));
+}
+
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_MEMORYBUFFER_H_
diff --git a/include/rapidjson/memorystream.h b/include/rapidjson/memorystream.h
new file mode 100644
index 00000000..1d71d8a4
--- /dev/null
+++ b/include/rapidjson/memorystream.h
@@ -0,0 +1,71 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_MEMORYSTREAM_H_
+#define RAPIDJSON_MEMORYSTREAM_H_
+
+#include "stream.h"
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(unreachable-code)
+RAPIDJSON_DIAG_OFF(missing-noreturn)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Represents an in-memory input byte stream.
+/*!
+ This class is mainly for being wrapped by EncodedInputStream or AutoUTFInputStream.
+
+ It is similar to FileReadBuffer but the source is an in-memory buffer instead of a file.
+
+ Differences between MemoryStream and StringStream:
+ 1. StringStream has encoding but MemoryStream is a byte stream.
+ 2. MemoryStream needs size of the source buffer and the buffer don't need to be null terminated. StringStream assume null-terminated string as source.
+ 3. MemoryStream supports Peek4() for encoding detection. StringStream is specified with an encoding so it should not have Peek4().
+ \note implements Stream concept
+*/
+struct MemoryStream {
+ typedef char Ch; // byte
+
+ MemoryStream(const Ch *src, size_t size) : src_(src), begin_(src), end_(src + size), size_(size) {}
+
+ Ch Peek() const { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_; }
+ Ch Take() { return RAPIDJSON_UNLIKELY(src_ == end_) ? '\0' : *src_++; }
+ size_t Tell() const { return static_cast<size_t>(src_ - begin_); }
+
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ void Put(Ch) { RAPIDJSON_ASSERT(false); }
+ void Flush() { RAPIDJSON_ASSERT(false); }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+ // For encoding detection only.
+ const Ch* Peek4() const {
+ return Tell() + 4 <= size_ ? src_ : 0;
+ }
+
+ const Ch* src_; //!< Current read position.
+ const Ch* begin_; //!< Original head of the string.
+ const Ch* end_; //!< End of stream.
+ size_t size_; //!< Size of the stream.
+};
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_MEMORYBUFFER_H_
diff --git a/include/rapidjson/msinttypes/inttypes.h b/include/rapidjson/msinttypes/inttypes.h
new file mode 100644
index 00000000..18111286
--- /dev/null
+++ b/include/rapidjson/msinttypes/inttypes.h
@@ -0,0 +1,316 @@
+// ISO C9x compliant inttypes.h for Microsoft Visual Studio
+// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
+//
+// Copyright (c) 2006-2013 Alexander Chemeris
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+//
+// 3. Neither the name of the product nor the names of its 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 ``AS IS'' AND ANY EXPRESS OR IMPLIED
+// 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.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+// The above software in this distribution may have been modified by
+// THL A29 Limited ("Tencent Modifications").
+// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited.
+
+#ifndef _MSC_VER // [
+#error "Use this header only with Microsoft Visual C++ compilers!"
+#endif // _MSC_VER ]
+
+#ifndef _MSC_INTTYPES_H_ // [
+#define _MSC_INTTYPES_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif
+
+#include "stdint.h"
+
+// miloyip: VC supports inttypes.h since VC2013
+#if _MSC_VER >= 1800
+#include <inttypes.h>
+#else
+
+// 7.8 Format conversion of integer types
+
+typedef struct {
+ intmax_t quot;
+ intmax_t rem;
+} imaxdiv_t;
+
+// 7.8.1 Macros for format specifiers
+
+#if !defined(__cplusplus) || defined(__STDC_FORMAT_MACROS) // [ See footnote 185 at page 198
+
+// The fprintf macros for signed integers are:
+#define PRId8 "d"
+#define PRIi8 "i"
+#define PRIdLEAST8 "d"
+#define PRIiLEAST8 "i"
+#define PRIdFAST8 "d"
+#define PRIiFAST8 "i"
+
+#define PRId16 "hd"
+#define PRIi16 "hi"
+#define PRIdLEAST16 "hd"
+#define PRIiLEAST16 "hi"
+#define PRIdFAST16 "hd"
+#define PRIiFAST16 "hi"
+
+#define PRId32 "I32d"
+#define PRIi32 "I32i"
+#define PRIdLEAST32 "I32d"
+#define PRIiLEAST32 "I32i"
+#define PRIdFAST32 "I32d"
+#define PRIiFAST32 "I32i"
+
+#define PRId64 "I64d"
+#define PRIi64 "I64i"
+#define PRIdLEAST64 "I64d"
+#define PRIiLEAST64 "I64i"
+#define PRIdFAST64 "I64d"
+#define PRIiFAST64 "I64i"
+
+#define PRIdMAX "I64d"
+#define PRIiMAX "I64i"
+
+#define PRIdPTR "Id"
+#define PRIiPTR "Ii"
+
+// The fprintf macros for unsigned integers are:
+#define PRIo8 "o"
+#define PRIu8 "u"
+#define PRIx8 "x"
+#define PRIX8 "X"
+#define PRIoLEAST8 "o"
+#define PRIuLEAST8 "u"
+#define PRIxLEAST8 "x"
+#define PRIXLEAST8 "X"
+#define PRIoFAST8 "o"
+#define PRIuFAST8 "u"
+#define PRIxFAST8 "x"
+#define PRIXFAST8 "X"
+
+#define PRIo16 "ho"
+#define PRIu16 "hu"
+#define PRIx16 "hx"
+#define PRIX16 "hX"
+#define PRIoLEAST16 "ho"
+#define PRIuLEAST16 "hu"
+#define PRIxLEAST16 "hx"
+#define PRIXLEAST16 "hX"
+#define PRIoFAST16 "ho"
+#define PRIuFAST16 "hu"
+#define PRIxFAST16 "hx"
+#define PRIXFAST16 "hX"
+
+#define PRIo32 "I32o"
+#define PRIu32 "I32u"
+#define PRIx32 "I32x"
+#define PRIX32 "I32X"
+#define PRIoLEAST32 "I32o"
+#define PRIuLEAST32 "I32u"
+#define PRIxLEAST32 "I32x"
+#define PRIXLEAST32 "I32X"
+#define PRIoFAST32 "I32o"
+#define PRIuFAST32 "I32u"
+#define PRIxFAST32 "I32x"
+#define PRIXFAST32 "I32X"
+
+#define PRIo64 "I64o"
+#define PRIu64 "I64u"
+#define PRIx64 "I64x"
+#define PRIX64 "I64X"
+#define PRIoLEAST64 "I64o"
+#define PRIuLEAST64 "I64u"
+#define PRIxLEAST64 "I64x"
+#define PRIXLEAST64 "I64X"
+#define PRIoFAST64 "I64o"
+#define PRIuFAST64 "I64u"
+#define PRIxFAST64 "I64x"
+#define PRIXFAST64 "I64X"
+
+#define PRIoMAX "I64o"
+#define PRIuMAX "I64u"
+#define PRIxMAX "I64x"
+#define PRIXMAX "I64X"
+
+#define PRIoPTR "Io"
+#define PRIuPTR "Iu"
+#define PRIxPTR "Ix"
+#define PRIXPTR "IX"
+
+// The fscanf macros for signed integers are:
+#define SCNd8 "d"
+#define SCNi8 "i"
+#define SCNdLEAST8 "d"
+#define SCNiLEAST8 "i"
+#define SCNdFAST8 "d"
+#define SCNiFAST8 "i"
+
+#define SCNd16 "hd"
+#define SCNi16 "hi"
+#define SCNdLEAST16 "hd"
+#define SCNiLEAST16 "hi"
+#define SCNdFAST16 "hd"
+#define SCNiFAST16 "hi"
+
+#define SCNd32 "ld"
+#define SCNi32 "li"
+#define SCNdLEAST32 "ld"
+#define SCNiLEAST32 "li"
+#define SCNdFAST32 "ld"
+#define SCNiFAST32 "li"
+
+#define SCNd64 "I64d"
+#define SCNi64 "I64i"
+#define SCNdLEAST64 "I64d"
+#define SCNiLEAST64 "I64i"
+#define SCNdFAST64 "I64d"
+#define SCNiFAST64 "I64i"
+
+#define SCNdMAX "I64d"
+#define SCNiMAX "I64i"
+
+#ifdef _WIN64 // [
+# define SCNdPTR "I64d"
+# define SCNiPTR "I64i"
+#else // _WIN64 ][
+# define SCNdPTR "ld"
+# define SCNiPTR "li"
+#endif // _WIN64 ]
+
+// The fscanf macros for unsigned integers are:
+#define SCNo8 "o"
+#define SCNu8 "u"
+#define SCNx8 "x"
+#define SCNX8 "X"
+#define SCNoLEAST8 "o"
+#define SCNuLEAST8 "u"
+#define SCNxLEAST8 "x"
+#define SCNXLEAST8 "X"
+#define SCNoFAST8 "o"
+#define SCNuFAST8 "u"
+#define SCNxFAST8 "x"
+#define SCNXFAST8 "X"
+
+#define SCNo16 "ho"
+#define SCNu16 "hu"
+#define SCNx16 "hx"
+#define SCNX16 "hX"
+#define SCNoLEAST16 "ho"
+#define SCNuLEAST16 "hu"
+#define SCNxLEAST16 "hx"
+#define SCNXLEAST16 "hX"
+#define SCNoFAST16 "ho"
+#define SCNuFAST16 "hu"
+#define SCNxFAST16 "hx"
+#define SCNXFAST16 "hX"
+
+#define SCNo32 "lo"
+#define SCNu32 "lu"
+#define SCNx32 "lx"
+#define SCNX32 "lX"
+#define SCNoLEAST32 "lo"
+#define SCNuLEAST32 "lu"
+#define SCNxLEAST32 "lx"
+#define SCNXLEAST32 "lX"
+#define SCNoFAST32 "lo"
+#define SCNuFAST32 "lu"
+#define SCNxFAST32 "lx"
+#define SCNXFAST32 "lX"
+
+#define SCNo64 "I64o"
+#define SCNu64 "I64u"
+#define SCNx64 "I64x"
+#define SCNX64 "I64X"
+#define SCNoLEAST64 "I64o"
+#define SCNuLEAST64 "I64u"
+#define SCNxLEAST64 "I64x"
+#define SCNXLEAST64 "I64X"
+#define SCNoFAST64 "I64o"
+#define SCNuFAST64 "I64u"
+#define SCNxFAST64 "I64x"
+#define SCNXFAST64 "I64X"
+
+#define SCNoMAX "I64o"
+#define SCNuMAX "I64u"
+#define SCNxMAX "I64x"
+#define SCNXMAX "I64X"
+
+#ifdef _WIN64 // [
+# define SCNoPTR "I64o"
+# define SCNuPTR "I64u"
+# define SCNxPTR "I64x"
+# define SCNXPTR "I64X"
+#else // _WIN64 ][
+# define SCNoPTR "lo"
+# define SCNuPTR "lu"
+# define SCNxPTR "lx"
+# define SCNXPTR "lX"
+#endif // _WIN64 ]
+
+#endif // __STDC_FORMAT_MACROS ]
+
+// 7.8.2 Functions for greatest-width integer types
+
+// 7.8.2.1 The imaxabs function
+#define imaxabs _abs64
+
+// 7.8.2.2 The imaxdiv function
+
+// This is modified version of div() function from Microsoft's div.c found
+// in %MSVC.NET%\crt\src\div.c
+#ifdef STATIC_IMAXDIV // [
+static
+#else // STATIC_IMAXDIV ][
+_inline
+#endif // STATIC_IMAXDIV ]
+imaxdiv_t __cdecl imaxdiv(intmax_t numer, intmax_t denom)
+{
+ imaxdiv_t result;
+
+ result.quot = numer / denom;
+ result.rem = numer % denom;
+
+ if (numer < 0 && result.rem > 0) {
+ // did division wrong; must fix up
+ ++result.quot;
+ result.rem -= denom;
+ }
+
+ return result;
+}
+
+// 7.8.2.3 The strtoimax and strtoumax functions
+#define strtoimax _strtoi64
+#define strtoumax _strtoui64
+
+// 7.8.2.4 The wcstoimax and wcstoumax functions
+#define wcstoimax _wcstoi64
+#define wcstoumax _wcstoui64
+
+#endif // _MSC_VER >= 1800
+
+#endif // _MSC_INTTYPES_H_ ]
diff --git a/include/rapidjson/msinttypes/stdint.h b/include/rapidjson/msinttypes/stdint.h
new file mode 100644
index 00000000..3d4477b9
--- /dev/null
+++ b/include/rapidjson/msinttypes/stdint.h
@@ -0,0 +1,300 @@
+// ISO C9x compliant stdint.h for Microsoft Visual Studio
+// Based on ISO/IEC 9899:TC2 Committee draft (May 6, 2005) WG14/N1124
+//
+// Copyright (c) 2006-2013 Alexander Chemeris
+//
+// Redistribution and use in source and binary forms, with or without
+// modification, are permitted provided that the following conditions are met:
+//
+// 1. Redistributions of source code must retain the above copyright notice,
+// this list of conditions and the following disclaimer.
+//
+// 2. Redistributions in binary form must reproduce the above copyright
+// notice, this list of conditions and the following disclaimer in the
+// documentation and/or other materials provided with the distribution.
+//
+// 3. Neither the name of the product nor the names of its 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 ``AS IS'' AND ANY EXPRESS OR IMPLIED
+// 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.
+//
+///////////////////////////////////////////////////////////////////////////////
+
+// The above software in this distribution may have been modified by
+// THL A29 Limited ("Tencent Modifications").
+// All Tencent Modifications are Copyright (C) 2015 THL A29 Limited.
+
+#ifndef _MSC_VER // [
+#error "Use this header only with Microsoft Visual C++ compilers!"
+#endif // _MSC_VER ]
+
+#ifndef _MSC_STDINT_H_ // [
+#define _MSC_STDINT_H_
+
+#if _MSC_VER > 1000
+#pragma once
+#endif
+
+// miloyip: Originally Visual Studio 2010 uses its own stdint.h. However it generates warning with INT64_C(), so change to use this file for vs2010.
+#if _MSC_VER >= 1600 // [
+#include <stdint.h>
+
+#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
+
+#undef INT8_C
+#undef INT16_C
+#undef INT32_C
+#undef INT64_C
+#undef UINT8_C
+#undef UINT16_C
+#undef UINT32_C
+#undef UINT64_C
+
+// 7.18.4.1 Macros for minimum-width integer constants
+
+#define INT8_C(val) val##i8
+#define INT16_C(val) val##i16
+#define INT32_C(val) val##i32
+#define INT64_C(val) val##i64
+
+#define UINT8_C(val) val##ui8
+#define UINT16_C(val) val##ui16
+#define UINT32_C(val) val##ui32
+#define UINT64_C(val) val##ui64
+
+// 7.18.4.2 Macros for greatest-width integer constants
+// These #ifndef's are needed to prevent collisions with <boost/cstdint.hpp>.
+// Check out Issue 9 for the details.
+#ifndef INTMAX_C // [
+# define INTMAX_C INT64_C
+#endif // INTMAX_C ]
+#ifndef UINTMAX_C // [
+# define UINTMAX_C UINT64_C
+#endif // UINTMAX_C ]
+
+#endif // __STDC_CONSTANT_MACROS ]
+
+#else // ] _MSC_VER >= 1700 [
+
+#include <limits.h>
+
+// For Visual Studio 6 in C++ mode and for many Visual Studio versions when
+// compiling for ARM we have to wrap <wchar.h> include with 'extern "C++" {}'
+// or compiler would give many errors like this:
+// error C2733: second C linkage of overloaded function 'wmemchr' not allowed
+#if defined(__cplusplus) && !defined(_M_ARM)
+extern "C" {
+#endif
+# include <wchar.h>
+#if defined(__cplusplus) && !defined(_M_ARM)
+}
+#endif
+
+// Define _W64 macros to mark types changing their size, like intptr_t.
+#ifndef _W64
+# if !defined(__midl) && (defined(_X86_) || defined(_M_IX86)) && _MSC_VER >= 1300
+# define _W64 __w64
+# else
+# define _W64
+# endif
+#endif
+
+
+// 7.18.1 Integer types
+
+// 7.18.1.1 Exact-width integer types
+
+// Visual Studio 6 and Embedded Visual C++ 4 doesn't
+// realize that, e.g. char has the same size as __int8
+// so we give up on __intX for them.
+#if (_MSC_VER < 1300)
+ typedef signed char int8_t;
+ typedef signed short int16_t;
+ typedef signed int int32_t;
+ typedef unsigned char uint8_t;
+ typedef unsigned short uint16_t;
+ typedef unsigned int uint32_t;
+#else
+ typedef signed __int8 int8_t;
+ typedef signed __int16 int16_t;
+ typedef signed __int32 int32_t;
+ typedef unsigned __int8 uint8_t;
+ typedef unsigned __int16 uint16_t;
+ typedef unsigned __int32 uint32_t;
+#endif
+typedef signed __int64 int64_t;
+typedef unsigned __int64 uint64_t;
+
+
+// 7.18.1.2 Minimum-width integer types
+typedef int8_t int_least8_t;
+typedef int16_t int_least16_t;
+typedef int32_t int_least32_t;
+typedef int64_t int_least64_t;
+typedef uint8_t uint_least8_t;
+typedef uint16_t uint_least16_t;
+typedef uint32_t uint_least32_t;
+typedef uint64_t uint_least64_t;
+
+// 7.18.1.3 Fastest minimum-width integer types
+typedef int8_t int_fast8_t;
+typedef int16_t int_fast16_t;
+typedef int32_t int_fast32_t;
+typedef int64_t int_fast64_t;
+typedef uint8_t uint_fast8_t;
+typedef uint16_t uint_fast16_t;
+typedef uint32_t uint_fast32_t;
+typedef uint64_t uint_fast64_t;
+
+// 7.18.1.4 Integer types capable of holding object pointers
+#ifdef _WIN64 // [
+ typedef signed __int64 intptr_t;
+ typedef unsigned __int64 uintptr_t;
+#else // _WIN64 ][
+ typedef _W64 signed int intptr_t;
+ typedef _W64 unsigned int uintptr_t;
+#endif // _WIN64 ]
+
+// 7.18.1.5 Greatest-width integer types
+typedef int64_t intmax_t;
+typedef uint64_t uintmax_t;
+
+
+// 7.18.2 Limits of specified-width integer types
+
+#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS) // [ See footnote 220 at page 257 and footnote 221 at page 259
+
+// 7.18.2.1 Limits of exact-width integer types
+#define INT8_MIN ((int8_t)_I8_MIN)
+#define INT8_MAX _I8_MAX
+#define INT16_MIN ((int16_t)_I16_MIN)
+#define INT16_MAX _I16_MAX
+#define INT32_MIN ((int32_t)_I32_MIN)
+#define INT32_MAX _I32_MAX
+#define INT64_MIN ((int64_t)_I64_MIN)
+#define INT64_MAX _I64_MAX
+#define UINT8_MAX _UI8_MAX
+#define UINT16_MAX _UI16_MAX
+#define UINT32_MAX _UI32_MAX
+#define UINT64_MAX _UI64_MAX
+
+// 7.18.2.2 Limits of minimum-width integer types
+#define INT_LEAST8_MIN INT8_MIN
+#define INT_LEAST8_MAX INT8_MAX
+#define INT_LEAST16_MIN INT16_MIN
+#define INT_LEAST16_MAX INT16_MAX
+#define INT_LEAST32_MIN INT32_MIN
+#define INT_LEAST32_MAX INT32_MAX
+#define INT_LEAST64_MIN INT64_MIN
+#define INT_LEAST64_MAX INT64_MAX
+#define UINT_LEAST8_MAX UINT8_MAX
+#define UINT_LEAST16_MAX UINT16_MAX
+#define UINT_LEAST32_MAX UINT32_MAX
+#define UINT_LEAST64_MAX UINT64_MAX
+
+// 7.18.2.3 Limits of fastest minimum-width integer types
+#define INT_FAST8_MIN INT8_MIN
+#define INT_FAST8_MAX INT8_MAX
+#define INT_FAST16_MIN INT16_MIN
+#define INT_FAST16_MAX INT16_MAX
+#define INT_FAST32_MIN INT32_MIN
+#define INT_FAST32_MAX INT32_MAX
+#define INT_FAST64_MIN INT64_MIN
+#define INT_FAST64_MAX INT64_MAX
+#define UINT_FAST8_MAX UINT8_MAX
+#define UINT_FAST16_MAX UINT16_MAX
+#define UINT_FAST32_MAX UINT32_MAX
+#define UINT_FAST64_MAX UINT64_MAX
+
+// 7.18.2.4 Limits of integer types capable of holding object pointers
+#ifdef _WIN64 // [
+# define INTPTR_MIN INT64_MIN
+# define INTPTR_MAX INT64_MAX
+# define UINTPTR_MAX UINT64_MAX
+#else // _WIN64 ][
+# define INTPTR_MIN INT32_MIN
+# define INTPTR_MAX INT32_MAX
+# define UINTPTR_MAX UINT32_MAX
+#endif // _WIN64 ]
+
+// 7.18.2.5 Limits of greatest-width integer types
+#define INTMAX_MIN INT64_MIN
+#define INTMAX_MAX INT64_MAX
+#define UINTMAX_MAX UINT64_MAX
+
+// 7.18.3 Limits of other integer types
+
+#ifdef _WIN64 // [
+# define PTRDIFF_MIN _I64_MIN
+# define PTRDIFF_MAX _I64_MAX
+#else // _WIN64 ][
+# define PTRDIFF_MIN _I32_MIN
+# define PTRDIFF_MAX _I32_MAX
+#endif // _WIN64 ]
+
+#define SIG_ATOMIC_MIN INT_MIN
+#define SIG_ATOMIC_MAX INT_MAX
+
+#ifndef SIZE_MAX // [
+# ifdef _WIN64 // [
+# define SIZE_MAX _UI64_MAX
+# else // _WIN64 ][
+# define SIZE_MAX _UI32_MAX
+# endif // _WIN64 ]
+#endif // SIZE_MAX ]
+
+// WCHAR_MIN and WCHAR_MAX are also defined in <wchar.h>
+#ifndef WCHAR_MIN // [
+# define WCHAR_MIN 0
+#endif // WCHAR_MIN ]
+#ifndef WCHAR_MAX // [
+# define WCHAR_MAX _UI16_MAX
+#endif // WCHAR_MAX ]
+
+#define WINT_MIN 0
+#define WINT_MAX _UI16_MAX
+
+#endif // __STDC_LIMIT_MACROS ]
+
+
+// 7.18.4 Limits of other integer types
+
+#if !defined(__cplusplus) || defined(__STDC_CONSTANT_MACROS) // [ See footnote 224 at page 260
+
+// 7.18.4.1 Macros for minimum-width integer constants
+
+#define INT8_C(val) val##i8
+#define INT16_C(val) val##i16
+#define INT32_C(val) val##i32
+#define INT64_C(val) val##i64
+
+#define UINT8_C(val) val##ui8
+#define UINT16_C(val) val##ui16
+#define UINT32_C(val) val##ui32
+#define UINT64_C(val) val##ui64
+
+// 7.18.4.2 Macros for greatest-width integer constants
+// These #ifndef's are needed to prevent collisions with <boost/cstdint.hpp>.
+// Check out Issue 9 for the details.
+#ifndef INTMAX_C // [
+# define INTMAX_C INT64_C
+#endif // INTMAX_C ]
+#ifndef UINTMAX_C // [
+# define UINTMAX_C UINT64_C
+#endif // UINTMAX_C ]
+
+#endif // __STDC_CONSTANT_MACROS ]
+
+#endif // _MSC_VER >= 1600 ]
+
+#endif // _MSC_STDINT_H_ ]
diff --git a/include/rapidjson/ostreamwrapper.h b/include/rapidjson/ostreamwrapper.h
new file mode 100644
index 00000000..6f4667c0
--- /dev/null
+++ b/include/rapidjson/ostreamwrapper.h
@@ -0,0 +1,81 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_OSTREAMWRAPPER_H_
+#define RAPIDJSON_OSTREAMWRAPPER_H_
+
+#include "stream.h"
+#include <iosfwd>
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Wrapper of \c std::basic_ostream into RapidJSON's Stream concept.
+/*!
+ The classes can be wrapped including but not limited to:
+
+ - \c std::ostringstream
+ - \c std::stringstream
+ - \c std::wpstringstream
+ - \c std::wstringstream
+ - \c std::ifstream
+ - \c std::fstream
+ - \c std::wofstream
+ - \c std::wfstream
+
+ \tparam StreamType Class derived from \c std::basic_ostream.
+*/
+
+template <typename StreamType>
+class BasicOStreamWrapper {
+public:
+ typedef typename StreamType::char_type Ch;
+ BasicOStreamWrapper(StreamType& stream) : stream_(stream) {}
+
+ void Put(Ch c) {
+ stream_.put(c);
+ }
+
+ void Flush() {
+ stream_.flush();
+ }
+
+ // Not implemented
+ char Peek() const { RAPIDJSON_ASSERT(false); return 0; }
+ char Take() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t Tell() const { RAPIDJSON_ASSERT(false); return 0; }
+ char* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ size_t PutEnd(char*) { RAPIDJSON_ASSERT(false); return 0; }
+
+private:
+ BasicOStreamWrapper(const BasicOStreamWrapper&);
+ BasicOStreamWrapper& operator=(const BasicOStreamWrapper&);
+
+ StreamType& stream_;
+};
+
+typedef BasicOStreamWrapper<std::ostream> OStreamWrapper;
+typedef BasicOStreamWrapper<std::wostream> WOStreamWrapper;
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_OSTREAMWRAPPER_H_
diff --git a/include/rapidjson/pointer.h b/include/rapidjson/pointer.h
new file mode 100644
index 00000000..0206ac1c
--- /dev/null
+++ b/include/rapidjson/pointer.h
@@ -0,0 +1,1358 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_POINTER_H_
+#define RAPIDJSON_POINTER_H_
+
+#include "document.h"
+#include "internal/itoa.h"
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(switch-enum)
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+static const SizeType kPointerInvalidIndex = ~SizeType(0); //!< Represents an invalid index in GenericPointer::Token
+
+//! Error code of parsing.
+/*! \ingroup RAPIDJSON_ERRORS
+ \see GenericPointer::GenericPointer, GenericPointer::GetParseErrorCode
+*/
+enum PointerParseErrorCode {
+ kPointerParseErrorNone = 0, //!< The parse is successful
+
+ kPointerParseErrorTokenMustBeginWithSolidus, //!< A token must begin with a '/'
+ kPointerParseErrorInvalidEscape, //!< Invalid escape
+ kPointerParseErrorInvalidPercentEncoding, //!< Invalid percent encoding in URI fragment
+ kPointerParseErrorCharacterMustPercentEncode //!< A character must percent encoded in URI fragment
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericPointer
+
+//! Represents a JSON Pointer. Use Pointer for UTF8 encoding and default allocator.
+/*!
+ This class implements RFC 6901 "JavaScript Object Notation (JSON) Pointer"
+ (https://tools.ietf.org/html/rfc6901).
+
+ A JSON pointer is for identifying a specific value in a JSON document
+ (GenericDocument). It can simplify coding of DOM tree manipulation, because it
+ can access multiple-level depth of DOM tree with single API call.
+
+ After it parses a string representation (e.g. "/foo/0" or URI fragment
+ representation (e.g. "#/foo/0") into its internal representation (tokens),
+ it can be used to resolve a specific value in multiple documents, or sub-tree
+ of documents.
+
+ Contrary to GenericValue, Pointer can be copy constructed and copy assigned.
+ Apart from assignment, a Pointer cannot be modified after construction.
+
+ Although Pointer is very convenient, please aware that constructing Pointer
+ involves parsing and dynamic memory allocation. A special constructor with user-
+ supplied tokens eliminates these.
+
+ GenericPointer depends on GenericDocument and GenericValue.
+
+ \tparam ValueType The value type of the DOM tree. E.g. GenericValue<UTF8<> >
+ \tparam Allocator The allocator type for allocating memory for internal representation.
+
+ \note GenericPointer uses same encoding of ValueType.
+ However, Allocator of GenericPointer is independent of Allocator of Value.
+*/
+template <typename ValueType, typename Allocator = CrtAllocator>
+class GenericPointer {
+public:
+ typedef typename ValueType::EncodingType EncodingType; //!< Encoding type from Value
+ typedef typename ValueType::Ch Ch; //!< Character type from Value
+
+ //! A token is the basic units of internal representation.
+ /*!
+ A JSON pointer string representation "/foo/123" is parsed to two tokens:
+ "foo" and 123. 123 will be represented in both numeric form and string form.
+ They are resolved according to the actual value type (object or array).
+
+ For token that are not numbers, or the numeric value is out of bound
+ (greater than limits of SizeType), they are only treated as string form
+ (i.e. the token's index will be equal to kPointerInvalidIndex).
+
+ This struct is public so that user can create a Pointer without parsing and
+ allocation, using a special constructor.
+ */
+ struct Token {
+ const Ch* name; //!< Name of the token. It has null character at the end but it can contain null character.
+ SizeType length; //!< Length of the name.
+ SizeType index; //!< A valid array index, if it is not equal to kPointerInvalidIndex.
+ };
+
+ //!@name Constructors and destructor.
+ //@{
+
+ //! Default constructor.
+ GenericPointer(Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {}
+
+ //! Constructor that parses a string or URI fragment representation.
+ /*!
+ \param source A null-terminated, string or URI fragment representation of JSON pointer.
+ \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one.
+ */
+ explicit GenericPointer(const Ch* source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
+ Parse(source, internal::StrLen(source));
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Constructor that parses a string or URI fragment representation.
+ /*!
+ \param source A string or URI fragment representation of JSON pointer.
+ \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one.
+ \note Requires the definition of the preprocessor symbol \ref RAPIDJSON_HAS_STDSTRING.
+ */
+ explicit GenericPointer(const std::basic_string<Ch>& source, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
+ Parse(source.c_str(), source.size());
+ }
+#endif
+
+ //! Constructor that parses a string or URI fragment representation, with length of the source string.
+ /*!
+ \param source A string or URI fragment representation of JSON pointer.
+ \param length Length of source.
+ \param allocator User supplied allocator for this pointer. If no allocator is provided, it creates a self-owned one.
+ \note Slightly faster than the overload without length.
+ */
+ GenericPointer(const Ch* source, size_t length, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
+ Parse(source, length);
+ }
+
+ //! Constructor with user-supplied tokens.
+ /*!
+ This constructor let user supplies const array of tokens.
+ This prevents the parsing process and eliminates allocation.
+ This is preferred for memory constrained environments.
+
+ \param tokens An constant array of tokens representing the JSON pointer.
+ \param tokenCount Number of tokens.
+
+ \b Example
+ \code
+ #define NAME(s) { s, sizeof(s) / sizeof(s[0]) - 1, kPointerInvalidIndex }
+ #define INDEX(i) { #i, sizeof(#i) - 1, i }
+
+ static const Pointer::Token kTokens[] = { NAME("foo"), INDEX(123) };
+ static const Pointer p(kTokens, sizeof(kTokens) / sizeof(kTokens[0]));
+ // Equivalent to static const Pointer p("/foo/123");
+
+ #undef NAME
+ #undef INDEX
+ \endcode
+ */
+ GenericPointer(const Token* tokens, size_t tokenCount) : allocator_(), ownAllocator_(), nameBuffer_(), tokens_(const_cast<Token*>(tokens)), tokenCount_(tokenCount), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {}
+
+ //! Copy constructor.
+ GenericPointer(const GenericPointer& rhs, Allocator* allocator = 0) : allocator_(allocator), ownAllocator_(), nameBuffer_(), tokens_(), tokenCount_(), parseErrorOffset_(), parseErrorCode_(kPointerParseErrorNone) {
+ *this = rhs;
+ }
+
+ //! Destructor.
+ ~GenericPointer() {
+ if (nameBuffer_) // If user-supplied tokens constructor is used, nameBuffer_ is nullptr and tokens_ are not deallocated.
+ Allocator::Free(tokens_);
+ RAPIDJSON_DELETE(ownAllocator_);
+ }
+
+ //! Assignment operator.
+ GenericPointer& operator=(const GenericPointer& rhs) {
+ if (this != &rhs) {
+ // Do not delete ownAllcator
+ if (nameBuffer_)
+ Allocator::Free(tokens_);
+
+ tokenCount_ = rhs.tokenCount_;
+ parseErrorOffset_ = rhs.parseErrorOffset_;
+ parseErrorCode_ = rhs.parseErrorCode_;
+
+ if (rhs.nameBuffer_)
+ CopyFromRaw(rhs); // Normally parsed tokens.
+ else {
+ tokens_ = rhs.tokens_; // User supplied const tokens.
+ nameBuffer_ = 0;
+ }
+ }
+ return *this;
+ }
+
+ //@}
+
+ //!@name Append token
+ //@{
+
+ //! Append a token and return a new Pointer
+ /*!
+ \param token Token to be appended.
+ \param allocator Allocator for the newly return Pointer.
+ \return A new Pointer with appended token.
+ */
+ GenericPointer Append(const Token& token, Allocator* allocator = 0) const {
+ GenericPointer r;
+ r.allocator_ = allocator;
+ Ch *p = r.CopyFromRaw(*this, 1, token.length + 1);
+ std::memcpy(p, token.name, (token.length + 1) * sizeof(Ch));
+ r.tokens_[tokenCount_].name = p;
+ r.tokens_[tokenCount_].length = token.length;
+ r.tokens_[tokenCount_].index = token.index;
+ return r;
+ }
+
+ //! Append a name token with length, and return a new Pointer
+ /*!
+ \param name Name to be appended.
+ \param length Length of name.
+ \param allocator Allocator for the newly return Pointer.
+ \return A new Pointer with appended token.
+ */
+ GenericPointer Append(const Ch* name, SizeType length, Allocator* allocator = 0) const {
+ Token token = { name, length, kPointerInvalidIndex };
+ return Append(token, allocator);
+ }
+
+ //! Append a name token without length, and return a new Pointer
+ /*!
+ \param name Name (const Ch*) to be appended.
+ \param allocator Allocator for the newly return Pointer.
+ \return A new Pointer with appended token.
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::NotExpr<internal::IsSame<typename internal::RemoveConst<T>::Type, Ch> >), (GenericPointer))
+ Append(T* name, Allocator* allocator = 0) const {
+ return Append(name, StrLen(name), allocator);
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Append a name token, and return a new Pointer
+ /*!
+ \param name Name to be appended.
+ \param allocator Allocator for the newly return Pointer.
+ \return A new Pointer with appended token.
+ */
+ GenericPointer Append(const std::basic_string<Ch>& name, Allocator* allocator = 0) const {
+ return Append(name.c_str(), static_cast<SizeType>(name.size()), allocator);
+ }
+#endif
+
+ //! Append a index token, and return a new Pointer
+ /*!
+ \param index Index to be appended.
+ \param allocator Allocator for the newly return Pointer.
+ \return A new Pointer with appended token.
+ */
+ GenericPointer Append(SizeType index, Allocator* allocator = 0) const {
+ char buffer[21];
+ char* end = sizeof(SizeType) == 4 ? internal::u32toa(index, buffer) : internal::u64toa(index, buffer);
+ SizeType length = static_cast<SizeType>(end - buffer);
+ buffer[length] = '\0';
+
+ if (sizeof(Ch) == 1) {
+ Token token = { reinterpret_cast<Ch*>(buffer), length, index };
+ return Append(token, allocator);
+ }
+ else {
+ Ch name[21];
+ for (size_t i = 0; i <= length; i++)
+ name[i] = buffer[i];
+ Token token = { name, length, index };
+ return Append(token, allocator);
+ }
+ }
+
+ //! Append a token by value, and return a new Pointer
+ /*!
+ \param token token to be appended.
+ \param allocator Allocator for the newly return Pointer.
+ \return A new Pointer with appended token.
+ */
+ GenericPointer Append(const ValueType& token, Allocator* allocator = 0) const {
+ if (token.IsString())
+ return Append(token.GetString(), token.GetStringLength(), allocator);
+ else {
+ RAPIDJSON_ASSERT(token.IsUint64());
+ RAPIDJSON_ASSERT(token.GetUint64() <= SizeType(~0));
+ return Append(static_cast<SizeType>(token.GetUint64()), allocator);
+ }
+ }
+
+ //!@name Handling Parse Error
+ //@{
+
+ //! Check whether this is a valid pointer.
+ bool IsValid() const { return parseErrorCode_ == kPointerParseErrorNone; }
+
+ //! Get the parsing error offset in code unit.
+ size_t GetParseErrorOffset() const { return parseErrorOffset_; }
+
+ //! Get the parsing error code.
+ PointerParseErrorCode GetParseErrorCode() const { return parseErrorCode_; }
+
+ //@}
+
+ //! Get the allocator of this pointer.
+ Allocator& GetAllocator() { return *allocator_; }
+
+ //!@name Tokens
+ //@{
+
+ //! Get the token array (const version only).
+ const Token* GetTokens() const { return tokens_; }
+
+ //! Get the number of tokens.
+ size_t GetTokenCount() const { return tokenCount_; }
+
+ //@}
+
+ //!@name Equality/inequality operators
+ //@{
+
+ //! Equality operator.
+ /*!
+ \note When any pointers are invalid, always returns false.
+ */
+ bool operator==(const GenericPointer& rhs) const {
+ if (!IsValid() || !rhs.IsValid() || tokenCount_ != rhs.tokenCount_)
+ return false;
+
+ for (size_t i = 0; i < tokenCount_; i++) {
+ if (tokens_[i].index != rhs.tokens_[i].index ||
+ tokens_[i].length != rhs.tokens_[i].length ||
+ (tokens_[i].length != 0 && std::memcmp(tokens_[i].name, rhs.tokens_[i].name, sizeof(Ch)* tokens_[i].length) != 0))
+ {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ //! Inequality operator.
+ /*!
+ \note When any pointers are invalid, always returns true.
+ */
+ bool operator!=(const GenericPointer& rhs) const { return !(*this == rhs); }
+
+ //@}
+
+ //!@name Stringify
+ //@{
+
+ //! Stringify the pointer into string representation.
+ /*!
+ \tparam OutputStream Type of output stream.
+ \param os The output stream.
+ */
+ template<typename OutputStream>
+ bool Stringify(OutputStream& os) const {
+ return Stringify<false, OutputStream>(os);
+ }
+
+ //! Stringify the pointer into URI fragment representation.
+ /*!
+ \tparam OutputStream Type of output stream.
+ \param os The output stream.
+ */
+ template<typename OutputStream>
+ bool StringifyUriFragment(OutputStream& os) const {
+ return Stringify<true, OutputStream>(os);
+ }
+
+ //@}
+
+ //!@name Create value
+ //@{
+
+ //! Create a value in a subtree.
+ /*!
+ If the value is not exist, it creates all parent values and a JSON Null value.
+ So it always succeed and return the newly created or existing value.
+
+ Remind that it may change types of parents according to tokens, so it
+ potentially removes previously stored values. For example, if a document
+ was an array, and "/foo" is used to create a value, then the document
+ will be changed to an object, and all existing array elements are lost.
+
+ \param root Root value of a DOM subtree to be resolved. It can be any value other than document root.
+ \param allocator Allocator for creating the values if the specified value or its parents are not exist.
+ \param alreadyExist If non-null, it stores whether the resolved value is already exist.
+ \return The resolved newly created (a JSON Null value), or already exists value.
+ */
+ ValueType& Create(ValueType& root, typename ValueType::AllocatorType& allocator, bool* alreadyExist = 0) const {
+ RAPIDJSON_ASSERT(IsValid());
+ ValueType* v = &root;
+ bool exist = true;
+ for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
+ if (v->IsArray() && t->name[0] == '-' && t->length == 1) {
+ v->PushBack(ValueType().Move(), allocator);
+ v = &((*v)[v->Size() - 1]);
+ exist = false;
+ }
+ else {
+ if (t->index == kPointerInvalidIndex) { // must be object name
+ if (!v->IsObject())
+ v->SetObject(); // Change to Object
+ }
+ else { // object name or array index
+ if (!v->IsArray() && !v->IsObject())
+ v->SetArray(); // Change to Array
+ }
+
+ if (v->IsArray()) {
+ if (t->index >= v->Size()) {
+ v->Reserve(t->index + 1, allocator);
+ while (t->index >= v->Size())
+ v->PushBack(ValueType().Move(), allocator);
+ exist = false;
+ }
+ v = &((*v)[t->index]);
+ }
+ else {
+ typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
+ if (m == v->MemberEnd()) {
+ v->AddMember(ValueType(t->name, t->length, allocator).Move(), ValueType().Move(), allocator);
+ v = &(--v->MemberEnd())->value; // Assumes AddMember() appends at the end
+ exist = false;
+ }
+ else
+ v = &m->value;
+ }
+ }
+ }
+
+ if (alreadyExist)
+ *alreadyExist = exist;
+
+ return *v;
+ }
+
+ //! Creates a value in a document.
+ /*!
+ \param document A document to be resolved.
+ \param alreadyExist If non-null, it stores whether the resolved value is already exist.
+ \return The resolved newly created, or already exists value.
+ */
+ template <typename stackAllocator>
+ ValueType& Create(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, bool* alreadyExist = 0) const {
+ return Create(document, document.GetAllocator(), alreadyExist);
+ }
+
+ //@}
+
+ //!@name Query value
+ //@{
+
+ //! Query a value in a subtree.
+ /*!
+ \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
+ \param unresolvedTokenIndex If the pointer cannot resolve a token in the pointer, this parameter can obtain the index of unresolved token.
+ \return Pointer to the value if it can be resolved. Otherwise null.
+
+ \note
+ There are only 3 situations when a value cannot be resolved:
+ 1. A value in the path is not an array nor object.
+ 2. An object value does not contain the token.
+ 3. A token is out of range of an array value.
+
+ Use unresolvedTokenIndex to retrieve the token index.
+ */
+ ValueType* Get(ValueType& root, size_t* unresolvedTokenIndex = 0) const {
+ RAPIDJSON_ASSERT(IsValid());
+ ValueType* v = &root;
+ for (const Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
+ switch (v->GetType()) {
+ case kObjectType:
+ {
+ typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
+ if (m == v->MemberEnd())
+ break;
+ v = &m->value;
+ }
+ continue;
+ case kArrayType:
+ if (t->index == kPointerInvalidIndex || t->index >= v->Size())
+ break;
+ v = &((*v)[t->index]);
+ continue;
+ default:
+ break;
+ }
+
+ // Error: unresolved token
+ if (unresolvedTokenIndex)
+ *unresolvedTokenIndex = static_cast<size_t>(t - tokens_);
+ return 0;
+ }
+ return v;
+ }
+
+ //! Query a const value in a const subtree.
+ /*!
+ \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
+ \return Pointer to the value if it can be resolved. Otherwise null.
+ */
+ const ValueType* Get(const ValueType& root, size_t* unresolvedTokenIndex = 0) const {
+ return Get(const_cast<ValueType&>(root), unresolvedTokenIndex);
+ }
+
+ //@}
+
+ //!@name Query a value with default
+ //@{
+
+ //! Query a value in a subtree with default value.
+ /*!
+ Similar to Get(), but if the specified value do not exists, it creates all parents and clone the default value.
+ So that this function always succeed.
+
+ \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
+ \param defaultValue Default value to be cloned if the value was not exists.
+ \param allocator Allocator for creating the values if the specified value or its parents are not exist.
+ \see Create()
+ */
+ ValueType& GetWithDefault(ValueType& root, const ValueType& defaultValue, typename ValueType::AllocatorType& allocator) const {
+ bool alreadyExist;
+ Value& v = Create(root, allocator, &alreadyExist);
+ return alreadyExist ? v : v.CopyFrom(defaultValue, allocator);
+ }
+
+ //! Query a value in a subtree with default null-terminated string.
+ ValueType& GetWithDefault(ValueType& root, const Ch* defaultValue, typename ValueType::AllocatorType& allocator) const {
+ bool alreadyExist;
+ Value& v = Create(root, allocator, &alreadyExist);
+ return alreadyExist ? v : v.SetString(defaultValue, allocator);
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Query a value in a subtree with default std::basic_string.
+ ValueType& GetWithDefault(ValueType& root, const std::basic_string<Ch>& defaultValue, typename ValueType::AllocatorType& allocator) const {
+ bool alreadyExist;
+ Value& v = Create(root, allocator, &alreadyExist);
+ return alreadyExist ? v : v.SetString(defaultValue, allocator);
+ }
+#endif
+
+ //! Query a value in a subtree with default primitive value.
+ /*!
+ \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
+ GetWithDefault(ValueType& root, T defaultValue, typename ValueType::AllocatorType& allocator) const {
+ return GetWithDefault(root, ValueType(defaultValue).Move(), allocator);
+ }
+
+ //! Query a value in a document with default value.
+ template <typename stackAllocator>
+ ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& defaultValue) const {
+ return GetWithDefault(document, defaultValue, document.GetAllocator());
+ }
+
+ //! Query a value in a document with default null-terminated string.
+ template <typename stackAllocator>
+ ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* defaultValue) const {
+ return GetWithDefault(document, defaultValue, document.GetAllocator());
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Query a value in a document with default std::basic_string.
+ template <typename stackAllocator>
+ ValueType& GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& defaultValue) const {
+ return GetWithDefault(document, defaultValue, document.GetAllocator());
+ }
+#endif
+
+ //! Query a value in a document with default primitive value.
+ /*!
+ \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
+ */
+ template <typename T, typename stackAllocator>
+ RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
+ GetWithDefault(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T defaultValue) const {
+ return GetWithDefault(document, defaultValue, document.GetAllocator());
+ }
+
+ //@}
+
+ //!@name Set a value
+ //@{
+
+ //! Set a value in a subtree, with move semantics.
+ /*!
+ It creates all parents if they are not exist or types are different to the tokens.
+ So this function always succeeds but potentially remove existing values.
+
+ \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
+ \param value Value to be set.
+ \param allocator Allocator for creating the values if the specified value or its parents are not exist.
+ \see Create()
+ */
+ ValueType& Set(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const {
+ return Create(root, allocator) = value;
+ }
+
+ //! Set a value in a subtree, with copy semantics.
+ ValueType& Set(ValueType& root, const ValueType& value, typename ValueType::AllocatorType& allocator) const {
+ return Create(root, allocator).CopyFrom(value, allocator);
+ }
+
+ //! Set a null-terminated string in a subtree.
+ ValueType& Set(ValueType& root, const Ch* value, typename ValueType::AllocatorType& allocator) const {
+ return Create(root, allocator) = ValueType(value, allocator).Move();
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Set a std::basic_string in a subtree.
+ ValueType& Set(ValueType& root, const std::basic_string<Ch>& value, typename ValueType::AllocatorType& allocator) const {
+ return Create(root, allocator) = ValueType(value, allocator).Move();
+ }
+#endif
+
+ //! Set a primitive value in a subtree.
+ /*!
+ \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
+ */
+ template <typename T>
+ RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
+ Set(ValueType& root, T value, typename ValueType::AllocatorType& allocator) const {
+ return Create(root, allocator) = ValueType(value).Move();
+ }
+
+ //! Set a value in a document, with move semantics.
+ template <typename stackAllocator>
+ ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const {
+ return Create(document) = value;
+ }
+
+ //! Set a value in a document, with copy semantics.
+ template <typename stackAllocator>
+ ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const ValueType& value) const {
+ return Create(document).CopyFrom(value, document.GetAllocator());
+ }
+
+ //! Set a null-terminated string in a document.
+ template <typename stackAllocator>
+ ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const Ch* value) const {
+ return Create(document) = ValueType(value, document.GetAllocator()).Move();
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ //! Sets a std::basic_string in a document.
+ template <typename stackAllocator>
+ ValueType& Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, const std::basic_string<Ch>& value) const {
+ return Create(document) = ValueType(value, document.GetAllocator()).Move();
+ }
+#endif
+
+ //! Set a primitive value in a document.
+ /*!
+ \tparam T Either \ref Type, \c int, \c unsigned, \c int64_t, \c uint64_t, \c bool
+ */
+ template <typename T, typename stackAllocator>
+ RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T>, internal::IsGenericValue<T> >), (ValueType&))
+ Set(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, T value) const {
+ return Create(document) = value;
+ }
+
+ //@}
+
+ //!@name Swap a value
+ //@{
+
+ //! Swap a value with a value in a subtree.
+ /*!
+ It creates all parents if they are not exist or types are different to the tokens.
+ So this function always succeeds but potentially remove existing values.
+
+ \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
+ \param value Value to be swapped.
+ \param allocator Allocator for creating the values if the specified value or its parents are not exist.
+ \see Create()
+ */
+ ValueType& Swap(ValueType& root, ValueType& value, typename ValueType::AllocatorType& allocator) const {
+ return Create(root, allocator).Swap(value);
+ }
+
+ //! Swap a value with a value in a document.
+ template <typename stackAllocator>
+ ValueType& Swap(GenericDocument<EncodingType, typename ValueType::AllocatorType, stackAllocator>& document, ValueType& value) const {
+ return Create(document).Swap(value);
+ }
+
+ //@}
+
+ //! Erase a value in a subtree.
+ /*!
+ \param root Root value of a DOM sub-tree to be resolved. It can be any value other than document root.
+ \return Whether the resolved value is found and erased.
+
+ \note Erasing with an empty pointer \c Pointer(""), i.e. the root, always fail and return false.
+ */
+ bool Erase(ValueType& root) const {
+ RAPIDJSON_ASSERT(IsValid());
+ if (tokenCount_ == 0) // Cannot erase the root
+ return false;
+
+ ValueType* v = &root;
+ const Token* last = tokens_ + (tokenCount_ - 1);
+ for (const Token *t = tokens_; t != last; ++t) {
+ switch (v->GetType()) {
+ case kObjectType:
+ {
+ typename ValueType::MemberIterator m = v->FindMember(GenericStringRef<Ch>(t->name, t->length));
+ if (m == v->MemberEnd())
+ return false;
+ v = &m->value;
+ }
+ break;
+ case kArrayType:
+ if (t->index == kPointerInvalidIndex || t->index >= v->Size())
+ return false;
+ v = &((*v)[t->index]);
+ break;
+ default:
+ return false;
+ }
+ }
+
+ switch (v->GetType()) {
+ case kObjectType:
+ return v->EraseMember(GenericStringRef<Ch>(last->name, last->length));
+ case kArrayType:
+ if (last->index == kPointerInvalidIndex || last->index >= v->Size())
+ return false;
+ v->Erase(v->Begin() + last->index);
+ return true;
+ default:
+ return false;
+ }
+ }
+
+private:
+ //! Clone the content from rhs to this.
+ /*!
+ \param rhs Source pointer.
+ \param extraToken Extra tokens to be allocated.
+ \param extraNameBufferSize Extra name buffer size (in number of Ch) to be allocated.
+ \return Start of non-occupied name buffer, for storing extra names.
+ */
+ Ch* CopyFromRaw(const GenericPointer& rhs, size_t extraToken = 0, size_t extraNameBufferSize = 0) {
+ if (!allocator_) // allocator is independently owned.
+ ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
+
+ size_t nameBufferSize = rhs.tokenCount_; // null terminators for tokens
+ for (Token *t = rhs.tokens_; t != rhs.tokens_ + rhs.tokenCount_; ++t)
+ nameBufferSize += t->length;
+
+ tokenCount_ = rhs.tokenCount_ + extraToken;
+ tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + (nameBufferSize + extraNameBufferSize) * sizeof(Ch)));
+ nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_);
+ if (rhs.tokenCount_ > 0) {
+ std::memcpy(tokens_, rhs.tokens_, rhs.tokenCount_ * sizeof(Token));
+ }
+ if (nameBufferSize > 0) {
+ std::memcpy(nameBuffer_, rhs.nameBuffer_, nameBufferSize * sizeof(Ch));
+ }
+
+ // Adjust pointers to name buffer
+ std::ptrdiff_t diff = nameBuffer_ - rhs.nameBuffer_;
+ for (Token *t = tokens_; t != tokens_ + rhs.tokenCount_; ++t)
+ t->name += diff;
+
+ return nameBuffer_ + nameBufferSize;
+ }
+
+ //! Check whether a character should be percent-encoded.
+ /*!
+ According to RFC 3986 2.3 Unreserved Characters.
+ \param c The character (code unit) to be tested.
+ */
+ bool NeedPercentEncode(Ch c) const {
+ return !((c >= '0' && c <= '9') || (c >= 'A' && c <='Z') || (c >= 'a' && c <= 'z') || c == '-' || c == '.' || c == '_' || c =='~');
+ }
+
+ //! Parse a JSON String or its URI fragment representation into tokens.
+#ifndef __clang__ // -Wdocumentation
+ /*!
+ \param source Either a JSON Pointer string, or its URI fragment representation. Not need to be null terminated.
+ \param length Length of the source string.
+ \note Source cannot be JSON String Representation of JSON Pointer, e.g. In "/\u0000", \u0000 will not be unescaped.
+ */
+#endif
+ void Parse(const Ch* source, size_t length) {
+ RAPIDJSON_ASSERT(source != NULL);
+ RAPIDJSON_ASSERT(nameBuffer_ == 0);
+ RAPIDJSON_ASSERT(tokens_ == 0);
+
+ // Create own allocator if user did not supply.
+ if (!allocator_)
+ ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
+
+ // Count number of '/' as tokenCount
+ tokenCount_ = 0;
+ for (const Ch* s = source; s != source + length; s++)
+ if (*s == '/')
+ tokenCount_++;
+
+ Token* token = tokens_ = static_cast<Token *>(allocator_->Malloc(tokenCount_ * sizeof(Token) + length * sizeof(Ch)));
+ Ch* name = nameBuffer_ = reinterpret_cast<Ch *>(tokens_ + tokenCount_);
+ size_t i = 0;
+
+ // Detect if it is a URI fragment
+ bool uriFragment = false;
+ if (source[i] == '#') {
+ uriFragment = true;
+ i++;
+ }
+
+ if (i != length && source[i] != '/') {
+ parseErrorCode_ = kPointerParseErrorTokenMustBeginWithSolidus;
+ goto error;
+ }
+
+ while (i < length) {
+ RAPIDJSON_ASSERT(source[i] == '/');
+ i++; // consumes '/'
+
+ token->name = name;
+ bool isNumber = true;
+
+ while (i < length && source[i] != '/') {
+ Ch c = source[i];
+ if (uriFragment) {
+ // Decoding percent-encoding for URI fragment
+ if (c == '%') {
+ PercentDecodeStream is(&source[i], source + length);
+ GenericInsituStringStream<EncodingType> os(name);
+ Ch* begin = os.PutBegin();
+ if (!Transcoder<UTF8<>, EncodingType>().Validate(is, os) || !is.IsValid()) {
+ parseErrorCode_ = kPointerParseErrorInvalidPercentEncoding;
+ goto error;
+ }
+ size_t len = os.PutEnd(begin);
+ i += is.Tell() - 1;
+ if (len == 1)
+ c = *name;
+ else {
+ name += len;
+ isNumber = false;
+ i++;
+ continue;
+ }
+ }
+ else if (NeedPercentEncode(c)) {
+ parseErrorCode_ = kPointerParseErrorCharacterMustPercentEncode;
+ goto error;
+ }
+ }
+
+ i++;
+
+ // Escaping "~0" -> '~', "~1" -> '/'
+ if (c == '~') {
+ if (i < length) {
+ c = source[i];
+ if (c == '0') c = '~';
+ else if (c == '1') c = '/';
+ else {
+ parseErrorCode_ = kPointerParseErrorInvalidEscape;
+ goto error;
+ }
+ i++;
+ }
+ else {
+ parseErrorCode_ = kPointerParseErrorInvalidEscape;
+ goto error;
+ }
+ }
+
+ // First check for index: all of characters are digit
+ if (c < '0' || c > '9')
+ isNumber = false;
+
+ *name++ = c;
+ }
+ token->length = static_cast<SizeType>(name - token->name);
+ if (token->length == 0)
+ isNumber = false;
+ *name++ = '\0'; // Null terminator
+
+ // Second check for index: more than one digit cannot have leading zero
+ if (isNumber && token->length > 1 && token->name[0] == '0')
+ isNumber = false;
+
+ // String to SizeType conversion
+ SizeType n = 0;
+ if (isNumber) {
+ for (size_t j = 0; j < token->length; j++) {
+ SizeType m = n * 10 + static_cast<SizeType>(token->name[j] - '0');
+ if (m < n) { // overflow detection
+ isNumber = false;
+ break;
+ }
+ n = m;
+ }
+ }
+
+ token->index = isNumber ? n : kPointerInvalidIndex;
+ token++;
+ }
+
+ RAPIDJSON_ASSERT(name <= nameBuffer_ + length); // Should not overflow buffer
+ parseErrorCode_ = kPointerParseErrorNone;
+ return;
+
+ error:
+ Allocator::Free(tokens_);
+ nameBuffer_ = 0;
+ tokens_ = 0;
+ tokenCount_ = 0;
+ parseErrorOffset_ = i;
+ return;
+ }
+
+ //! Stringify to string or URI fragment representation.
+ /*!
+ \tparam uriFragment True for stringifying to URI fragment representation. False for string representation.
+ \tparam OutputStream type of output stream.
+ \param os The output stream.
+ */
+ template<bool uriFragment, typename OutputStream>
+ bool Stringify(OutputStream& os) const {
+ RAPIDJSON_ASSERT(IsValid());
+
+ if (uriFragment)
+ os.Put('#');
+
+ for (Token *t = tokens_; t != tokens_ + tokenCount_; ++t) {
+ os.Put('/');
+ for (size_t j = 0; j < t->length; j++) {
+ Ch c = t->name[j];
+ if (c == '~') {
+ os.Put('~');
+ os.Put('0');
+ }
+ else if (c == '/') {
+ os.Put('~');
+ os.Put('1');
+ }
+ else if (uriFragment && NeedPercentEncode(c)) {
+ // Transcode to UTF8 sequence
+ GenericStringStream<typename ValueType::EncodingType> source(&t->name[j]);
+ PercentEncodeStream<OutputStream> target(os);
+ if (!Transcoder<EncodingType, UTF8<> >().Validate(source, target))
+ return false;
+ j += source.Tell() - 1;
+ }
+ else
+ os.Put(c);
+ }
+ }
+ return true;
+ }
+
+ //! A helper stream for decoding a percent-encoded sequence into code unit.
+ /*!
+ This stream decodes %XY triplet into code unit (0-255).
+ If it encounters invalid characters, it sets output code unit as 0 and
+ mark invalid, and to be checked by IsValid().
+ */
+ class PercentDecodeStream {
+ public:
+ typedef typename ValueType::Ch Ch;
+
+ //! Constructor
+ /*!
+ \param source Start of the stream
+ \param end Past-the-end of the stream.
+ */
+ PercentDecodeStream(const Ch* source, const Ch* end) : src_(source), head_(source), end_(end), valid_(true) {}
+
+ Ch Take() {
+ if (*src_ != '%' || src_ + 3 > end_) { // %XY triplet
+ valid_ = false;
+ return 0;
+ }
+ src_++;
+ Ch c = 0;
+ for (int j = 0; j < 2; j++) {
+ c = static_cast<Ch>(c << 4);
+ Ch h = *src_;
+ if (h >= '0' && h <= '9') c = static_cast<Ch>(c + h - '0');
+ else if (h >= 'A' && h <= 'F') c = static_cast<Ch>(c + h - 'A' + 10);
+ else if (h >= 'a' && h <= 'f') c = static_cast<Ch>(c + h - 'a' + 10);
+ else {
+ valid_ = false;
+ return 0;
+ }
+ src_++;
+ }
+ return c;
+ }
+
+ size_t Tell() const { return static_cast<size_t>(src_ - head_); }
+ bool IsValid() const { return valid_; }
+
+ private:
+ const Ch* src_; //!< Current read position.
+ const Ch* head_; //!< Original head of the string.
+ const Ch* end_; //!< Past-the-end position.
+ bool valid_; //!< Whether the parsing is valid.
+ };
+
+ //! A helper stream to encode character (UTF-8 code unit) into percent-encoded sequence.
+ template <typename OutputStream>
+ class PercentEncodeStream {
+ public:
+ PercentEncodeStream(OutputStream& os) : os_(os) {}
+ void Put(char c) { // UTF-8 must be byte
+ unsigned char u = static_cast<unsigned char>(c);
+ static const char hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+ os_.Put('%');
+ os_.Put(hexDigits[u >> 4]);
+ os_.Put(hexDigits[u & 15]);
+ }
+ private:
+ OutputStream& os_;
+ };
+
+ Allocator* allocator_; //!< The current allocator. It is either user-supplied or equal to ownAllocator_.
+ Allocator* ownAllocator_; //!< Allocator owned by this Pointer.
+ Ch* nameBuffer_; //!< A buffer containing all names in tokens.
+ Token* tokens_; //!< A list of tokens.
+ size_t tokenCount_; //!< Number of tokens in tokens_.
+ size_t parseErrorOffset_; //!< Offset in code unit when parsing fail.
+ PointerParseErrorCode parseErrorCode_; //!< Parsing error code.
+};
+
+//! GenericPointer for Value (UTF-8, default allocator).
+typedef GenericPointer<Value> Pointer;
+
+//!@name Helper functions for GenericPointer
+//@{
+
+//////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+typename T::ValueType& CreateValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::AllocatorType& a) {
+ return pointer.Create(root, a);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& CreateValueByPointer(T& root, const CharType(&source)[N], typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Create(root, a);
+}
+
+// No allocator parameter
+
+template <typename DocumentType>
+typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer) {
+ return pointer.Create(document);
+}
+
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& CreateValueByPointer(DocumentType& document, const CharType(&source)[N]) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Create(document);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+typename T::ValueType* GetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) {
+ return pointer.Get(root, unresolvedTokenIndex);
+}
+
+template <typename T>
+const typename T::ValueType* GetValueByPointer(const T& root, const GenericPointer<typename T::ValueType>& pointer, size_t* unresolvedTokenIndex = 0) {
+ return pointer.Get(root, unresolvedTokenIndex);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType* GetValueByPointer(T& root, const CharType (&source)[N], size_t* unresolvedTokenIndex = 0) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex);
+}
+
+template <typename T, typename CharType, size_t N>
+const typename T::ValueType* GetValueByPointer(const T& root, const CharType(&source)[N], size_t* unresolvedTokenIndex = 0) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Get(root, unresolvedTokenIndex);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& defaultValue, typename T::AllocatorType& a) {
+ return pointer.GetWithDefault(root, defaultValue, a);
+}
+
+template <typename T>
+typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* defaultValue, typename T::AllocatorType& a) {
+ return pointer.GetWithDefault(root, defaultValue, a);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename T>
+typename T::ValueType& GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) {
+ return pointer.GetWithDefault(root, defaultValue, a);
+}
+#endif
+
+template <typename T, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
+GetValueByPointerWithDefault(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 defaultValue, typename T::AllocatorType& a) {
+ return pointer.GetWithDefault(root, defaultValue, a);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::ValueType& defaultValue, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const typename T::Ch* defaultValue, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& GetValueByPointerWithDefault(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& defaultValue, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
+}
+#endif
+
+template <typename T, typename CharType, size_t N, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
+GetValueByPointerWithDefault(T& root, const CharType(&source)[N], T2 defaultValue, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).GetWithDefault(root, defaultValue, a);
+}
+
+// No allocator parameter
+
+template <typename DocumentType>
+typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& defaultValue) {
+ return pointer.GetWithDefault(document, defaultValue);
+}
+
+template <typename DocumentType>
+typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* defaultValue) {
+ return pointer.GetWithDefault(document, defaultValue);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename DocumentType>
+typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& defaultValue) {
+ return pointer.GetWithDefault(document, defaultValue);
+}
+#endif
+
+template <typename DocumentType, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
+GetValueByPointerWithDefault(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 defaultValue) {
+ return pointer.GetWithDefault(document, defaultValue);
+}
+
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& defaultValue) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
+}
+
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* defaultValue) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& defaultValue) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
+}
+#endif
+
+template <typename DocumentType, typename CharType, size_t N, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
+GetValueByPointerWithDefault(DocumentType& document, const CharType(&source)[N], T2 defaultValue) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).GetWithDefault(document, defaultValue);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) {
+ return pointer.Set(root, value, a);
+}
+
+template <typename T>
+typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::ValueType& value, typename T::AllocatorType& a) {
+ return pointer.Set(root, value, a);
+}
+
+template <typename T>
+typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const typename T::Ch* value, typename T::AllocatorType& a) {
+ return pointer.Set(root, value, a);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename T>
+typename T::ValueType& SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) {
+ return pointer.Set(root, value, a);
+}
+#endif
+
+template <typename T, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
+SetValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, T2 value, typename T::AllocatorType& a) {
+ return pointer.Set(root, value, a);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::ValueType& value, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const typename T::Ch* value, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& SetValueByPointer(T& root, const CharType(&source)[N], const std::basic_string<typename T::Ch>& value, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
+}
+#endif
+
+template <typename T, typename CharType, size_t N, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename T::ValueType&))
+SetValueByPointer(T& root, const CharType(&source)[N], T2 value, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Set(root, value, a);
+}
+
+// No allocator parameter
+
+template <typename DocumentType>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) {
+ return pointer.Set(document, value);
+}
+
+template <typename DocumentType>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::ValueType& value) {
+ return pointer.Set(document, value);
+}
+
+template <typename DocumentType>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const typename DocumentType::Ch* value) {
+ return pointer.Set(document, value);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename DocumentType>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, const std::basic_string<typename DocumentType::Ch>& value) {
+ return pointer.Set(document, value);
+}
+#endif
+
+template <typename DocumentType, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
+SetValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, T2 value) {
+ return pointer.Set(document, value);
+}
+
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
+}
+
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::ValueType& value) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
+}
+
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const typename DocumentType::Ch* value) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
+}
+
+#if RAPIDJSON_HAS_STDSTRING
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& SetValueByPointer(DocumentType& document, const CharType(&source)[N], const std::basic_string<typename DocumentType::Ch>& value) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
+}
+#endif
+
+template <typename DocumentType, typename CharType, size_t N, typename T2>
+RAPIDJSON_DISABLEIF_RETURN((internal::OrExpr<internal::IsPointer<T2>, internal::IsGenericValue<T2> >), (typename DocumentType::ValueType&))
+SetValueByPointer(DocumentType& document, const CharType(&source)[N], T2 value) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Set(document, value);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+typename T::ValueType& SwapValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer, typename T::ValueType& value, typename T::AllocatorType& a) {
+ return pointer.Swap(root, value, a);
+}
+
+template <typename T, typename CharType, size_t N>
+typename T::ValueType& SwapValueByPointer(T& root, const CharType(&source)[N], typename T::ValueType& value, typename T::AllocatorType& a) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Swap(root, value, a);
+}
+
+template <typename DocumentType>
+typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const GenericPointer<typename DocumentType::ValueType>& pointer, typename DocumentType::ValueType& value) {
+ return pointer.Swap(document, value);
+}
+
+template <typename DocumentType, typename CharType, size_t N>
+typename DocumentType::ValueType& SwapValueByPointer(DocumentType& document, const CharType(&source)[N], typename DocumentType::ValueType& value) {
+ return GenericPointer<typename DocumentType::ValueType>(source, N - 1).Swap(document, value);
+}
+
+//////////////////////////////////////////////////////////////////////////////
+
+template <typename T>
+bool EraseValueByPointer(T& root, const GenericPointer<typename T::ValueType>& pointer) {
+ return pointer.Erase(root);
+}
+
+template <typename T, typename CharType, size_t N>
+bool EraseValueByPointer(T& root, const CharType(&source)[N]) {
+ return GenericPointer<typename T::ValueType>(source, N - 1).Erase(root);
+}
+
+//@}
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_POINTER_H_
diff --git a/include/rapidjson/prettywriter.h b/include/rapidjson/prettywriter.h
new file mode 100644
index 00000000..0dcb0fee
--- /dev/null
+++ b/include/rapidjson/prettywriter.h
@@ -0,0 +1,255 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_PRETTYWRITER_H_
+#define RAPIDJSON_PRETTYWRITER_H_
+
+#include "writer.h"
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Combination of PrettyWriter format flags.
+/*! \see PrettyWriter::SetFormatOptions
+ */
+enum PrettyFormatOptions {
+ kFormatDefault = 0, //!< Default pretty formatting.
+ kFormatSingleLineArray = 1 //!< Format arrays on a single line.
+};
+
+//! Writer with indentation and spacing.
+/*!
+ \tparam OutputStream Type of ouptut os.
+ \tparam SourceEncoding Encoding of source string.
+ \tparam TargetEncoding Encoding of output stream.
+ \tparam StackAllocator Type of allocator for allocating memory of stack.
+*/
+template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
+class PrettyWriter : public Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator, writeFlags> {
+public:
+ typedef Writer<OutputStream, SourceEncoding, TargetEncoding, StackAllocator> Base;
+ typedef typename Base::Ch Ch;
+
+ //! Constructor
+ /*! \param os Output stream.
+ \param allocator User supplied allocator. If it is null, it will create a private one.
+ \param levelDepth Initial capacity of stack.
+ */
+ explicit PrettyWriter(OutputStream& os, StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
+ Base(os, allocator, levelDepth), indentChar_(' '), indentCharCount_(4), formatOptions_(kFormatDefault) {}
+
+
+ explicit PrettyWriter(StackAllocator* allocator = 0, size_t levelDepth = Base::kDefaultLevelDepth) :
+ Base(allocator, levelDepth), indentChar_(' '), indentCharCount_(4) {}
+
+ //! Set custom indentation.
+ /*! \param indentChar Character for indentation. Must be whitespace character (' ', '\\t', '\\n', '\\r').
+ \param indentCharCount Number of indent characters for each indentation level.
+ \note The default indentation is 4 spaces.
+ */
+ PrettyWriter& SetIndent(Ch indentChar, unsigned indentCharCount) {
+ RAPIDJSON_ASSERT(indentChar == ' ' || indentChar == '\t' || indentChar == '\n' || indentChar == '\r');
+ indentChar_ = indentChar;
+ indentCharCount_ = indentCharCount;
+ return *this;
+ }
+
+ //! Set pretty writer formatting options.
+ /*! \param options Formatting options.
+ */
+ PrettyWriter& SetFormatOptions(PrettyFormatOptions options) {
+ formatOptions_ = options;
+ return *this;
+ }
+
+ /*! @name Implementation of Handler
+ \see Handler
+ */
+ //@{
+
+ bool Null() { PrettyPrefix(kNullType); return Base::WriteNull(); }
+ bool Bool(bool b) { PrettyPrefix(b ? kTrueType : kFalseType); return Base::WriteBool(b); }
+ bool Int(int i) { PrettyPrefix(kNumberType); return Base::WriteInt(i); }
+ bool Uint(unsigned u) { PrettyPrefix(kNumberType); return Base::WriteUint(u); }
+ bool Int64(int64_t i64) { PrettyPrefix(kNumberType); return Base::WriteInt64(i64); }
+ bool Uint64(uint64_t u64) { PrettyPrefix(kNumberType); return Base::WriteUint64(u64); }
+ bool Double(double d) { PrettyPrefix(kNumberType); return Base::WriteDouble(d); }
+
+ bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
+ (void)copy;
+ PrettyPrefix(kNumberType);
+ return Base::WriteString(str, length);
+ }
+
+ bool String(const Ch* str, SizeType length, bool copy = false) {
+ (void)copy;
+ PrettyPrefix(kStringType);
+ return Base::WriteString(str, length);
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ bool String(const std::basic_string<Ch>& str) {
+ return String(str.data(), SizeType(str.size()));
+ }
+#endif
+
+ bool StartObject() {
+ PrettyPrefix(kObjectType);
+ new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(false);
+ return Base::WriteStartObject();
+ }
+
+ bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
+
+#if RAPIDJSON_HAS_STDSTRING
+ bool Key(const std::basic_string<Ch>& str) {
+ return Key(str.data(), SizeType(str.size()));
+ }
+#endif
+
+ bool EndObject(SizeType memberCount = 0) {
+ (void)memberCount;
+ RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
+ RAPIDJSON_ASSERT(!Base::level_stack_.template Top<typename Base::Level>()->inArray);
+ bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
+
+ if (!empty) {
+ Base::os_->Put('\n');
+ WriteIndent();
+ }
+ bool ret = Base::WriteEndObject();
+ (void)ret;
+ RAPIDJSON_ASSERT(ret == true);
+ if (Base::level_stack_.Empty()) // end of json text
+ Base::os_->Flush();
+ return true;
+ }
+
+ bool StartArray() {
+ PrettyPrefix(kArrayType);
+ new (Base::level_stack_.template Push<typename Base::Level>()) typename Base::Level(true);
+ return Base::WriteStartArray();
+ }
+
+ bool EndArray(SizeType memberCount = 0) {
+ (void)memberCount;
+ RAPIDJSON_ASSERT(Base::level_stack_.GetSize() >= sizeof(typename Base::Level));
+ RAPIDJSON_ASSERT(Base::level_stack_.template Top<typename Base::Level>()->inArray);
+ bool empty = Base::level_stack_.template Pop<typename Base::Level>(1)->valueCount == 0;
+
+ if (!empty && !(formatOptions_ & kFormatSingleLineArray)) {
+ Base::os_->Put('\n');
+ WriteIndent();
+ }
+ bool ret = Base::WriteEndArray();
+ (void)ret;
+ RAPIDJSON_ASSERT(ret == true);
+ if (Base::level_stack_.Empty()) // end of json text
+ Base::os_->Flush();
+ return true;
+ }
+
+ //@}
+
+ /*! @name Convenience extensions */
+ //@{
+
+ //! Simpler but slower overload.
+ bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
+ bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
+
+ //@}
+
+ //! Write a raw JSON value.
+ /*!
+ For user to write a stringified JSON as a value.
+
+ \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range.
+ \param length Length of the json.
+ \param type Type of the root of json.
+ \note When using PrettyWriter::RawValue(), the result json may not be indented correctly.
+ */
+ bool RawValue(const Ch* json, size_t length, Type type) { PrettyPrefix(type); return Base::WriteRawValue(json, length); }
+
+protected:
+ void PrettyPrefix(Type type) {
+ (void)type;
+ if (Base::level_stack_.GetSize() != 0) { // this value is not at root
+ typename Base::Level* level = Base::level_stack_.template Top<typename Base::Level>();
+
+ if (level->inArray) {
+ if (level->valueCount > 0) {
+ Base::os_->Put(','); // add comma if it is not the first element in array
+ if (formatOptions_ & kFormatSingleLineArray)
+ Base::os_->Put(' ');
+ }
+
+ if (!(formatOptions_ & kFormatSingleLineArray)) {
+ Base::os_->Put('\n');
+ WriteIndent();
+ }
+ }
+ else { // in object
+ if (level->valueCount > 0) {
+ if (level->valueCount % 2 == 0) {
+ Base::os_->Put(',');
+ Base::os_->Put('\n');
+ }
+ else {
+ Base::os_->Put(':');
+ Base::os_->Put(' ');
+ }
+ }
+ else
+ Base::os_->Put('\n');
+
+ if (level->valueCount % 2 == 0)
+ WriteIndent();
+ }
+ if (!level->inArray && level->valueCount % 2 == 0)
+ RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
+ level->valueCount++;
+ }
+ else {
+ RAPIDJSON_ASSERT(!Base::hasRoot_); // Should only has one and only one root.
+ Base::hasRoot_ = true;
+ }
+ }
+
+ void WriteIndent() {
+ size_t count = (Base::level_stack_.GetSize() / sizeof(typename Base::Level)) * indentCharCount_;
+ PutN(*Base::os_, static_cast<typename TargetEncoding::Ch>(indentChar_), count);
+ }
+
+ Ch indentChar_;
+ unsigned indentCharCount_;
+ PrettyFormatOptions formatOptions_;
+
+private:
+ // Prohibit copy constructor & assignment operator.
+ PrettyWriter(const PrettyWriter&);
+ PrettyWriter& operator=(const PrettyWriter&);
+};
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_RAPIDJSON_H_
diff --git a/include/rapidjson/rapidjson.h b/include/rapidjson/rapidjson.h
new file mode 100644
index 00000000..053b2ce4
--- /dev/null
+++ b/include/rapidjson/rapidjson.h
@@ -0,0 +1,615 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_RAPIDJSON_H_
+#define RAPIDJSON_RAPIDJSON_H_
+
+/*!\file rapidjson.h
+ \brief common definitions and configuration
+
+ \see RAPIDJSON_CONFIG
+ */
+
+/*! \defgroup RAPIDJSON_CONFIG RapidJSON configuration
+ \brief Configuration macros for library features
+
+ Some RapidJSON features are configurable to adapt the library to a wide
+ variety of platforms, environments and usage scenarios. Most of the
+ features can be configured in terms of overriden or predefined
+ preprocessor macros at compile-time.
+
+ Some additional customization is available in the \ref RAPIDJSON_ERRORS APIs.
+
+ \note These macros should be given on the compiler command-line
+ (where applicable) to avoid inconsistent values when compiling
+ different translation units of a single application.
+ */
+
+#include <cstdlib> // malloc(), realloc(), free(), size_t
+#include <cstring> // memset(), memcpy(), memmove(), memcmp()
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_VERSION_STRING
+//
+// ALWAYS synchronize the following 3 macros with corresponding variables in /CMakeLists.txt.
+//
+
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+// token stringification
+#define RAPIDJSON_STRINGIFY(x) RAPIDJSON_DO_STRINGIFY(x)
+#define RAPIDJSON_DO_STRINGIFY(x) #x
+//!@endcond
+
+/*! \def RAPIDJSON_MAJOR_VERSION
+ \ingroup RAPIDJSON_CONFIG
+ \brief Major version of RapidJSON in integer.
+*/
+/*! \def RAPIDJSON_MINOR_VERSION
+ \ingroup RAPIDJSON_CONFIG
+ \brief Minor version of RapidJSON in integer.
+*/
+/*! \def RAPIDJSON_PATCH_VERSION
+ \ingroup RAPIDJSON_CONFIG
+ \brief Patch version of RapidJSON in integer.
+*/
+/*! \def RAPIDJSON_VERSION_STRING
+ \ingroup RAPIDJSON_CONFIG
+ \brief Version of RapidJSON in "<major>.<minor>.<patch>" string format.
+*/
+#define RAPIDJSON_MAJOR_VERSION 1
+#define RAPIDJSON_MINOR_VERSION 1
+#define RAPIDJSON_PATCH_VERSION 0
+#define RAPIDJSON_VERSION_STRING \
+ RAPIDJSON_STRINGIFY(RAPIDJSON_MAJOR_VERSION.RAPIDJSON_MINOR_VERSION.RAPIDJSON_PATCH_VERSION)
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_NAMESPACE_(BEGIN|END)
+/*! \def RAPIDJSON_NAMESPACE
+ \ingroup RAPIDJSON_CONFIG
+ \brief provide custom rapidjson namespace
+
+ In order to avoid symbol clashes and/or "One Definition Rule" errors
+ between multiple inclusions of (different versions of) RapidJSON in
+ a single binary, users can customize the name of the main RapidJSON
+ namespace.
+
+ In case of a single nesting level, defining \c RAPIDJSON_NAMESPACE
+ to a custom name (e.g. \c MyRapidJSON) is sufficient. If multiple
+ levels are needed, both \ref RAPIDJSON_NAMESPACE_BEGIN and \ref
+ RAPIDJSON_NAMESPACE_END need to be defined as well:
+
+ \code
+ // in some .cpp file
+ #define RAPIDJSON_NAMESPACE my::rapidjson
+ #define RAPIDJSON_NAMESPACE_BEGIN namespace my { namespace rapidjson {
+ #define RAPIDJSON_NAMESPACE_END } }
+ #include "rapidjson/..."
+ \endcode
+
+ \see rapidjson
+ */
+/*! \def RAPIDJSON_NAMESPACE_BEGIN
+ \ingroup RAPIDJSON_CONFIG
+ \brief provide custom rapidjson namespace (opening expression)
+ \see RAPIDJSON_NAMESPACE
+*/
+/*! \def RAPIDJSON_NAMESPACE_END
+ \ingroup RAPIDJSON_CONFIG
+ \brief provide custom rapidjson namespace (closing expression)
+ \see RAPIDJSON_NAMESPACE
+*/
+#ifndef RAPIDJSON_NAMESPACE
+#define RAPIDJSON_NAMESPACE rapidjson
+#endif
+#ifndef RAPIDJSON_NAMESPACE_BEGIN
+#define RAPIDJSON_NAMESPACE_BEGIN namespace RAPIDJSON_NAMESPACE {
+#endif
+#ifndef RAPIDJSON_NAMESPACE_END
+#define RAPIDJSON_NAMESPACE_END }
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_HAS_STDSTRING
+
+#ifndef RAPIDJSON_HAS_STDSTRING
+#ifdef RAPIDJSON_DOXYGEN_RUNNING
+#define RAPIDJSON_HAS_STDSTRING 1 // force generation of documentation
+#else
+#define RAPIDJSON_HAS_STDSTRING 0 // no std::string support by default
+#endif
+/*! \def RAPIDJSON_HAS_STDSTRING
+ \ingroup RAPIDJSON_CONFIG
+ \brief Enable RapidJSON support for \c std::string
+
+ By defining this preprocessor symbol to \c 1, several convenience functions for using
+ \ref rapidjson::GenericValue with \c std::string are enabled, especially
+ for construction and comparison.
+
+ \hideinitializer
+*/
+#endif // !defined(RAPIDJSON_HAS_STDSTRING)
+
+#if RAPIDJSON_HAS_STDSTRING
+#include <string>
+#endif // RAPIDJSON_HAS_STDSTRING
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_NO_INT64DEFINE
+
+/*! \def RAPIDJSON_NO_INT64DEFINE
+ \ingroup RAPIDJSON_CONFIG
+ \brief Use external 64-bit integer types.
+
+ RapidJSON requires the 64-bit integer types \c int64_t and \c uint64_t types
+ to be available at global scope.
+
+ If users have their own definition, define RAPIDJSON_NO_INT64DEFINE to
+ prevent RapidJSON from defining its own types.
+*/
+#ifndef RAPIDJSON_NO_INT64DEFINE
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+#if defined(_MSC_VER) && (_MSC_VER < 1800) // Visual Studio 2013
+#include "msinttypes/stdint.h"
+#include "msinttypes/inttypes.h"
+#else
+// Other compilers should have this.
+#include <stdint.h>
+#include <inttypes.h>
+#endif
+//!@endcond
+#ifdef RAPIDJSON_DOXYGEN_RUNNING
+#define RAPIDJSON_NO_INT64DEFINE
+#endif
+#endif // RAPIDJSON_NO_INT64TYPEDEF
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_FORCEINLINE
+
+#ifndef RAPIDJSON_FORCEINLINE
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+#if defined(_MSC_VER) && defined(NDEBUG)
+#define RAPIDJSON_FORCEINLINE __forceinline
+#elif defined(__GNUC__) && __GNUC__ >= 4 && defined(NDEBUG)
+#define RAPIDJSON_FORCEINLINE __attribute__((always_inline))
+#else
+#define RAPIDJSON_FORCEINLINE
+#endif
+//!@endcond
+#endif // RAPIDJSON_FORCEINLINE
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_ENDIAN
+#define RAPIDJSON_LITTLEENDIAN 0 //!< Little endian machine
+#define RAPIDJSON_BIGENDIAN 1 //!< Big endian machine
+
+//! Endianness of the machine.
+/*!
+ \def RAPIDJSON_ENDIAN
+ \ingroup RAPIDJSON_CONFIG
+
+ GCC 4.6 provided macro for detecting endianness of the target machine. But other
+ compilers may not have this. User can define RAPIDJSON_ENDIAN to either
+ \ref RAPIDJSON_LITTLEENDIAN or \ref RAPIDJSON_BIGENDIAN.
+
+ Default detection implemented with reference to
+ \li https://gcc.gnu.org/onlinedocs/gcc-4.6.0/cpp/Common-Predefined-Macros.html
+ \li http://www.boost.org/doc/libs/1_42_0/boost/detail/endian.hpp
+*/
+#ifndef RAPIDJSON_ENDIAN
+// Detect with GCC 4.6's macro
+# ifdef __BYTE_ORDER__
+# if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
+# elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
+# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
+# else
+# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN.
+# endif // __BYTE_ORDER__
+// Detect with GLIBC's endian.h
+# elif defined(__GLIBC__)
+# include <endian.h>
+# if (__BYTE_ORDER == __LITTLE_ENDIAN)
+# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
+# elif (__BYTE_ORDER == __BIG_ENDIAN)
+# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
+# else
+# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN.
+# endif // __GLIBC__
+// Detect with _LITTLE_ENDIAN and _BIG_ENDIAN macro
+# elif defined(_LITTLE_ENDIAN) && !defined(_BIG_ENDIAN)
+# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
+# elif defined(_BIG_ENDIAN) && !defined(_LITTLE_ENDIAN)
+# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
+// Detect with architecture macros
+# elif defined(__sparc) || defined(__sparc__) || defined(_POWER) || defined(__powerpc__) || defined(__ppc__) || defined(__hpux) || defined(__hppa) || defined(_MIPSEB) || defined(_POWER) || defined(__s390__)
+# define RAPIDJSON_ENDIAN RAPIDJSON_BIGENDIAN
+# elif defined(__i386__) || defined(__alpha__) || defined(__ia64) || defined(__ia64__) || defined(_M_IX86) || defined(_M_IA64) || defined(_M_ALPHA) || defined(__amd64) || defined(__amd64__) || defined(_M_AMD64) || defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || defined(__bfin__)
+# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
+# elif defined(_MSC_VER) && defined(_M_ARM)
+# define RAPIDJSON_ENDIAN RAPIDJSON_LITTLEENDIAN
+# elif defined(RAPIDJSON_DOXYGEN_RUNNING)
+# define RAPIDJSON_ENDIAN
+# else
+# error Unknown machine endianess detected. User needs to define RAPIDJSON_ENDIAN.
+# endif
+#endif // RAPIDJSON_ENDIAN
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_64BIT
+
+//! Whether using 64-bit architecture
+#ifndef RAPIDJSON_64BIT
+#if defined(__LP64__) || (defined(__x86_64__) && defined(__ILP32__)) || defined(_WIN64) || defined(__EMSCRIPTEN__)
+#define RAPIDJSON_64BIT 1
+#else
+#define RAPIDJSON_64BIT 0
+#endif
+#endif // RAPIDJSON_64BIT
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_ALIGN
+
+//! Data alignment of the machine.
+/*! \ingroup RAPIDJSON_CONFIG
+ \param x pointer to align
+
+ Some machines require strict data alignment. Currently the default uses 4 bytes
+ alignment on 32-bit platforms and 8 bytes alignment for 64-bit platforms.
+ User can customize by defining the RAPIDJSON_ALIGN function macro.
+*/
+#ifndef RAPIDJSON_ALIGN
+#if RAPIDJSON_64BIT == 1
+#define RAPIDJSON_ALIGN(x) (((x) + static_cast<uint64_t>(7u)) & ~static_cast<uint64_t>(7u))
+#else
+#define RAPIDJSON_ALIGN(x) (((x) + 3u) & ~3u)
+#endif
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_UINT64_C2
+
+//! Construct a 64-bit literal by a pair of 32-bit integer.
+/*!
+ 64-bit literal with or without ULL suffix is prone to compiler warnings.
+ UINT64_C() is C macro which cause compilation problems.
+ Use this macro to define 64-bit constants by a pair of 32-bit integer.
+*/
+#ifndef RAPIDJSON_UINT64_C2
+#define RAPIDJSON_UINT64_C2(high32, low32) ((static_cast<uint64_t>(high32) << 32) | static_cast<uint64_t>(low32))
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_48BITPOINTER_OPTIMIZATION
+
+//! Use only lower 48-bit address for some pointers.
+/*!
+ \ingroup RAPIDJSON_CONFIG
+
+ This optimization uses the fact that current X86-64 architecture only implement lower 48-bit virtual address.
+ The higher 16-bit can be used for storing other data.
+ \c GenericValue uses this optimization to reduce its size form 24 bytes to 16 bytes in 64-bit architecture.
+*/
+#ifndef RAPIDJSON_48BITPOINTER_OPTIMIZATION
+#if defined(__amd64__) || defined(__amd64) || defined(__x86_64__) || defined(__x86_64) || defined(_M_X64) || defined(_M_AMD64)
+#define RAPIDJSON_48BITPOINTER_OPTIMIZATION 1
+#else
+#define RAPIDJSON_48BITPOINTER_OPTIMIZATION 0
+#endif
+#endif // RAPIDJSON_48BITPOINTER_OPTIMIZATION
+
+#if RAPIDJSON_48BITPOINTER_OPTIMIZATION == 1
+#if RAPIDJSON_64BIT != 1
+#error RAPIDJSON_48BITPOINTER_OPTIMIZATION can only be set to 1 when RAPIDJSON_64BIT=1
+#endif
+#define RAPIDJSON_SETPOINTER(type, p, x) (p = reinterpret_cast<type *>((reinterpret_cast<uintptr_t>(p) & static_cast<uintptr_t>(RAPIDJSON_UINT64_C2(0xFFFF0000, 0x00000000))) | reinterpret_cast<uintptr_t>(reinterpret_cast<const void*>(x))))
+#define RAPIDJSON_GETPOINTER(type, p) (reinterpret_cast<type *>(reinterpret_cast<uintptr_t>(p) & static_cast<uintptr_t>(RAPIDJSON_UINT64_C2(0x0000FFFF, 0xFFFFFFFF))))
+#else
+#define RAPIDJSON_SETPOINTER(type, p, x) (p = (x))
+#define RAPIDJSON_GETPOINTER(type, p) (p)
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_SSE2/RAPIDJSON_SSE42/RAPIDJSON_SIMD
+
+/*! \def RAPIDJSON_SIMD
+ \ingroup RAPIDJSON_CONFIG
+ \brief Enable SSE2/SSE4.2 optimization.
+
+ RapidJSON supports optimized implementations for some parsing operations
+ based on the SSE2 or SSE4.2 SIMD extensions on modern Intel-compatible
+ processors.
+
+ To enable these optimizations, two different symbols can be defined;
+ \code
+ // Enable SSE2 optimization.
+ #define RAPIDJSON_SSE2
+
+ // Enable SSE4.2 optimization.
+ #define RAPIDJSON_SSE42
+ \endcode
+
+ \c RAPIDJSON_SSE42 takes precedence, if both are defined.
+
+ If any of these symbols is defined, RapidJSON defines the macro
+ \c RAPIDJSON_SIMD to indicate the availability of the optimized code.
+*/
+#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42) \
+ || defined(RAPIDJSON_DOXYGEN_RUNNING)
+#define RAPIDJSON_SIMD
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_NO_SIZETYPEDEFINE
+
+#ifndef RAPIDJSON_NO_SIZETYPEDEFINE
+/*! \def RAPIDJSON_NO_SIZETYPEDEFINE
+ \ingroup RAPIDJSON_CONFIG
+ \brief User-provided \c SizeType definition.
+
+ In order to avoid using 32-bit size types for indexing strings and arrays,
+ define this preprocessor symbol and provide the type rapidjson::SizeType
+ before including RapidJSON:
+ \code
+ #define RAPIDJSON_NO_SIZETYPEDEFINE
+ namespace rapidjson { typedef ::std::size_t SizeType; }
+ #include "rapidjson/..."
+ \endcode
+
+ \see rapidjson::SizeType
+*/
+#ifdef RAPIDJSON_DOXYGEN_RUNNING
+#define RAPIDJSON_NO_SIZETYPEDEFINE
+#endif
+RAPIDJSON_NAMESPACE_BEGIN
+//! Size type (for string lengths, array sizes, etc.)
+/*! RapidJSON uses 32-bit array/string indices even on 64-bit platforms,
+ instead of using \c size_t. Users may override the SizeType by defining
+ \ref RAPIDJSON_NO_SIZETYPEDEFINE.
+*/
+typedef unsigned SizeType;
+RAPIDJSON_NAMESPACE_END
+#endif
+
+// always import std::size_t to rapidjson namespace
+RAPIDJSON_NAMESPACE_BEGIN
+using std::size_t;
+RAPIDJSON_NAMESPACE_END
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_ASSERT
+
+//! Assertion.
+/*! \ingroup RAPIDJSON_CONFIG
+ By default, rapidjson uses C \c assert() for internal assertions.
+ User can override it by defining RAPIDJSON_ASSERT(x) macro.
+
+ \note Parsing errors are handled and can be customized by the
+ \ref RAPIDJSON_ERRORS APIs.
+*/
+#ifndef RAPIDJSON_ASSERT
+#include <cassert>
+#define RAPIDJSON_ASSERT(x) assert(x)
+#endif // RAPIDJSON_ASSERT
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_STATIC_ASSERT
+
+// Adopt from boost
+#ifndef RAPIDJSON_STATIC_ASSERT
+#ifndef __clang__
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+#endif
+RAPIDJSON_NAMESPACE_BEGIN
+template <bool x> struct STATIC_ASSERTION_FAILURE;
+template <> struct STATIC_ASSERTION_FAILURE<true> { enum { value = 1 }; };
+template<int x> struct StaticAssertTest {};
+RAPIDJSON_NAMESPACE_END
+
+#define RAPIDJSON_JOIN(X, Y) RAPIDJSON_DO_JOIN(X, Y)
+#define RAPIDJSON_DO_JOIN(X, Y) RAPIDJSON_DO_JOIN2(X, Y)
+#define RAPIDJSON_DO_JOIN2(X, Y) X##Y
+
+#if defined(__GNUC__)
+#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE __attribute__((unused))
+#else
+#define RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
+#endif
+#ifndef __clang__
+//!@endcond
+#endif
+
+/*! \def RAPIDJSON_STATIC_ASSERT
+ \brief (Internal) macro to check for conditions at compile-time
+ \param x compile-time condition
+ \hideinitializer
+ */
+#define RAPIDJSON_STATIC_ASSERT(x) \
+ typedef ::RAPIDJSON_NAMESPACE::StaticAssertTest< \
+ sizeof(::RAPIDJSON_NAMESPACE::STATIC_ASSERTION_FAILURE<bool(x) >)> \
+ RAPIDJSON_JOIN(StaticAssertTypedef, __LINE__) RAPIDJSON_STATIC_ASSERT_UNUSED_ATTRIBUTE
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_LIKELY, RAPIDJSON_UNLIKELY
+
+//! Compiler branching hint for expression with high probability to be true.
+/*!
+ \ingroup RAPIDJSON_CONFIG
+ \param x Boolean expression likely to be true.
+*/
+#ifndef RAPIDJSON_LIKELY
+#if defined(__GNUC__) || defined(__clang__)
+#define RAPIDJSON_LIKELY(x) __builtin_expect(!!(x), 1)
+#else
+#define RAPIDJSON_LIKELY(x) (x)
+#endif
+#endif
+
+//! Compiler branching hint for expression with low probability to be true.
+/*!
+ \ingroup RAPIDJSON_CONFIG
+ \param x Boolean expression unlikely to be true.
+*/
+#ifndef RAPIDJSON_UNLIKELY
+#if defined(__GNUC__) || defined(__clang__)
+#define RAPIDJSON_UNLIKELY(x) __builtin_expect(!!(x), 0)
+#else
+#define RAPIDJSON_UNLIKELY(x) (x)
+#endif
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// Helpers
+
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+
+#define RAPIDJSON_MULTILINEMACRO_BEGIN do {
+#define RAPIDJSON_MULTILINEMACRO_END \
+} while((void)0, 0)
+
+// adopted from Boost
+#define RAPIDJSON_VERSION_CODE(x,y,z) \
+ (((x)*100000) + ((y)*100) + (z))
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_DIAG_PUSH/POP, RAPIDJSON_DIAG_OFF
+
+#if defined(__GNUC__)
+#define RAPIDJSON_GNUC \
+ RAPIDJSON_VERSION_CODE(__GNUC__,__GNUC_MINOR__,__GNUC_PATCHLEVEL__)
+#endif
+
+#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,2,0))
+
+#define RAPIDJSON_PRAGMA(x) _Pragma(RAPIDJSON_STRINGIFY(x))
+#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(GCC diagnostic x)
+#define RAPIDJSON_DIAG_OFF(x) \
+ RAPIDJSON_DIAG_PRAGMA(ignored RAPIDJSON_STRINGIFY(RAPIDJSON_JOIN(-W,x)))
+
+// push/pop support in Clang and GCC>=4.6
+#if defined(__clang__) || (defined(RAPIDJSON_GNUC) && RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0))
+#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push)
+#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop)
+#else // GCC >= 4.2, < 4.6
+#define RAPIDJSON_DIAG_PUSH /* ignored */
+#define RAPIDJSON_DIAG_POP /* ignored */
+#endif
+
+#elif defined(_MSC_VER)
+
+// pragma (MSVC specific)
+#define RAPIDJSON_PRAGMA(x) __pragma(x)
+#define RAPIDJSON_DIAG_PRAGMA(x) RAPIDJSON_PRAGMA(warning(x))
+
+#define RAPIDJSON_DIAG_OFF(x) RAPIDJSON_DIAG_PRAGMA(disable: x)
+#define RAPIDJSON_DIAG_PUSH RAPIDJSON_DIAG_PRAGMA(push)
+#define RAPIDJSON_DIAG_POP RAPIDJSON_DIAG_PRAGMA(pop)
+
+#else
+
+#define RAPIDJSON_DIAG_OFF(x) /* ignored */
+#define RAPIDJSON_DIAG_PUSH /* ignored */
+#define RAPIDJSON_DIAG_POP /* ignored */
+
+#endif // RAPIDJSON_DIAG_*
+
+///////////////////////////////////////////////////////////////////////////////
+// C++11 features
+
+#ifndef RAPIDJSON_HAS_CXX11_RVALUE_REFS
+#if defined(__clang__)
+#if __has_feature(cxx_rvalue_references) && \
+ (defined(_LIBCPP_VERSION) || defined(__GLIBCXX__) && __GLIBCXX__ >= 20080306)
+#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1
+#else
+#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0
+#endif
+#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \
+ (defined(_MSC_VER) && _MSC_VER >= 1600)
+
+#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 1
+#else
+#define RAPIDJSON_HAS_CXX11_RVALUE_REFS 0
+#endif
+#endif // RAPIDJSON_HAS_CXX11_RVALUE_REFS
+
+#ifndef RAPIDJSON_HAS_CXX11_NOEXCEPT
+#if defined(__clang__)
+#define RAPIDJSON_HAS_CXX11_NOEXCEPT __has_feature(cxx_noexcept)
+#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,6,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__))
+// (defined(_MSC_VER) && _MSC_VER >= ????) // not yet supported
+#define RAPIDJSON_HAS_CXX11_NOEXCEPT 1
+#else
+#define RAPIDJSON_HAS_CXX11_NOEXCEPT 0
+#endif
+#endif
+#if RAPIDJSON_HAS_CXX11_NOEXCEPT
+#define RAPIDJSON_NOEXCEPT noexcept
+#else
+#define RAPIDJSON_NOEXCEPT /* noexcept */
+#endif // RAPIDJSON_HAS_CXX11_NOEXCEPT
+
+// no automatic detection, yet
+#ifndef RAPIDJSON_HAS_CXX11_TYPETRAITS
+#define RAPIDJSON_HAS_CXX11_TYPETRAITS 0
+#endif
+
+#ifndef RAPIDJSON_HAS_CXX11_RANGE_FOR
+#if defined(__clang__)
+#define RAPIDJSON_HAS_CXX11_RANGE_FOR __has_feature(cxx_range_for)
+#elif (defined(RAPIDJSON_GNUC) && (RAPIDJSON_GNUC >= RAPIDJSON_VERSION_CODE(4,3,0)) && defined(__GXX_EXPERIMENTAL_CXX0X__)) || \
+ (defined(_MSC_VER) && _MSC_VER >= 1700)
+#define RAPIDJSON_HAS_CXX11_RANGE_FOR 1
+#else
+#define RAPIDJSON_HAS_CXX11_RANGE_FOR 0
+#endif
+#endif // RAPIDJSON_HAS_CXX11_RANGE_FOR
+
+//!@endcond
+
+///////////////////////////////////////////////////////////////////////////////
+// new/delete
+
+#ifndef RAPIDJSON_NEW
+///! customization point for global \c new
+#define RAPIDJSON_NEW(x) new x
+#endif
+#ifndef RAPIDJSON_DELETE
+///! customization point for global \c delete
+#define RAPIDJSON_DELETE(x) delete x
+#endif
+
+///////////////////////////////////////////////////////////////////////////////
+// Type
+
+/*! \namespace rapidjson
+ \brief main RapidJSON namespace
+ \see RAPIDJSON_NAMESPACE
+*/
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Type of JSON value
+enum Type {
+ kNullType = 0, //!< null
+ kFalseType = 1, //!< false
+ kTrueType = 2, //!< true
+ kObjectType = 3, //!< object
+ kArrayType = 4, //!< array
+ kStringType = 5, //!< string
+ kNumberType = 6 //!< number
+};
+
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_RAPIDJSON_H_
diff --git a/include/rapidjson/reader.h b/include/rapidjson/reader.h
new file mode 100644
index 00000000..19f8849b
--- /dev/null
+++ b/include/rapidjson/reader.h
@@ -0,0 +1,1879 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_READER_H_
+#define RAPIDJSON_READER_H_
+
+/*! \file reader.h */
+
+#include "allocators.h"
+#include "stream.h"
+#include "encodedstream.h"
+#include "internal/meta.h"
+#include "internal/stack.h"
+#include "internal/strtod.h"
+#include <limits>
+
+#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
+#include <intrin.h>
+#pragma intrinsic(_BitScanForward)
+#endif
+#ifdef RAPIDJSON_SSE42
+#include <nmmintrin.h>
+#elif defined(RAPIDJSON_SSE2)
+#include <emmintrin.h>
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
+RAPIDJSON_DIAG_OFF(4702) // unreachable code
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(old-style-cast)
+RAPIDJSON_DIAG_OFF(padded)
+RAPIDJSON_DIAG_OFF(switch-enum)
+#endif
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(effc++)
+#endif
+
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+#define RAPIDJSON_NOTHING /* deliberately empty */
+#ifndef RAPIDJSON_PARSE_ERROR_EARLY_RETURN
+#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN(value) \
+ RAPIDJSON_MULTILINEMACRO_BEGIN \
+ if (RAPIDJSON_UNLIKELY(HasParseError())) { return value; } \
+ RAPIDJSON_MULTILINEMACRO_END
+#endif
+#define RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID \
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(RAPIDJSON_NOTHING)
+//!@endcond
+
+/*! \def RAPIDJSON_PARSE_ERROR_NORETURN
+ \ingroup RAPIDJSON_ERRORS
+ \brief Macro to indicate a parse error.
+ \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
+ \param offset position of the error in JSON input (\c size_t)
+
+ This macros can be used as a customization point for the internal
+ error handling mechanism of RapidJSON.
+
+ A common usage model is to throw an exception instead of requiring the
+ caller to explicitly check the \ref rapidjson::GenericReader::Parse's
+ return value:
+
+ \code
+ #define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode,offset) \
+ throw ParseException(parseErrorCode, #parseErrorCode, offset)
+
+ #include <stdexcept> // std::runtime_error
+ #include "rapidjson/error/error.h" // rapidjson::ParseResult
+
+ struct ParseException : std::runtime_error, rapidjson::ParseResult {
+ ParseException(rapidjson::ParseErrorCode code, const char* msg, size_t offset)
+ : std::runtime_error(msg), ParseResult(code, offset) {}
+ };
+
+ #include "rapidjson/reader.h"
+ \endcode
+
+ \see RAPIDJSON_PARSE_ERROR, rapidjson::GenericReader::Parse
+ */
+#ifndef RAPIDJSON_PARSE_ERROR_NORETURN
+#define RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset) \
+ RAPIDJSON_MULTILINEMACRO_BEGIN \
+ RAPIDJSON_ASSERT(!HasParseError()); /* Error can only be assigned once */ \
+ SetParseError(parseErrorCode, offset); \
+ RAPIDJSON_MULTILINEMACRO_END
+#endif
+
+/*! \def RAPIDJSON_PARSE_ERROR
+ \ingroup RAPIDJSON_ERRORS
+ \brief (Internal) macro to indicate and handle a parse error.
+ \param parseErrorCode \ref rapidjson::ParseErrorCode of the error
+ \param offset position of the error in JSON input (\c size_t)
+
+ Invokes RAPIDJSON_PARSE_ERROR_NORETURN and stops the parsing.
+
+ \see RAPIDJSON_PARSE_ERROR_NORETURN
+ \hideinitializer
+ */
+#ifndef RAPIDJSON_PARSE_ERROR
+#define RAPIDJSON_PARSE_ERROR(parseErrorCode, offset) \
+ RAPIDJSON_MULTILINEMACRO_BEGIN \
+ RAPIDJSON_PARSE_ERROR_NORETURN(parseErrorCode, offset); \
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID; \
+ RAPIDJSON_MULTILINEMACRO_END
+#endif
+
+#include "error/error.h" // ParseErrorCode, ParseResult
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+///////////////////////////////////////////////////////////////////////////////
+// ParseFlag
+
+/*! \def RAPIDJSON_PARSE_DEFAULT_FLAGS
+ \ingroup RAPIDJSON_CONFIG
+ \brief User-defined kParseDefaultFlags definition.
+
+ User can define this as any \c ParseFlag combinations.
+*/
+#ifndef RAPIDJSON_PARSE_DEFAULT_FLAGS
+#define RAPIDJSON_PARSE_DEFAULT_FLAGS kParseNoFlags
+#endif
+
+//! Combination of parseFlags
+/*! \see Reader::Parse, Document::Parse, Document::ParseInsitu, Document::ParseStream
+ */
+enum ParseFlag {
+ kParseNoFlags = 0, //!< No flags are set.
+ kParseInsituFlag = 1, //!< In-situ(destructive) parsing.
+ kParseValidateEncodingFlag = 2, //!< Validate encoding of JSON strings.
+ kParseIterativeFlag = 4, //!< Iterative(constant complexity in terms of function call stack size) parsing.
+ kParseStopWhenDoneFlag = 8, //!< After parsing a complete JSON root from stream, stop further processing the rest of stream. When this flag is used, parser will not generate kParseErrorDocumentRootNotSingular error.
+ kParseFullPrecisionFlag = 16, //!< Parse number in full precision (but slower).
+ kParseCommentsFlag = 32, //!< Allow one-line (//) and multi-line (/**/) comments.
+ kParseNumbersAsStringsFlag = 64, //!< Parse all numbers (ints/doubles) as strings.
+ kParseTrailingCommasFlag = 128, //!< Allow trailing commas at the end of objects and arrays.
+ kParseNanAndInfFlag = 256, //!< Allow parsing NaN, Inf, Infinity, -Inf and -Infinity as doubles.
+ kParseDefaultFlags = RAPIDJSON_PARSE_DEFAULT_FLAGS //!< Default parse flags. Can be customized by defining RAPIDJSON_PARSE_DEFAULT_FLAGS
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Handler
+
+/*! \class rapidjson::Handler
+ \brief Concept for receiving events from GenericReader upon parsing.
+ The functions return true if no error occurs. If they return false,
+ the event publisher should terminate the process.
+\code
+concept Handler {
+ typename Ch;
+
+ bool Null();
+ bool Bool(bool b);
+ bool Int(int i);
+ bool Uint(unsigned i);
+ bool Int64(int64_t i);
+ bool Uint64(uint64_t i);
+ bool Double(double d);
+ /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length)
+ bool RawNumber(const Ch* str, SizeType length, bool copy);
+ bool String(const Ch* str, SizeType length, bool copy);
+ bool StartObject();
+ bool Key(const Ch* str, SizeType length, bool copy);
+ bool EndObject(SizeType memberCount);
+ bool StartArray();
+ bool EndArray(SizeType elementCount);
+};
+\endcode
+*/
+///////////////////////////////////////////////////////////////////////////////
+// BaseReaderHandler
+
+//! Default implementation of Handler.
+/*! This can be used as base class of any reader handler.
+ \note implements Handler concept
+*/
+template<typename Encoding = UTF8<>, typename Derived = void>
+struct BaseReaderHandler {
+ typedef typename Encoding::Ch Ch;
+
+ typedef typename internal::SelectIf<internal::IsSame<Derived, void>, BaseReaderHandler, Derived>::Type Override;
+
+ bool Default() { return true; }
+ bool Null() { return static_cast<Override&>(*this).Default(); }
+ bool Bool(bool) { return static_cast<Override&>(*this).Default(); }
+ bool Int(int) { return static_cast<Override&>(*this).Default(); }
+ bool Uint(unsigned) { return static_cast<Override&>(*this).Default(); }
+ bool Int64(int64_t) { return static_cast<Override&>(*this).Default(); }
+ bool Uint64(uint64_t) { return static_cast<Override&>(*this).Default(); }
+ bool Double(double) { return static_cast<Override&>(*this).Default(); }
+ /// enabled via kParseNumbersAsStringsFlag, string is not null-terminated (use length)
+ bool RawNumber(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); }
+ bool String(const Ch*, SizeType, bool) { return static_cast<Override&>(*this).Default(); }
+ bool StartObject() { return static_cast<Override&>(*this).Default(); }
+ bool Key(const Ch* str, SizeType len, bool copy) { return static_cast<Override&>(*this).String(str, len, copy); }
+ bool EndObject(SizeType) { return static_cast<Override&>(*this).Default(); }
+ bool StartArray() { return static_cast<Override&>(*this).Default(); }
+ bool EndArray(SizeType) { return static_cast<Override&>(*this).Default(); }
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// StreamLocalCopy
+
+namespace internal {
+
+template<typename Stream, int = StreamTraits<Stream>::copyOptimization>
+class StreamLocalCopy;
+
+//! Do copy optimization.
+template<typename Stream>
+class StreamLocalCopy<Stream, 1> {
+public:
+ StreamLocalCopy(Stream& original) : s(original), original_(original) {}
+ ~StreamLocalCopy() { original_ = s; }
+
+ Stream s;
+
+private:
+ StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
+
+ Stream& original_;
+};
+
+//! Keep reference.
+template<typename Stream>
+class StreamLocalCopy<Stream, 0> {
+public:
+ StreamLocalCopy(Stream& original) : s(original) {}
+
+ Stream& s;
+
+private:
+ StreamLocalCopy& operator=(const StreamLocalCopy&) /* = delete */;
+};
+
+} // namespace internal
+
+///////////////////////////////////////////////////////////////////////////////
+// SkipWhitespace
+
+//! Skip the JSON white spaces in a stream.
+/*! \param is A input stream for skipping white spaces.
+ \note This function has SSE2/SSE4.2 specialization.
+*/
+template<typename InputStream>
+void SkipWhitespace(InputStream& is) {
+ internal::StreamLocalCopy<InputStream> copy(is);
+ InputStream& s(copy.s);
+
+ typename InputStream::Ch c;
+ while ((c = s.Peek()) == ' ' || c == '\n' || c == '\r' || c == '\t')
+ s.Take();
+}
+
+inline const char* SkipWhitespace(const char* p, const char* end) {
+ while (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
+ ++p;
+ return p;
+}
+
+#ifdef RAPIDJSON_SSE42
+//! Skip whitespace with SSE 4.2 pcmpistrm instruction, testing 16 8-byte characters at once.
+inline const char *SkipWhitespace_SIMD(const char* p) {
+ // Fast return for single non-whitespace
+ if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
+ ++p;
+ else
+ return p;
+
+ // 16-byte align to the next boundary
+ const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
+ while (p != nextAligned)
+ if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
+ ++p;
+ else
+ return p;
+
+ // The rest of string using SIMD
+ static const char whitespace[16] = " \n\r\t";
+ const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0]));
+
+ for (;; p += 16) {
+ const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
+ const int r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY));
+ if (r != 0) { // some of characters is non-whitespace
+#ifdef _MSC_VER // Find the index of first non-whitespace
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ return p + offset;
+#else
+ return p + __builtin_ffs(r) - 1;
+#endif
+ }
+ }
+}
+
+inline const char *SkipWhitespace_SIMD(const char* p, const char* end) {
+ // Fast return for single non-whitespace
+ if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
+ ++p;
+ else
+ return p;
+
+ // The middle of string using SIMD
+ static const char whitespace[16] = " \n\r\t";
+ const __m128i w = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespace[0]));
+
+ for (; p <= end - 16; p += 16) {
+ const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p));
+ const int r = _mm_cvtsi128_si32(_mm_cmpistrm(w, s, _SIDD_UBYTE_OPS | _SIDD_CMP_EQUAL_ANY | _SIDD_BIT_MASK | _SIDD_NEGATIVE_POLARITY));
+ if (r != 0) { // some of characters is non-whitespace
+#ifdef _MSC_VER // Find the index of first non-whitespace
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ return p + offset;
+#else
+ return p + __builtin_ffs(r) - 1;
+#endif
+ }
+ }
+
+ return SkipWhitespace(p, end);
+}
+
+#elif defined(RAPIDJSON_SSE2)
+
+//! Skip whitespace with SSE2 instructions, testing 16 8-byte characters at once.
+inline const char *SkipWhitespace_SIMD(const char* p) {
+ // Fast return for single non-whitespace
+ if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
+ ++p;
+ else
+ return p;
+
+ // 16-byte align to the next boundary
+ const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
+ while (p != nextAligned)
+ if (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t')
+ ++p;
+ else
+ return p;
+
+ // The rest of string
+ #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c }
+ static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') };
+ #undef C16
+
+ const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0]));
+ const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0]));
+ const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0]));
+ const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0]));
+
+ for (;; p += 16) {
+ const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
+ __m128i x = _mm_cmpeq_epi8(s, w0);
+ x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1));
+ x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2));
+ x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3));
+ unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x));
+ if (r != 0) { // some of characters may be non-whitespace
+#ifdef _MSC_VER // Find the index of first non-whitespace
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ return p + offset;
+#else
+ return p + __builtin_ffs(r) - 1;
+#endif
+ }
+ }
+}
+
+inline const char *SkipWhitespace_SIMD(const char* p, const char* end) {
+ // Fast return for single non-whitespace
+ if (p != end && (*p == ' ' || *p == '\n' || *p == '\r' || *p == '\t'))
+ ++p;
+ else
+ return p;
+
+ // The rest of string
+ #define C16(c) { c, c, c, c, c, c, c, c, c, c, c, c, c, c, c, c }
+ static const char whitespaces[4][16] = { C16(' '), C16('\n'), C16('\r'), C16('\t') };
+ #undef C16
+
+ const __m128i w0 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[0][0]));
+ const __m128i w1 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[1][0]));
+ const __m128i w2 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[2][0]));
+ const __m128i w3 = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&whitespaces[3][0]));
+
+ for (; p <= end - 16; p += 16) {
+ const __m128i s = _mm_loadu_si128(reinterpret_cast<const __m128i *>(p));
+ __m128i x = _mm_cmpeq_epi8(s, w0);
+ x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w1));
+ x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w2));
+ x = _mm_or_si128(x, _mm_cmpeq_epi8(s, w3));
+ unsigned short r = static_cast<unsigned short>(~_mm_movemask_epi8(x));
+ if (r != 0) { // some of characters may be non-whitespace
+#ifdef _MSC_VER // Find the index of first non-whitespace
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ return p + offset;
+#else
+ return p + __builtin_ffs(r) - 1;
+#endif
+ }
+ }
+
+ return SkipWhitespace(p, end);
+}
+
+#endif // RAPIDJSON_SSE2
+
+#ifdef RAPIDJSON_SIMD
+//! Template function specialization for InsituStringStream
+template<> inline void SkipWhitespace(InsituStringStream& is) {
+ is.src_ = const_cast<char*>(SkipWhitespace_SIMD(is.src_));
+}
+
+//! Template function specialization for StringStream
+template<> inline void SkipWhitespace(StringStream& is) {
+ is.src_ = SkipWhitespace_SIMD(is.src_);
+}
+
+template<> inline void SkipWhitespace(EncodedInputStream<UTF8<>, MemoryStream>& is) {
+ is.is_.src_ = SkipWhitespace_SIMD(is.is_.src_, is.is_.end_);
+}
+#endif // RAPIDJSON_SIMD
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericReader
+
+//! SAX-style JSON parser. Use \ref Reader for UTF8 encoding and default allocator.
+/*! GenericReader parses JSON text from a stream, and send events synchronously to an
+ object implementing Handler concept.
+
+ It needs to allocate a stack for storing a single decoded string during
+ non-destructive parsing.
+
+ For in-situ parsing, the decoded string is directly written to the source
+ text string, no temporary buffer is required.
+
+ A GenericReader object can be reused for parsing multiple JSON text.
+
+ \tparam SourceEncoding Encoding of the input stream.
+ \tparam TargetEncoding Encoding of the parse output.
+ \tparam StackAllocator Allocator type for stack.
+*/
+template <typename SourceEncoding, typename TargetEncoding, typename StackAllocator = CrtAllocator>
+class GenericReader {
+public:
+ typedef typename SourceEncoding::Ch Ch; //!< SourceEncoding character type
+
+ //! Constructor.
+ /*! \param stackAllocator Optional allocator for allocating stack memory. (Only use for non-destructive parsing)
+ \param stackCapacity stack capacity in bytes for storing a single decoded string. (Only use for non-destructive parsing)
+ */
+ GenericReader(StackAllocator* stackAllocator = 0, size_t stackCapacity = kDefaultStackCapacity) : stack_(stackAllocator, stackCapacity), parseResult_() {}
+
+ //! Parse JSON text.
+ /*! \tparam parseFlags Combination of \ref ParseFlag.
+ \tparam InputStream Type of input stream, implementing Stream concept.
+ \tparam Handler Type of handler, implementing Handler concept.
+ \param is Input stream to be parsed.
+ \param handler The handler to receive events.
+ \return Whether the parsing is successful.
+ */
+ template <unsigned parseFlags, typename InputStream, typename Handler>
+ ParseResult Parse(InputStream& is, Handler& handler) {
+ if (parseFlags & kParseIterativeFlag)
+ return IterativeParse<parseFlags>(is, handler);
+
+ parseResult_.Clear();
+
+ ClearStackOnExit scope(*this);
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
+
+ if (RAPIDJSON_UNLIKELY(is.Peek() == '\0')) {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentEmpty, is.Tell());
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
+ }
+ else {
+ ParseValue<parseFlags>(is, handler);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
+
+ if (!(parseFlags & kParseStopWhenDoneFlag)) {
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
+
+ if (RAPIDJSON_UNLIKELY(is.Peek() != '\0')) {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorDocumentRootNotSingular, is.Tell());
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
+ }
+ }
+ }
+
+ return parseResult_;
+ }
+
+ //! Parse JSON text (with \ref kParseDefaultFlags)
+ /*! \tparam InputStream Type of input stream, implementing Stream concept
+ \tparam Handler Type of handler, implementing Handler concept.
+ \param is Input stream to be parsed.
+ \param handler The handler to receive events.
+ \return Whether the parsing is successful.
+ */
+ template <typename InputStream, typename Handler>
+ ParseResult Parse(InputStream& is, Handler& handler) {
+ return Parse<kParseDefaultFlags>(is, handler);
+ }
+
+ //! Whether a parse error has occured in the last parsing.
+ bool HasParseError() const { return parseResult_.IsError(); }
+
+ //! Get the \ref ParseErrorCode of last parsing.
+ ParseErrorCode GetParseErrorCode() const { return parseResult_.Code(); }
+
+ //! Get the position of last parsing error in input, 0 otherwise.
+ size_t GetErrorOffset() const { return parseResult_.Offset(); }
+
+protected:
+ void SetParseError(ParseErrorCode code, size_t offset) { parseResult_.Set(code, offset); }
+
+private:
+ // Prohibit copy constructor & assignment operator.
+ GenericReader(const GenericReader&);
+ GenericReader& operator=(const GenericReader&);
+
+ void ClearStack() { stack_.Clear(); }
+
+ // clear stack on any exit from ParseStream, e.g. due to exception
+ struct ClearStackOnExit {
+ explicit ClearStackOnExit(GenericReader& r) : r_(r) {}
+ ~ClearStackOnExit() { r_.ClearStack(); }
+ private:
+ GenericReader& r_;
+ ClearStackOnExit(const ClearStackOnExit&);
+ ClearStackOnExit& operator=(const ClearStackOnExit&);
+ };
+
+ template<unsigned parseFlags, typename InputStream>
+ void SkipWhitespaceAndComments(InputStream& is) {
+ SkipWhitespace(is);
+
+ if (parseFlags & kParseCommentsFlag) {
+ while (RAPIDJSON_UNLIKELY(Consume(is, '/'))) {
+ if (Consume(is, '*')) {
+ while (true) {
+ if (RAPIDJSON_UNLIKELY(is.Peek() == '\0'))
+ RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell());
+ else if (Consume(is, '*')) {
+ if (Consume(is, '/'))
+ break;
+ }
+ else
+ is.Take();
+ }
+ }
+ else if (RAPIDJSON_LIKELY(Consume(is, '/')))
+ while (is.Peek() != '\0' && is.Take() != '\n');
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorUnspecificSyntaxError, is.Tell());
+
+ SkipWhitespace(is);
+ }
+ }
+ }
+
+ // Parse object: { string : value, ... }
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseObject(InputStream& is, Handler& handler) {
+ RAPIDJSON_ASSERT(is.Peek() == '{');
+ is.Take(); // Skip '{'
+
+ if (RAPIDJSON_UNLIKELY(!handler.StartObject()))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ if (Consume(is, '}')) {
+ if (RAPIDJSON_UNLIKELY(!handler.EndObject(0))) // empty object
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ return;
+ }
+
+ for (SizeType memberCount = 0;;) {
+ if (RAPIDJSON_UNLIKELY(is.Peek() != '"'))
+ RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell());
+
+ ParseString<parseFlags>(is, handler, true);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ if (RAPIDJSON_UNLIKELY(!Consume(is, ':')))
+ RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell());
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ ParseValue<parseFlags>(is, handler);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ ++memberCount;
+
+ switch (is.Peek()) {
+ case ',':
+ is.Take();
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+ break;
+ case '}':
+ is.Take();
+ if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount)))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ return;
+ default:
+ RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); break; // This useless break is only for making warning and coverage happy
+ }
+
+ if (parseFlags & kParseTrailingCommasFlag) {
+ if (is.Peek() == '}') {
+ if (RAPIDJSON_UNLIKELY(!handler.EndObject(memberCount)))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ is.Take();
+ return;
+ }
+ }
+ }
+ }
+
+ // Parse array: [ value, ... ]
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseArray(InputStream& is, Handler& handler) {
+ RAPIDJSON_ASSERT(is.Peek() == '[');
+ is.Take(); // Skip '['
+
+ if (RAPIDJSON_UNLIKELY(!handler.StartArray()))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ if (Consume(is, ']')) {
+ if (RAPIDJSON_UNLIKELY(!handler.EndArray(0))) // empty array
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ return;
+ }
+
+ for (SizeType elementCount = 0;;) {
+ ParseValue<parseFlags>(is, handler);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ ++elementCount;
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+
+ if (Consume(is, ',')) {
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+ }
+ else if (Consume(is, ']')) {
+ if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount)))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ return;
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell());
+
+ if (parseFlags & kParseTrailingCommasFlag) {
+ if (is.Peek() == ']') {
+ if (RAPIDJSON_UNLIKELY(!handler.EndArray(elementCount)))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ is.Take();
+ return;
+ }
+ }
+ }
+ }
+
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseNull(InputStream& is, Handler& handler) {
+ RAPIDJSON_ASSERT(is.Peek() == 'n');
+ is.Take();
+
+ if (RAPIDJSON_LIKELY(Consume(is, 'u') && Consume(is, 'l') && Consume(is, 'l'))) {
+ if (RAPIDJSON_UNLIKELY(!handler.Null()))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell());
+ }
+
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseTrue(InputStream& is, Handler& handler) {
+ RAPIDJSON_ASSERT(is.Peek() == 't');
+ is.Take();
+
+ if (RAPIDJSON_LIKELY(Consume(is, 'r') && Consume(is, 'u') && Consume(is, 'e'))) {
+ if (RAPIDJSON_UNLIKELY(!handler.Bool(true)))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell());
+ }
+
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseFalse(InputStream& is, Handler& handler) {
+ RAPIDJSON_ASSERT(is.Peek() == 'f');
+ is.Take();
+
+ if (RAPIDJSON_LIKELY(Consume(is, 'a') && Consume(is, 'l') && Consume(is, 's') && Consume(is, 'e'))) {
+ if (RAPIDJSON_UNLIKELY(!handler.Bool(false)))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, is.Tell());
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell());
+ }
+
+ template<typename InputStream>
+ RAPIDJSON_FORCEINLINE static bool Consume(InputStream& is, typename InputStream::Ch expect) {
+ if (RAPIDJSON_LIKELY(is.Peek() == expect)) {
+ is.Take();
+ return true;
+ }
+ else
+ return false;
+ }
+
+ // Helper function to parse four hexidecimal digits in \uXXXX in ParseString().
+ template<typename InputStream>
+ unsigned ParseHex4(InputStream& is, size_t escapeOffset) {
+ unsigned codepoint = 0;
+ for (int i = 0; i < 4; i++) {
+ Ch c = is.Peek();
+ codepoint <<= 4;
+ codepoint += static_cast<unsigned>(c);
+ if (c >= '0' && c <= '9')
+ codepoint -= '0';
+ else if (c >= 'A' && c <= 'F')
+ codepoint -= 'A' - 10;
+ else if (c >= 'a' && c <= 'f')
+ codepoint -= 'a' - 10;
+ else {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorStringUnicodeEscapeInvalidHex, escapeOffset);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(0);
+ }
+ is.Take();
+ }
+ return codepoint;
+ }
+
+ template <typename CharType>
+ class StackStream {
+ public:
+ typedef CharType Ch;
+
+ StackStream(internal::Stack<StackAllocator>& stack) : stack_(stack), length_(0) {}
+ RAPIDJSON_FORCEINLINE void Put(Ch c) {
+ *stack_.template Push<Ch>() = c;
+ ++length_;
+ }
+
+ RAPIDJSON_FORCEINLINE void* Push(SizeType count) {
+ length_ += count;
+ return stack_.template Push<Ch>(count);
+ }
+
+ size_t Length() const { return length_; }
+
+ Ch* Pop() {
+ return stack_.template Pop<Ch>(length_);
+ }
+
+ private:
+ StackStream(const StackStream&);
+ StackStream& operator=(const StackStream&);
+
+ internal::Stack<StackAllocator>& stack_;
+ SizeType length_;
+ };
+
+ // Parse string and generate String event. Different code paths for kParseInsituFlag.
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseString(InputStream& is, Handler& handler, bool isKey = false) {
+ internal::StreamLocalCopy<InputStream> copy(is);
+ InputStream& s(copy.s);
+
+ RAPIDJSON_ASSERT(s.Peek() == '\"');
+ s.Take(); // Skip '\"'
+
+ bool success = false;
+ if (parseFlags & kParseInsituFlag) {
+ typename InputStream::Ch *head = s.PutBegin();
+ ParseStringToStream<parseFlags, SourceEncoding, SourceEncoding>(s, s);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+ size_t length = s.PutEnd(head) - 1;
+ RAPIDJSON_ASSERT(length <= 0xFFFFFFFF);
+ const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head);
+ success = (isKey ? handler.Key(str, SizeType(length), false) : handler.String(str, SizeType(length), false));
+ }
+ else {
+ StackStream<typename TargetEncoding::Ch> stackStream(stack_);
+ ParseStringToStream<parseFlags, SourceEncoding, TargetEncoding>(s, stackStream);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+ SizeType length = static_cast<SizeType>(stackStream.Length()) - 1;
+ const typename TargetEncoding::Ch* const str = stackStream.Pop();
+ success = (isKey ? handler.Key(str, length, true) : handler.String(str, length, true));
+ }
+ if (RAPIDJSON_UNLIKELY(!success))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, s.Tell());
+ }
+
+ // Parse string to an output is
+ // This function handles the prefix/suffix double quotes, escaping, and optional encoding validation.
+ template<unsigned parseFlags, typename SEncoding, typename TEncoding, typename InputStream, typename OutputStream>
+ RAPIDJSON_FORCEINLINE void ParseStringToStream(InputStream& is, OutputStream& os) {
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
+ static const char escape[256] = {
+ Z16, Z16, 0, 0,'\"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'/',
+ Z16, Z16, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0,
+ 0, 0,'\b', 0, 0, 0,'\f', 0, 0, 0, 0, 0, 0, 0,'\n', 0,
+ 0, 0,'\r', 0,'\t', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16
+ };
+#undef Z16
+//!@endcond
+
+ for (;;) {
+ // Scan and copy string before "\\\"" or < 0x20. This is an optional optimzation.
+ if (!(parseFlags & kParseValidateEncodingFlag))
+ ScanCopyUnescapedString(is, os);
+
+ Ch c = is.Peek();
+ if (RAPIDJSON_UNLIKELY(c == '\\')) { // Escape
+ size_t escapeOffset = is.Tell(); // For invalid escaping, report the inital '\\' as error offset
+ is.Take();
+ Ch e = is.Peek();
+ if ((sizeof(Ch) == 1 || unsigned(e) < 256) && RAPIDJSON_LIKELY(escape[static_cast<unsigned char>(e)])) {
+ is.Take();
+ os.Put(static_cast<typename TEncoding::Ch>(escape[static_cast<unsigned char>(e)]));
+ }
+ else if (RAPIDJSON_LIKELY(e == 'u')) { // Unicode
+ is.Take();
+ unsigned codepoint = ParseHex4(is, escapeOffset);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+ if (RAPIDJSON_UNLIKELY(codepoint >= 0xD800 && codepoint <= 0xDBFF)) {
+ // Handle UTF-16 surrogate pair
+ if (RAPIDJSON_UNLIKELY(!Consume(is, '\\') || !Consume(is, 'u')))
+ RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset);
+ unsigned codepoint2 = ParseHex4(is, escapeOffset);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN_VOID;
+ if (RAPIDJSON_UNLIKELY(codepoint2 < 0xDC00 || codepoint2 > 0xDFFF))
+ RAPIDJSON_PARSE_ERROR(kParseErrorStringUnicodeSurrogateInvalid, escapeOffset);
+ codepoint = (((codepoint - 0xD800) << 10) | (codepoint2 - 0xDC00)) + 0x10000;
+ }
+ TEncoding::Encode(os, codepoint);
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, escapeOffset);
+ }
+ else if (RAPIDJSON_UNLIKELY(c == '"')) { // Closing double quote
+ is.Take();
+ os.Put('\0'); // null-terminate the string
+ return;
+ }
+ else if (RAPIDJSON_UNLIKELY(static_cast<unsigned>(c) < 0x20)) { // RFC 4627: unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
+ if (c == '\0')
+ RAPIDJSON_PARSE_ERROR(kParseErrorStringMissQuotationMark, is.Tell());
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorStringEscapeInvalid, is.Tell());
+ }
+ else {
+ size_t offset = is.Tell();
+ if (RAPIDJSON_UNLIKELY((parseFlags & kParseValidateEncodingFlag ?
+ !Transcoder<SEncoding, TEncoding>::Validate(is, os) :
+ !Transcoder<SEncoding, TEncoding>::Transcode(is, os))))
+ RAPIDJSON_PARSE_ERROR(kParseErrorStringInvalidEncoding, offset);
+ }
+ }
+ }
+
+ template<typename InputStream, typename OutputStream>
+ static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InputStream&, OutputStream&) {
+ // Do nothing for generic version
+ }
+
+#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
+ // StringStream -> StackStream<char>
+ static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(StringStream& is, StackStream<char>& os) {
+ const char* p = is.src_;
+
+ // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
+ const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
+ while (p != nextAligned)
+ if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
+ is.src_ = p;
+ return;
+ }
+ else
+ os.Put(*p++);
+
+ // The rest of string using SIMD
+ static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
+ static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
+ static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 };
+ const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
+ const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
+ const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
+
+ for (;; p += 16) {
+ const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
+ const __m128i t1 = _mm_cmpeq_epi8(s, dq);
+ const __m128i t2 = _mm_cmpeq_epi8(s, bs);
+ const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19
+ const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
+ unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
+ if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
+ SizeType length;
+ #ifdef _MSC_VER // Find the index of first escaped
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ length = offset;
+ #else
+ length = static_cast<SizeType>(__builtin_ffs(r) - 1);
+ #endif
+ char* q = reinterpret_cast<char*>(os.Push(length));
+ for (size_t i = 0; i < length; i++)
+ q[i] = p[i];
+
+ p += length;
+ break;
+ }
+ _mm_storeu_si128(reinterpret_cast<__m128i *>(os.Push(16)), s);
+ }
+
+ is.src_ = p;
+ }
+
+ // InsituStringStream -> InsituStringStream
+ static RAPIDJSON_FORCEINLINE void ScanCopyUnescapedString(InsituStringStream& is, InsituStringStream& os) {
+ RAPIDJSON_ASSERT(&is == &os);
+ (void)os;
+
+ if (is.src_ == is.dst_) {
+ SkipUnescapedString(is);
+ return;
+ }
+
+ char* p = is.src_;
+ char *q = is.dst_;
+
+ // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
+ const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
+ while (p != nextAligned)
+ if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
+ is.src_ = p;
+ is.dst_ = q;
+ return;
+ }
+ else
+ *q++ = *p++;
+
+ // The rest of string using SIMD
+ static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
+ static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
+ static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 };
+ const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
+ const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
+ const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
+
+ for (;; p += 16, q += 16) {
+ const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
+ const __m128i t1 = _mm_cmpeq_epi8(s, dq);
+ const __m128i t2 = _mm_cmpeq_epi8(s, bs);
+ const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19
+ const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
+ unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
+ if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
+ size_t length;
+#ifdef _MSC_VER // Find the index of first escaped
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ length = offset;
+#else
+ length = static_cast<size_t>(__builtin_ffs(r) - 1);
+#endif
+ for (const char* pend = p + length; p != pend; )
+ *q++ = *p++;
+ break;
+ }
+ _mm_storeu_si128(reinterpret_cast<__m128i *>(q), s);
+ }
+
+ is.src_ = p;
+ is.dst_ = q;
+ }
+
+ // When read/write pointers are the same for insitu stream, just skip unescaped characters
+ static RAPIDJSON_FORCEINLINE void SkipUnescapedString(InsituStringStream& is) {
+ RAPIDJSON_ASSERT(is.src_ == is.dst_);
+ char* p = is.src_;
+
+ // Scan one by one until alignment (unaligned load may cross page boundary and cause crash)
+ const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
+ for (; p != nextAligned; p++)
+ if (RAPIDJSON_UNLIKELY(*p == '\"') || RAPIDJSON_UNLIKELY(*p == '\\') || RAPIDJSON_UNLIKELY(static_cast<unsigned>(*p) < 0x20)) {
+ is.src_ = is.dst_ = p;
+ return;
+ }
+
+ // The rest of string using SIMD
+ static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
+ static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
+ static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 };
+ const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
+ const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
+ const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
+
+ for (;; p += 16) {
+ const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
+ const __m128i t1 = _mm_cmpeq_epi8(s, dq);
+ const __m128i t2 = _mm_cmpeq_epi8(s, bs);
+ const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19
+ const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
+ unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
+ if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
+ size_t length;
+#ifdef _MSC_VER // Find the index of first escaped
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ length = offset;
+#else
+ length = static_cast<size_t>(__builtin_ffs(r) - 1);
+#endif
+ p += length;
+ break;
+ }
+ }
+
+ is.src_ = is.dst_ = p;
+ }
+#endif
+
+ template<typename InputStream, bool backup, bool pushOnTake>
+ class NumberStream;
+
+ template<typename InputStream>
+ class NumberStream<InputStream, false, false> {
+ public:
+ typedef typename InputStream::Ch Ch;
+
+ NumberStream(GenericReader& reader, InputStream& s) : is(s) { (void)reader; }
+ ~NumberStream() {}
+
+ RAPIDJSON_FORCEINLINE Ch Peek() const { return is.Peek(); }
+ RAPIDJSON_FORCEINLINE Ch TakePush() { return is.Take(); }
+ RAPIDJSON_FORCEINLINE Ch Take() { return is.Take(); }
+ RAPIDJSON_FORCEINLINE void Push(char) {}
+
+ size_t Tell() { return is.Tell(); }
+ size_t Length() { return 0; }
+ const char* Pop() { return 0; }
+
+ protected:
+ NumberStream& operator=(const NumberStream&);
+
+ InputStream& is;
+ };
+
+ template<typename InputStream>
+ class NumberStream<InputStream, true, false> : public NumberStream<InputStream, false, false> {
+ typedef NumberStream<InputStream, false, false> Base;
+ public:
+ NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is), stackStream(reader.stack_) {}
+ ~NumberStream() {}
+
+ RAPIDJSON_FORCEINLINE Ch TakePush() {
+ stackStream.Put(static_cast<char>(Base::is.Peek()));
+ return Base::is.Take();
+ }
+
+ RAPIDJSON_FORCEINLINE void Push(char c) {
+ stackStream.Put(c);
+ }
+
+ size_t Length() { return stackStream.Length(); }
+
+ const char* Pop() {
+ stackStream.Put('\0');
+ return stackStream.Pop();
+ }
+
+ private:
+ StackStream<char> stackStream;
+ };
+
+ template<typename InputStream>
+ class NumberStream<InputStream, true, true> : public NumberStream<InputStream, true, false> {
+ typedef NumberStream<InputStream, true, false> Base;
+ public:
+ NumberStream(GenericReader& reader, InputStream& is) : Base(reader, is) {}
+ ~NumberStream() {}
+
+ RAPIDJSON_FORCEINLINE Ch Take() { return Base::TakePush(); }
+ };
+
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseNumber(InputStream& is, Handler& handler) {
+ internal::StreamLocalCopy<InputStream> copy(is);
+ NumberStream<InputStream,
+ ((parseFlags & kParseNumbersAsStringsFlag) != 0) ?
+ ((parseFlags & kParseInsituFlag) == 0) :
+ ((parseFlags & kParseFullPrecisionFlag) != 0),
+ (parseFlags & kParseNumbersAsStringsFlag) != 0 &&
+ (parseFlags & kParseInsituFlag) == 0> s(*this, copy.s);
+
+ size_t startOffset = s.Tell();
+ double d = 0.0;
+ bool useNanOrInf = false;
+
+ // Parse minus
+ bool minus = Consume(s, '-');
+
+ // Parse int: zero / ( digit1-9 *DIGIT )
+ unsigned i = 0;
+ uint64_t i64 = 0;
+ bool use64bit = false;
+ int significandDigit = 0;
+ if (RAPIDJSON_UNLIKELY(s.Peek() == '0')) {
+ i = 0;
+ s.TakePush();
+ }
+ else if (RAPIDJSON_LIKELY(s.Peek() >= '1' && s.Peek() <= '9')) {
+ i = static_cast<unsigned>(s.TakePush() - '0');
+
+ if (minus)
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ if (RAPIDJSON_UNLIKELY(i >= 214748364)) { // 2^31 = 2147483648
+ if (RAPIDJSON_LIKELY(i != 214748364 || s.Peek() > '8')) {
+ i64 = i;
+ use64bit = true;
+ break;
+ }
+ }
+ i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
+ significandDigit++;
+ }
+ else
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ if (RAPIDJSON_UNLIKELY(i >= 429496729)) { // 2^32 - 1 = 4294967295
+ if (RAPIDJSON_LIKELY(i != 429496729 || s.Peek() > '5')) {
+ i64 = i;
+ use64bit = true;
+ break;
+ }
+ }
+ i = i * 10 + static_cast<unsigned>(s.TakePush() - '0');
+ significandDigit++;
+ }
+ }
+ // Parse NaN or Infinity here
+ else if ((parseFlags & kParseNanAndInfFlag) && RAPIDJSON_LIKELY((s.Peek() == 'I' || s.Peek() == 'N'))) {
+ useNanOrInf = true;
+ if (RAPIDJSON_LIKELY(Consume(s, 'N') && Consume(s, 'a') && Consume(s, 'N'))) {
+ d = std::numeric_limits<double>::quiet_NaN();
+ }
+ else if (RAPIDJSON_LIKELY(Consume(s, 'I') && Consume(s, 'n') && Consume(s, 'f'))) {
+ d = (minus ? -std::numeric_limits<double>::infinity() : std::numeric_limits<double>::infinity());
+ if (RAPIDJSON_UNLIKELY(s.Peek() == 'i' && !(Consume(s, 'i') && Consume(s, 'n')
+ && Consume(s, 'i') && Consume(s, 't') && Consume(s, 'y'))))
+ RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, s.Tell());
+
+ // Parse 64bit int
+ bool useDouble = false;
+ if (use64bit) {
+ if (minus)
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC))) // 2^63 = 9223372036854775808
+ if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x0CCCCCCC, 0xCCCCCCCC) || s.Peek() > '8')) {
+ d = static_cast<double>(i64);
+ useDouble = true;
+ break;
+ }
+ i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
+ significandDigit++;
+ }
+ else
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ if (RAPIDJSON_UNLIKELY(i64 >= RAPIDJSON_UINT64_C2(0x19999999, 0x99999999))) // 2^64 - 1 = 18446744073709551615
+ if (RAPIDJSON_LIKELY(i64 != RAPIDJSON_UINT64_C2(0x19999999, 0x99999999) || s.Peek() > '5')) {
+ d = static_cast<double>(i64);
+ useDouble = true;
+ break;
+ }
+ i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
+ significandDigit++;
+ }
+ }
+
+ // Force double for big integer
+ if (useDouble) {
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ if (RAPIDJSON_UNLIKELY(d >= 1.7976931348623157e307)) // DBL_MAX / 10.0
+ RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset);
+ d = d * 10 + (s.TakePush() - '0');
+ }
+ }
+
+ // Parse frac = decimal-point 1*DIGIT
+ int expFrac = 0;
+ size_t decimalPosition;
+ if (Consume(s, '.')) {
+ decimalPosition = s.Length();
+
+ if (RAPIDJSON_UNLIKELY(!(s.Peek() >= '0' && s.Peek() <= '9')))
+ RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissFraction, s.Tell());
+
+ if (!useDouble) {
+#if RAPIDJSON_64BIT
+ // Use i64 to store significand in 64-bit architecture
+ if (!use64bit)
+ i64 = i;
+
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ if (i64 > RAPIDJSON_UINT64_C2(0x1FFFFF, 0xFFFFFFFF)) // 2^53 - 1 for fast path
+ break;
+ else {
+ i64 = i64 * 10 + static_cast<unsigned>(s.TakePush() - '0');
+ --expFrac;
+ if (i64 != 0)
+ significandDigit++;
+ }
+ }
+
+ d = static_cast<double>(i64);
+#else
+ // Use double to store significand in 32-bit architecture
+ d = static_cast<double>(use64bit ? i64 : i);
+#endif
+ useDouble = true;
+ }
+
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ if (significandDigit < 17) {
+ d = d * 10.0 + (s.TakePush() - '0');
+ --expFrac;
+ if (RAPIDJSON_LIKELY(d > 0.0))
+ significandDigit++;
+ }
+ else
+ s.TakePush();
+ }
+ }
+ else
+ decimalPosition = s.Length(); // decimal position at the end of integer.
+
+ // Parse exp = e [ minus / plus ] 1*DIGIT
+ int exp = 0;
+ if (Consume(s, 'e') || Consume(s, 'E')) {
+ if (!useDouble) {
+ d = static_cast<double>(use64bit ? i64 : i);
+ useDouble = true;
+ }
+
+ bool expMinus = false;
+ if (Consume(s, '+'))
+ ;
+ else if (Consume(s, '-'))
+ expMinus = true;
+
+ if (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ exp = static_cast<int>(s.Take() - '0');
+ if (expMinus) {
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ exp = exp * 10 + static_cast<int>(s.Take() - '0');
+ if (exp >= 214748364) { // Issue #313: prevent overflow exponent
+ while (RAPIDJSON_UNLIKELY(s.Peek() >= '0' && s.Peek() <= '9')) // Consume the rest of exponent
+ s.Take();
+ }
+ }
+ }
+ else { // positive exp
+ int maxExp = 308 - expFrac;
+ while (RAPIDJSON_LIKELY(s.Peek() >= '0' && s.Peek() <= '9')) {
+ exp = exp * 10 + static_cast<int>(s.Take() - '0');
+ if (RAPIDJSON_UNLIKELY(exp > maxExp))
+ RAPIDJSON_PARSE_ERROR(kParseErrorNumberTooBig, startOffset);
+ }
+ }
+ }
+ else
+ RAPIDJSON_PARSE_ERROR(kParseErrorNumberMissExponent, s.Tell());
+
+ if (expMinus)
+ exp = -exp;
+ }
+
+ // Finish parsing, call event according to the type of number.
+ bool cont = true;
+
+ if (parseFlags & kParseNumbersAsStringsFlag) {
+ if (parseFlags & kParseInsituFlag) {
+ s.Pop(); // Pop stack no matter if it will be used or not.
+ typename InputStream::Ch* head = is.PutBegin();
+ const size_t length = s.Tell() - startOffset;
+ RAPIDJSON_ASSERT(length <= 0xFFFFFFFF);
+ // unable to insert the \0 character here, it will erase the comma after this number
+ const typename TargetEncoding::Ch* const str = reinterpret_cast<typename TargetEncoding::Ch*>(head);
+ cont = handler.RawNumber(str, SizeType(length), false);
+ }
+ else {
+ SizeType numCharsToCopy = static_cast<SizeType>(s.Length());
+ StringStream srcStream(s.Pop());
+ StackStream<typename TargetEncoding::Ch> dstStream(stack_);
+ while (numCharsToCopy--) {
+ Transcoder<UTF8<>, TargetEncoding>::Transcode(srcStream, dstStream);
+ }
+ dstStream.Put('\0');
+ const typename TargetEncoding::Ch* str = dstStream.Pop();
+ const SizeType length = static_cast<SizeType>(dstStream.Length()) - 1;
+ cont = handler.RawNumber(str, SizeType(length), true);
+ }
+ }
+ else {
+ size_t length = s.Length();
+ const char* decimal = s.Pop(); // Pop stack no matter if it will be used or not.
+
+ if (useDouble) {
+ int p = exp + expFrac;
+ if (parseFlags & kParseFullPrecisionFlag)
+ d = internal::StrtodFullPrecision(d, p, decimal, length, decimalPosition, exp);
+ else
+ d = internal::StrtodNormalPrecision(d, p);
+
+ cont = handler.Double(minus ? -d : d);
+ }
+ else if (useNanOrInf) {
+ cont = handler.Double(d);
+ }
+ else {
+ if (use64bit) {
+ if (minus)
+ cont = handler.Int64(static_cast<int64_t>(~i64 + 1));
+ else
+ cont = handler.Uint64(i64);
+ }
+ else {
+ if (minus)
+ cont = handler.Int(static_cast<int32_t>(~i + 1));
+ else
+ cont = handler.Uint(i);
+ }
+ }
+ }
+ if (RAPIDJSON_UNLIKELY(!cont))
+ RAPIDJSON_PARSE_ERROR(kParseErrorTermination, startOffset);
+ }
+
+ // Parse any JSON value
+ template<unsigned parseFlags, typename InputStream, typename Handler>
+ void ParseValue(InputStream& is, Handler& handler) {
+ switch (is.Peek()) {
+ case 'n': ParseNull <parseFlags>(is, handler); break;
+ case 't': ParseTrue <parseFlags>(is, handler); break;
+ case 'f': ParseFalse <parseFlags>(is, handler); break;
+ case '"': ParseString<parseFlags>(is, handler); break;
+ case '{': ParseObject<parseFlags>(is, handler); break;
+ case '[': ParseArray <parseFlags>(is, handler); break;
+ default :
+ ParseNumber<parseFlags>(is, handler);
+ break;
+
+ }
+ }
+
+ // Iterative Parsing
+
+ // States
+ enum IterativeParsingState {
+ IterativeParsingStartState = 0,
+ IterativeParsingFinishState,
+ IterativeParsingErrorState,
+
+ // Object states
+ IterativeParsingObjectInitialState,
+ IterativeParsingMemberKeyState,
+ IterativeParsingKeyValueDelimiterState,
+ IterativeParsingMemberValueState,
+ IterativeParsingMemberDelimiterState,
+ IterativeParsingObjectFinishState,
+
+ // Array states
+ IterativeParsingArrayInitialState,
+ IterativeParsingElementState,
+ IterativeParsingElementDelimiterState,
+ IterativeParsingArrayFinishState,
+
+ // Single value state
+ IterativeParsingValueState
+ };
+
+ enum { cIterativeParsingStateCount = IterativeParsingValueState + 1 };
+
+ // Tokens
+ enum Token {
+ LeftBracketToken = 0,
+ RightBracketToken,
+
+ LeftCurlyBracketToken,
+ RightCurlyBracketToken,
+
+ CommaToken,
+ ColonToken,
+
+ StringToken,
+ FalseToken,
+ TrueToken,
+ NullToken,
+ NumberToken,
+
+ kTokenCount
+ };
+
+ RAPIDJSON_FORCEINLINE Token Tokenize(Ch c) {
+
+//!@cond RAPIDJSON_HIDDEN_FROM_DOXYGEN
+#define N NumberToken
+#define N16 N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N
+ // Maps from ASCII to Token
+ static const unsigned char tokenMap[256] = {
+ N16, // 00~0F
+ N16, // 10~1F
+ N, N, StringToken, N, N, N, N, N, N, N, N, N, CommaToken, N, N, N, // 20~2F
+ N, N, N, N, N, N, N, N, N, N, ColonToken, N, N, N, N, N, // 30~3F
+ N16, // 40~4F
+ N, N, N, N, N, N, N, N, N, N, N, LeftBracketToken, N, RightBracketToken, N, N, // 50~5F
+ N, N, N, N, N, N, FalseToken, N, N, N, N, N, N, N, NullToken, N, // 60~6F
+ N, N, N, N, TrueToken, N, N, N, N, N, N, LeftCurlyBracketToken, N, RightCurlyBracketToken, N, N, // 70~7F
+ N16, N16, N16, N16, N16, N16, N16, N16 // 80~FF
+ };
+#undef N
+#undef N16
+//!@endcond
+
+ if (sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256)
+ return static_cast<Token>(tokenMap[static_cast<unsigned char>(c)]);
+ else
+ return NumberToken;
+ }
+
+ RAPIDJSON_FORCEINLINE IterativeParsingState Predict(IterativeParsingState state, Token token) {
+ // current state x one lookahead token -> new state
+ static const char G[cIterativeParsingStateCount][kTokenCount] = {
+ // Start
+ {
+ IterativeParsingArrayInitialState, // Left bracket
+ IterativeParsingErrorState, // Right bracket
+ IterativeParsingObjectInitialState, // Left curly bracket
+ IterativeParsingErrorState, // Right curly bracket
+ IterativeParsingErrorState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingValueState, // String
+ IterativeParsingValueState, // False
+ IterativeParsingValueState, // True
+ IterativeParsingValueState, // Null
+ IterativeParsingValueState // Number
+ },
+ // Finish(sink state)
+ {
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState
+ },
+ // Error(sink state)
+ {
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState
+ },
+ // ObjectInitial
+ {
+ IterativeParsingErrorState, // Left bracket
+ IterativeParsingErrorState, // Right bracket
+ IterativeParsingErrorState, // Left curly bracket
+ IterativeParsingObjectFinishState, // Right curly bracket
+ IterativeParsingErrorState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingMemberKeyState, // String
+ IterativeParsingErrorState, // False
+ IterativeParsingErrorState, // True
+ IterativeParsingErrorState, // Null
+ IterativeParsingErrorState // Number
+ },
+ // MemberKey
+ {
+ IterativeParsingErrorState, // Left bracket
+ IterativeParsingErrorState, // Right bracket
+ IterativeParsingErrorState, // Left curly bracket
+ IterativeParsingErrorState, // Right curly bracket
+ IterativeParsingErrorState, // Comma
+ IterativeParsingKeyValueDelimiterState, // Colon
+ IterativeParsingErrorState, // String
+ IterativeParsingErrorState, // False
+ IterativeParsingErrorState, // True
+ IterativeParsingErrorState, // Null
+ IterativeParsingErrorState // Number
+ },
+ // KeyValueDelimiter
+ {
+ IterativeParsingArrayInitialState, // Left bracket(push MemberValue state)
+ IterativeParsingErrorState, // Right bracket
+ IterativeParsingObjectInitialState, // Left curly bracket(push MemberValue state)
+ IterativeParsingErrorState, // Right curly bracket
+ IterativeParsingErrorState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingMemberValueState, // String
+ IterativeParsingMemberValueState, // False
+ IterativeParsingMemberValueState, // True
+ IterativeParsingMemberValueState, // Null
+ IterativeParsingMemberValueState // Number
+ },
+ // MemberValue
+ {
+ IterativeParsingErrorState, // Left bracket
+ IterativeParsingErrorState, // Right bracket
+ IterativeParsingErrorState, // Left curly bracket
+ IterativeParsingObjectFinishState, // Right curly bracket
+ IterativeParsingMemberDelimiterState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingErrorState, // String
+ IterativeParsingErrorState, // False
+ IterativeParsingErrorState, // True
+ IterativeParsingErrorState, // Null
+ IterativeParsingErrorState // Number
+ },
+ // MemberDelimiter
+ {
+ IterativeParsingErrorState, // Left bracket
+ IterativeParsingErrorState, // Right bracket
+ IterativeParsingErrorState, // Left curly bracket
+ IterativeParsingObjectFinishState, // Right curly bracket
+ IterativeParsingErrorState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingMemberKeyState, // String
+ IterativeParsingErrorState, // False
+ IterativeParsingErrorState, // True
+ IterativeParsingErrorState, // Null
+ IterativeParsingErrorState // Number
+ },
+ // ObjectFinish(sink state)
+ {
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState
+ },
+ // ArrayInitial
+ {
+ IterativeParsingArrayInitialState, // Left bracket(push Element state)
+ IterativeParsingArrayFinishState, // Right bracket
+ IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
+ IterativeParsingErrorState, // Right curly bracket
+ IterativeParsingErrorState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingElementState, // String
+ IterativeParsingElementState, // False
+ IterativeParsingElementState, // True
+ IterativeParsingElementState, // Null
+ IterativeParsingElementState // Number
+ },
+ // Element
+ {
+ IterativeParsingErrorState, // Left bracket
+ IterativeParsingArrayFinishState, // Right bracket
+ IterativeParsingErrorState, // Left curly bracket
+ IterativeParsingErrorState, // Right curly bracket
+ IterativeParsingElementDelimiterState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingErrorState, // String
+ IterativeParsingErrorState, // False
+ IterativeParsingErrorState, // True
+ IterativeParsingErrorState, // Null
+ IterativeParsingErrorState // Number
+ },
+ // ElementDelimiter
+ {
+ IterativeParsingArrayInitialState, // Left bracket(push Element state)
+ IterativeParsingArrayFinishState, // Right bracket
+ IterativeParsingObjectInitialState, // Left curly bracket(push Element state)
+ IterativeParsingErrorState, // Right curly bracket
+ IterativeParsingErrorState, // Comma
+ IterativeParsingErrorState, // Colon
+ IterativeParsingElementState, // String
+ IterativeParsingElementState, // False
+ IterativeParsingElementState, // True
+ IterativeParsingElementState, // Null
+ IterativeParsingElementState // Number
+ },
+ // ArrayFinish(sink state)
+ {
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState
+ },
+ // Single Value (sink state)
+ {
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState, IterativeParsingErrorState,
+ IterativeParsingErrorState
+ }
+ }; // End of G
+
+ return static_cast<IterativeParsingState>(G[state][token]);
+ }
+
+ // Make an advance in the token stream and state based on the candidate destination state which was returned by Transit().
+ // May return a new state on state pop.
+ template <unsigned parseFlags, typename InputStream, typename Handler>
+ RAPIDJSON_FORCEINLINE IterativeParsingState Transit(IterativeParsingState src, Token token, IterativeParsingState dst, InputStream& is, Handler& handler) {
+ (void)token;
+
+ switch (dst) {
+ case IterativeParsingErrorState:
+ return dst;
+
+ case IterativeParsingObjectInitialState:
+ case IterativeParsingArrayInitialState:
+ {
+ // Push the state(Element or MemeberValue) if we are nested in another array or value of member.
+ // In this way we can get the correct state on ObjectFinish or ArrayFinish by frame pop.
+ IterativeParsingState n = src;
+ if (src == IterativeParsingArrayInitialState || src == IterativeParsingElementDelimiterState)
+ n = IterativeParsingElementState;
+ else if (src == IterativeParsingKeyValueDelimiterState)
+ n = IterativeParsingMemberValueState;
+ // Push current state.
+ *stack_.template Push<SizeType>(1) = n;
+ // Initialize and push the member/element count.
+ *stack_.template Push<SizeType>(1) = 0;
+ // Call handler
+ bool hr = (dst == IterativeParsingObjectInitialState) ? handler.StartObject() : handler.StartArray();
+ // On handler short circuits the parsing.
+ if (!hr) {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
+ return IterativeParsingErrorState;
+ }
+ else {
+ is.Take();
+ return dst;
+ }
+ }
+
+ case IterativeParsingMemberKeyState:
+ ParseString<parseFlags>(is, handler, true);
+ if (HasParseError())
+ return IterativeParsingErrorState;
+ else
+ return dst;
+
+ case IterativeParsingKeyValueDelimiterState:
+ RAPIDJSON_ASSERT(token == ColonToken);
+ is.Take();
+ return dst;
+
+ case IterativeParsingMemberValueState:
+ // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
+ ParseValue<parseFlags>(is, handler);
+ if (HasParseError()) {
+ return IterativeParsingErrorState;
+ }
+ return dst;
+
+ case IterativeParsingElementState:
+ // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
+ ParseValue<parseFlags>(is, handler);
+ if (HasParseError()) {
+ return IterativeParsingErrorState;
+ }
+ return dst;
+
+ case IterativeParsingMemberDelimiterState:
+ case IterativeParsingElementDelimiterState:
+ is.Take();
+ // Update member/element count.
+ *stack_.template Top<SizeType>() = *stack_.template Top<SizeType>() + 1;
+ return dst;
+
+ case IterativeParsingObjectFinishState:
+ {
+ // Transit from delimiter is only allowed when trailing commas are enabled
+ if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingMemberDelimiterState) {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorObjectMissName, is.Tell());
+ return IterativeParsingErrorState;
+ }
+ // Get member count.
+ SizeType c = *stack_.template Pop<SizeType>(1);
+ // If the object is not empty, count the last member.
+ if (src == IterativeParsingMemberValueState)
+ ++c;
+ // Restore the state.
+ IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
+ // Transit to Finish state if this is the topmost scope.
+ if (n == IterativeParsingStartState)
+ n = IterativeParsingFinishState;
+ // Call handler
+ bool hr = handler.EndObject(c);
+ // On handler short circuits the parsing.
+ if (!hr) {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
+ return IterativeParsingErrorState;
+ }
+ else {
+ is.Take();
+ return n;
+ }
+ }
+
+ case IterativeParsingArrayFinishState:
+ {
+ // Transit from delimiter is only allowed when trailing commas are enabled
+ if (!(parseFlags & kParseTrailingCommasFlag) && src == IterativeParsingElementDelimiterState) {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorValueInvalid, is.Tell());
+ return IterativeParsingErrorState;
+ }
+ // Get element count.
+ SizeType c = *stack_.template Pop<SizeType>(1);
+ // If the array is not empty, count the last element.
+ if (src == IterativeParsingElementState)
+ ++c;
+ // Restore the state.
+ IterativeParsingState n = static_cast<IterativeParsingState>(*stack_.template Pop<SizeType>(1));
+ // Transit to Finish state if this is the topmost scope.
+ if (n == IterativeParsingStartState)
+ n = IterativeParsingFinishState;
+ // Call handler
+ bool hr = handler.EndArray(c);
+ // On handler short circuits the parsing.
+ if (!hr) {
+ RAPIDJSON_PARSE_ERROR_NORETURN(kParseErrorTermination, is.Tell());
+ return IterativeParsingErrorState;
+ }
+ else {
+ is.Take();
+ return n;
+ }
+ }
+
+ default:
+ // This branch is for IterativeParsingValueState actually.
+ // Use `default:` rather than
+ // `case IterativeParsingValueState:` is for code coverage.
+
+ // The IterativeParsingStartState is not enumerated in this switch-case.
+ // It is impossible for that case. And it can be caught by following assertion.
+
+ // The IterativeParsingFinishState is not enumerated in this switch-case either.
+ // It is a "derivative" state which cannot triggered from Predict() directly.
+ // Therefore it cannot happen here. And it can be caught by following assertion.
+ RAPIDJSON_ASSERT(dst == IterativeParsingValueState);
+
+ // Must be non-compound value. Or it would be ObjectInitial or ArrayInitial state.
+ ParseValue<parseFlags>(is, handler);
+ if (HasParseError()) {
+ return IterativeParsingErrorState;
+ }
+ return IterativeParsingFinishState;
+ }
+ }
+
+ template <typename InputStream>
+ void HandleError(IterativeParsingState src, InputStream& is) {
+ if (HasParseError()) {
+ // Error flag has been set.
+ return;
+ }
+
+ switch (src) {
+ case IterativeParsingStartState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentEmpty, is.Tell()); return;
+ case IterativeParsingFinishState: RAPIDJSON_PARSE_ERROR(kParseErrorDocumentRootNotSingular, is.Tell()); return;
+ case IterativeParsingObjectInitialState:
+ case IterativeParsingMemberDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissName, is.Tell()); return;
+ case IterativeParsingMemberKeyState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissColon, is.Tell()); return;
+ case IterativeParsingMemberValueState: RAPIDJSON_PARSE_ERROR(kParseErrorObjectMissCommaOrCurlyBracket, is.Tell()); return;
+ case IterativeParsingKeyValueDelimiterState:
+ case IterativeParsingArrayInitialState:
+ case IterativeParsingElementDelimiterState: RAPIDJSON_PARSE_ERROR(kParseErrorValueInvalid, is.Tell()); return;
+ default: RAPIDJSON_ASSERT(src == IterativeParsingElementState); RAPIDJSON_PARSE_ERROR(kParseErrorArrayMissCommaOrSquareBracket, is.Tell()); return;
+ }
+ }
+
+ template <unsigned parseFlags, typename InputStream, typename Handler>
+ ParseResult IterativeParse(InputStream& is, Handler& handler) {
+ parseResult_.Clear();
+ ClearStackOnExit scope(*this);
+ IterativeParsingState state = IterativeParsingStartState;
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
+ while (is.Peek() != '\0') {
+ Token t = Tokenize(is.Peek());
+ IterativeParsingState n = Predict(state, t);
+ IterativeParsingState d = Transit<parseFlags>(state, t, n, is, handler);
+
+ if (d == IterativeParsingErrorState) {
+ HandleError(state, is);
+ break;
+ }
+
+ state = d;
+
+ // Do not further consume streams if a root JSON has been parsed.
+ if ((parseFlags & kParseStopWhenDoneFlag) && state == IterativeParsingFinishState)
+ break;
+
+ SkipWhitespaceAndComments<parseFlags>(is);
+ RAPIDJSON_PARSE_ERROR_EARLY_RETURN(parseResult_);
+ }
+
+ // Handle the end of file.
+ if (state != IterativeParsingFinishState)
+ HandleError(state, is);
+
+ return parseResult_;
+ }
+
+ static const size_t kDefaultStackCapacity = 256; //!< Default stack capacity in bytes for storing a single decoded string.
+ internal::Stack<StackAllocator> stack_; //!< A stack for storing decoded string temporarily during non-destructive parsing.
+ ParseResult parseResult_;
+}; // class GenericReader
+
+//! Reader with UTF8 encoding and default allocator.
+typedef GenericReader<UTF8<>, UTF8<> > Reader;
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+
+#ifdef __GNUC__
+RAPIDJSON_DIAG_POP
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_READER_H_
diff --git a/include/rapidjson/schema.h b/include/rapidjson/schema.h
new file mode 100644
index 00000000..b182aa27
--- /dev/null
+++ b/include/rapidjson/schema.h
@@ -0,0 +1,2006 @@
+// Tencent is pleased to support the open source community by making RapidJSON available->
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip-> All rights reserved->
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License-> You may obtain a copy of the License at
+//
+// http://opensource->org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied-> See the License for the
+// specific language governing permissions and limitations under the License->
+
+#ifndef RAPIDJSON_SCHEMA_H_
+#define RAPIDJSON_SCHEMA_H_
+
+#include "document.h"
+#include "pointer.h"
+#include <cmath> // abs, floor
+
+#if !defined(RAPIDJSON_SCHEMA_USE_INTERNALREGEX)
+#define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 1
+#else
+#define RAPIDJSON_SCHEMA_USE_INTERNALREGEX 0
+#endif
+
+#if !RAPIDJSON_SCHEMA_USE_INTERNALREGEX && !defined(RAPIDJSON_SCHEMA_USE_STDREGEX) && (__cplusplus >=201103L || (defined(_MSC_VER) && _MSC_VER >= 1800))
+#define RAPIDJSON_SCHEMA_USE_STDREGEX 1
+#else
+#define RAPIDJSON_SCHEMA_USE_STDREGEX 0
+#endif
+
+#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
+#include "internal/regex.h"
+#elif RAPIDJSON_SCHEMA_USE_STDREGEX
+#include <regex>
+#endif
+
+#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX || RAPIDJSON_SCHEMA_USE_STDREGEX
+#define RAPIDJSON_SCHEMA_HAS_REGEX 1
+#else
+#define RAPIDJSON_SCHEMA_HAS_REGEX 0
+#endif
+
+#ifndef RAPIDJSON_SCHEMA_VERBOSE
+#define RAPIDJSON_SCHEMA_VERBOSE 0
+#endif
+
+#if RAPIDJSON_SCHEMA_VERBOSE
+#include "stringbuffer.h"
+#endif
+
+RAPIDJSON_DIAG_PUSH
+
+#if defined(__GNUC__)
+RAPIDJSON_DIAG_OFF(effc++)
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_OFF(weak-vtables)
+RAPIDJSON_DIAG_OFF(exit-time-destructors)
+RAPIDJSON_DIAG_OFF(c++98-compat-pedantic)
+RAPIDJSON_DIAG_OFF(variadic-macros)
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_OFF(4512) // assignment operator could not be generated
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+///////////////////////////////////////////////////////////////////////////////
+// Verbose Utilities
+
+#if RAPIDJSON_SCHEMA_VERBOSE
+
+namespace internal {
+
+inline void PrintInvalidKeyword(const char* keyword) {
+ printf("Fail keyword: %s\n", keyword);
+}
+
+inline void PrintInvalidKeyword(const wchar_t* keyword) {
+ wprintf(L"Fail keyword: %ls\n", keyword);
+}
+
+inline void PrintInvalidDocument(const char* document) {
+ printf("Fail document: %s\n\n", document);
+}
+
+inline void PrintInvalidDocument(const wchar_t* document) {
+ wprintf(L"Fail document: %ls\n\n", document);
+}
+
+inline void PrintValidatorPointers(unsigned depth, const char* s, const char* d) {
+ printf("S: %*s%s\nD: %*s%s\n\n", depth * 4, " ", s, depth * 4, " ", d);
+}
+
+inline void PrintValidatorPointers(unsigned depth, const wchar_t* s, const wchar_t* d) {
+ wprintf(L"S: %*ls%ls\nD: %*ls%ls\n\n", depth * 4, L" ", s, depth * 4, L" ", d);
+}
+
+} // namespace internal
+
+#endif // RAPIDJSON_SCHEMA_VERBOSE
+
+///////////////////////////////////////////////////////////////////////////////
+// RAPIDJSON_INVALID_KEYWORD_RETURN
+
+#if RAPIDJSON_SCHEMA_VERBOSE
+#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword) internal::PrintInvalidKeyword(keyword)
+#else
+#define RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword)
+#endif
+
+#define RAPIDJSON_INVALID_KEYWORD_RETURN(keyword)\
+RAPIDJSON_MULTILINEMACRO_BEGIN\
+ context.invalidKeyword = keyword.GetString();\
+ RAPIDJSON_INVALID_KEYWORD_VERBOSE(keyword.GetString());\
+ return false;\
+RAPIDJSON_MULTILINEMACRO_END
+
+///////////////////////////////////////////////////////////////////////////////
+// Forward declarations
+
+template <typename ValueType, typename Allocator>
+class GenericSchemaDocument;
+
+namespace internal {
+
+template <typename SchemaDocumentType>
+class Schema;
+
+///////////////////////////////////////////////////////////////////////////////
+// ISchemaValidator
+
+class ISchemaValidator {
+public:
+ virtual ~ISchemaValidator() {}
+ virtual bool IsValid() const = 0;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// ISchemaStateFactory
+
+template <typename SchemaType>
+class ISchemaStateFactory {
+public:
+ virtual ~ISchemaStateFactory() {}
+ virtual ISchemaValidator* CreateSchemaValidator(const SchemaType&) = 0;
+ virtual void DestroySchemaValidator(ISchemaValidator* validator) = 0;
+ virtual void* CreateHasher() = 0;
+ virtual uint64_t GetHashCode(void* hasher) = 0;
+ virtual void DestroryHasher(void* hasher) = 0;
+ virtual void* MallocState(size_t size) = 0;
+ virtual void FreeState(void* p) = 0;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Hasher
+
+// For comparison of compound value
+template<typename Encoding, typename Allocator>
+class Hasher {
+public:
+ typedef typename Encoding::Ch Ch;
+
+ Hasher(Allocator* allocator = 0, size_t stackCapacity = kDefaultSize) : stack_(allocator, stackCapacity) {}
+
+ bool Null() { return WriteType(kNullType); }
+ bool Bool(bool b) { return WriteType(b ? kTrueType : kFalseType); }
+ bool Int(int i) { Number n; n.u.i = i; n.d = static_cast<double>(i); return WriteNumber(n); }
+ bool Uint(unsigned u) { Number n; n.u.u = u; n.d = static_cast<double>(u); return WriteNumber(n); }
+ bool Int64(int64_t i) { Number n; n.u.i = i; n.d = static_cast<double>(i); return WriteNumber(n); }
+ bool Uint64(uint64_t u) { Number n; n.u.u = u; n.d = static_cast<double>(u); return WriteNumber(n); }
+ bool Double(double d) {
+ Number n;
+ if (d < 0) n.u.i = static_cast<int64_t>(d);
+ else n.u.u = static_cast<uint64_t>(d);
+ n.d = d;
+ return WriteNumber(n);
+ }
+
+ bool RawNumber(const Ch* str, SizeType len, bool) {
+ WriteBuffer(kNumberType, str, len * sizeof(Ch));
+ return true;
+ }
+
+ bool String(const Ch* str, SizeType len, bool) {
+ WriteBuffer(kStringType, str, len * sizeof(Ch));
+ return true;
+ }
+
+ bool StartObject() { return true; }
+ bool Key(const Ch* str, SizeType len, bool copy) { return String(str, len, copy); }
+ bool EndObject(SizeType memberCount) {
+ uint64_t h = Hash(0, kObjectType);
+ uint64_t* kv = stack_.template Pop<uint64_t>(memberCount * 2);
+ for (SizeType i = 0; i < memberCount; i++)
+ h ^= Hash(kv[i * 2], kv[i * 2 + 1]); // Use xor to achieve member order insensitive
+ *stack_.template Push<uint64_t>() = h;
+ return true;
+ }
+
+ bool StartArray() { return true; }
+ bool EndArray(SizeType elementCount) {
+ uint64_t h = Hash(0, kArrayType);
+ uint64_t* e = stack_.template Pop<uint64_t>(elementCount);
+ for (SizeType i = 0; i < elementCount; i++)
+ h = Hash(h, e[i]); // Use hash to achieve element order sensitive
+ *stack_.template Push<uint64_t>() = h;
+ return true;
+ }
+
+ bool IsValid() const { return stack_.GetSize() == sizeof(uint64_t); }
+
+ uint64_t GetHashCode() const {
+ RAPIDJSON_ASSERT(IsValid());
+ return *stack_.template Top<uint64_t>();
+ }
+
+private:
+ static const size_t kDefaultSize = 256;
+ struct Number {
+ union U {
+ uint64_t u;
+ int64_t i;
+ }u;
+ double d;
+ };
+
+ bool WriteType(Type type) { return WriteBuffer(type, 0, 0); }
+
+ bool WriteNumber(const Number& n) { return WriteBuffer(kNumberType, &n, sizeof(n)); }
+
+ bool WriteBuffer(Type type, const void* data, size_t len) {
+ // FNV-1a from http://isthe.com/chongo/tech/comp/fnv/
+ uint64_t h = Hash(RAPIDJSON_UINT64_C2(0x84222325, 0xcbf29ce4), type);
+ const unsigned char* d = static_cast<const unsigned char*>(data);
+ for (size_t i = 0; i < len; i++)
+ h = Hash(h, d[i]);
+ *stack_.template Push<uint64_t>() = h;
+ return true;
+ }
+
+ static uint64_t Hash(uint64_t h, uint64_t d) {
+ static const uint64_t kPrime = RAPIDJSON_UINT64_C2(0x00000100, 0x000001b3);
+ h ^= d;
+ h *= kPrime;
+ return h;
+ }
+
+ Stack<Allocator> stack_;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// SchemaValidationContext
+
+template <typename SchemaDocumentType>
+struct SchemaValidationContext {
+ typedef Schema<SchemaDocumentType> SchemaType;
+ typedef ISchemaStateFactory<SchemaType> SchemaValidatorFactoryType;
+ typedef typename SchemaType::ValueType ValueType;
+ typedef typename ValueType::Ch Ch;
+
+ enum PatternValidatorType {
+ kPatternValidatorOnly,
+ kPatternValidatorWithProperty,
+ kPatternValidatorWithAdditionalProperty
+ };
+
+ SchemaValidationContext(SchemaValidatorFactoryType& f, const SchemaType* s) :
+ factory(f),
+ schema(s),
+ valueSchema(),
+ invalidKeyword(),
+ hasher(),
+ arrayElementHashCodes(),
+ validators(),
+ validatorCount(),
+ patternPropertiesValidators(),
+ patternPropertiesValidatorCount(),
+ patternPropertiesSchemas(),
+ patternPropertiesSchemaCount(),
+ valuePatternValidatorType(kPatternValidatorOnly),
+ propertyExist(),
+ inArray(false),
+ valueUniqueness(false),
+ arrayUniqueness(false)
+ {
+ }
+
+ ~SchemaValidationContext() {
+ if (hasher)
+ factory.DestroryHasher(hasher);
+ if (validators) {
+ for (SizeType i = 0; i < validatorCount; i++)
+ factory.DestroySchemaValidator(validators[i]);
+ factory.FreeState(validators);
+ }
+ if (patternPropertiesValidators) {
+ for (SizeType i = 0; i < patternPropertiesValidatorCount; i++)
+ factory.DestroySchemaValidator(patternPropertiesValidators[i]);
+ factory.FreeState(patternPropertiesValidators);
+ }
+ if (patternPropertiesSchemas)
+ factory.FreeState(patternPropertiesSchemas);
+ if (propertyExist)
+ factory.FreeState(propertyExist);
+ }
+
+ SchemaValidatorFactoryType& factory;
+ const SchemaType* schema;
+ const SchemaType* valueSchema;
+ const Ch* invalidKeyword;
+ void* hasher; // Only validator access
+ void* arrayElementHashCodes; // Only validator access this
+ ISchemaValidator** validators;
+ SizeType validatorCount;
+ ISchemaValidator** patternPropertiesValidators;
+ SizeType patternPropertiesValidatorCount;
+ const SchemaType** patternPropertiesSchemas;
+ SizeType patternPropertiesSchemaCount;
+ PatternValidatorType valuePatternValidatorType;
+ PatternValidatorType objectPatternValidatorType;
+ SizeType arrayElementIndex;
+ bool* propertyExist;
+ bool inArray;
+ bool valueUniqueness;
+ bool arrayUniqueness;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// Schema
+
+template <typename SchemaDocumentType>
+class Schema {
+public:
+ typedef typename SchemaDocumentType::ValueType ValueType;
+ typedef typename SchemaDocumentType::AllocatorType AllocatorType;
+ typedef typename SchemaDocumentType::PointerType PointerType;
+ typedef typename ValueType::EncodingType EncodingType;
+ typedef typename EncodingType::Ch Ch;
+ typedef SchemaValidationContext<SchemaDocumentType> Context;
+ typedef Schema<SchemaDocumentType> SchemaType;
+ typedef GenericValue<EncodingType, AllocatorType> SValue;
+ friend class GenericSchemaDocument<ValueType, AllocatorType>;
+
+ Schema(SchemaDocumentType* schemaDocument, const PointerType& p, const ValueType& value, const ValueType& document, AllocatorType* allocator) :
+ allocator_(allocator),
+ enum_(),
+ enumCount_(),
+ not_(),
+ type_((1 << kTotalSchemaType) - 1), // typeless
+ validatorCount_(),
+ properties_(),
+ additionalPropertiesSchema_(),
+ patternProperties_(),
+ patternPropertyCount_(),
+ propertyCount_(),
+ minProperties_(),
+ maxProperties_(SizeType(~0)),
+ additionalProperties_(true),
+ hasDependencies_(),
+ hasRequired_(),
+ hasSchemaDependencies_(),
+ additionalItemsSchema_(),
+ itemsList_(),
+ itemsTuple_(),
+ itemsTupleCount_(),
+ minItems_(),
+ maxItems_(SizeType(~0)),
+ additionalItems_(true),
+ uniqueItems_(false),
+ pattern_(),
+ minLength_(0),
+ maxLength_(~SizeType(0)),
+ exclusiveMinimum_(false),
+ exclusiveMaximum_(false)
+ {
+ typedef typename SchemaDocumentType::ValueType ValueType;
+ typedef typename ValueType::ConstValueIterator ConstValueIterator;
+ typedef typename ValueType::ConstMemberIterator ConstMemberIterator;
+
+ if (!value.IsObject())
+ return;
+
+ if (const ValueType* v = GetMember(value, GetTypeString())) {
+ type_ = 0;
+ if (v->IsString())
+ AddType(*v);
+ else if (v->IsArray())
+ for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr)
+ AddType(*itr);
+ }
+
+ if (const ValueType* v = GetMember(value, GetEnumString()))
+ if (v->IsArray() && v->Size() > 0) {
+ enum_ = static_cast<uint64_t*>(allocator_->Malloc(sizeof(uint64_t) * v->Size()));
+ for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr) {
+ typedef Hasher<EncodingType, MemoryPoolAllocator<> > EnumHasherType;
+ char buffer[256 + 24];
+ MemoryPoolAllocator<> hasherAllocator(buffer, sizeof(buffer));
+ EnumHasherType h(&hasherAllocator, 256);
+ itr->Accept(h);
+ enum_[enumCount_++] = h.GetHashCode();
+ }
+ }
+
+ if (schemaDocument) {
+ AssignIfExist(allOf_, *schemaDocument, p, value, GetAllOfString(), document);
+ AssignIfExist(anyOf_, *schemaDocument, p, value, GetAnyOfString(), document);
+ AssignIfExist(oneOf_, *schemaDocument, p, value, GetOneOfString(), document);
+ }
+
+ if (const ValueType* v = GetMember(value, GetNotString())) {
+ schemaDocument->CreateSchema(&not_, p.Append(GetNotString(), allocator_), *v, document);
+ notValidatorIndex_ = validatorCount_;
+ validatorCount_++;
+ }
+
+ // Object
+
+ const ValueType* properties = GetMember(value, GetPropertiesString());
+ const ValueType* required = GetMember(value, GetRequiredString());
+ const ValueType* dependencies = GetMember(value, GetDependenciesString());
+ {
+ // Gather properties from properties/required/dependencies
+ SValue allProperties(kArrayType);
+
+ if (properties && properties->IsObject())
+ for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr)
+ AddUniqueElement(allProperties, itr->name);
+
+ if (required && required->IsArray())
+ for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr)
+ if (itr->IsString())
+ AddUniqueElement(allProperties, *itr);
+
+ if (dependencies && dependencies->IsObject())
+ for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) {
+ AddUniqueElement(allProperties, itr->name);
+ if (itr->value.IsArray())
+ for (ConstValueIterator i = itr->value.Begin(); i != itr->value.End(); ++i)
+ if (i->IsString())
+ AddUniqueElement(allProperties, *i);
+ }
+
+ if (allProperties.Size() > 0) {
+ propertyCount_ = allProperties.Size();
+ properties_ = static_cast<Property*>(allocator_->Malloc(sizeof(Property) * propertyCount_));
+ for (SizeType i = 0; i < propertyCount_; i++) {
+ new (&properties_[i]) Property();
+ properties_[i].name = allProperties[i];
+ properties_[i].schema = GetTypeless();
+ }
+ }
+ }
+
+ if (properties && properties->IsObject()) {
+ PointerType q = p.Append(GetPropertiesString(), allocator_);
+ for (ConstMemberIterator itr = properties->MemberBegin(); itr != properties->MemberEnd(); ++itr) {
+ SizeType index;
+ if (FindPropertyIndex(itr->name, &index))
+ schemaDocument->CreateSchema(&properties_[index].schema, q.Append(itr->name, allocator_), itr->value, document);
+ }
+ }
+
+ if (const ValueType* v = GetMember(value, GetPatternPropertiesString())) {
+ PointerType q = p.Append(GetPatternPropertiesString(), allocator_);
+ patternProperties_ = static_cast<PatternProperty*>(allocator_->Malloc(sizeof(PatternProperty) * v->MemberCount()));
+ patternPropertyCount_ = 0;
+
+ for (ConstMemberIterator itr = v->MemberBegin(); itr != v->MemberEnd(); ++itr) {
+ new (&patternProperties_[patternPropertyCount_]) PatternProperty();
+ patternProperties_[patternPropertyCount_].pattern = CreatePattern(itr->name);
+ schemaDocument->CreateSchema(&patternProperties_[patternPropertyCount_].schema, q.Append(itr->name, allocator_), itr->value, document);
+ patternPropertyCount_++;
+ }
+ }
+
+ if (required && required->IsArray())
+ for (ConstValueIterator itr = required->Begin(); itr != required->End(); ++itr)
+ if (itr->IsString()) {
+ SizeType index;
+ if (FindPropertyIndex(*itr, &index)) {
+ properties_[index].required = true;
+ hasRequired_ = true;
+ }
+ }
+
+ if (dependencies && dependencies->IsObject()) {
+ PointerType q = p.Append(GetDependenciesString(), allocator_);
+ hasDependencies_ = true;
+ for (ConstMemberIterator itr = dependencies->MemberBegin(); itr != dependencies->MemberEnd(); ++itr) {
+ SizeType sourceIndex;
+ if (FindPropertyIndex(itr->name, &sourceIndex)) {
+ if (itr->value.IsArray()) {
+ properties_[sourceIndex].dependencies = static_cast<bool*>(allocator_->Malloc(sizeof(bool) * propertyCount_));
+ std::memset(properties_[sourceIndex].dependencies, 0, sizeof(bool)* propertyCount_);
+ for (ConstValueIterator targetItr = itr->value.Begin(); targetItr != itr->value.End(); ++targetItr) {
+ SizeType targetIndex;
+ if (FindPropertyIndex(*targetItr, &targetIndex))
+ properties_[sourceIndex].dependencies[targetIndex] = true;
+ }
+ }
+ else if (itr->value.IsObject()) {
+ hasSchemaDependencies_ = true;
+ schemaDocument->CreateSchema(&properties_[sourceIndex].dependenciesSchema, q.Append(itr->name, allocator_), itr->value, document);
+ properties_[sourceIndex].dependenciesValidatorIndex = validatorCount_;
+ validatorCount_++;
+ }
+ }
+ }
+ }
+
+ if (const ValueType* v = GetMember(value, GetAdditionalPropertiesString())) {
+ if (v->IsBool())
+ additionalProperties_ = v->GetBool();
+ else if (v->IsObject())
+ schemaDocument->CreateSchema(&additionalPropertiesSchema_, p.Append(GetAdditionalPropertiesString(), allocator_), *v, document);
+ }
+
+ AssignIfExist(minProperties_, value, GetMinPropertiesString());
+ AssignIfExist(maxProperties_, value, GetMaxPropertiesString());
+
+ // Array
+ if (const ValueType* v = GetMember(value, GetItemsString())) {
+ PointerType q = p.Append(GetItemsString(), allocator_);
+ if (v->IsObject()) // List validation
+ schemaDocument->CreateSchema(&itemsList_, q, *v, document);
+ else if (v->IsArray()) { // Tuple validation
+ itemsTuple_ = static_cast<const Schema**>(allocator_->Malloc(sizeof(const Schema*) * v->Size()));
+ SizeType index = 0;
+ for (ConstValueIterator itr = v->Begin(); itr != v->End(); ++itr, index++)
+ schemaDocument->CreateSchema(&itemsTuple_[itemsTupleCount_++], q.Append(index, allocator_), *itr, document);
+ }
+ }
+
+ AssignIfExist(minItems_, value, GetMinItemsString());
+ AssignIfExist(maxItems_, value, GetMaxItemsString());
+
+ if (const ValueType* v = GetMember(value, GetAdditionalItemsString())) {
+ if (v->IsBool())
+ additionalItems_ = v->GetBool();
+ else if (v->IsObject())
+ schemaDocument->CreateSchema(&additionalItemsSchema_, p.Append(GetAdditionalItemsString(), allocator_), *v, document);
+ }
+
+ AssignIfExist(uniqueItems_, value, GetUniqueItemsString());
+
+ // String
+ AssignIfExist(minLength_, value, GetMinLengthString());
+ AssignIfExist(maxLength_, value, GetMaxLengthString());
+
+ if (const ValueType* v = GetMember(value, GetPatternString()))
+ pattern_ = CreatePattern(*v);
+
+ // Number
+ if (const ValueType* v = GetMember(value, GetMinimumString()))
+ if (v->IsNumber())
+ minimum_.CopyFrom(*v, *allocator_);
+
+ if (const ValueType* v = GetMember(value, GetMaximumString()))
+ if (v->IsNumber())
+ maximum_.CopyFrom(*v, *allocator_);
+
+ AssignIfExist(exclusiveMinimum_, value, GetExclusiveMinimumString());
+ AssignIfExist(exclusiveMaximum_, value, GetExclusiveMaximumString());
+
+ if (const ValueType* v = GetMember(value, GetMultipleOfString()))
+ if (v->IsNumber() && v->GetDouble() > 0.0)
+ multipleOf_.CopyFrom(*v, *allocator_);
+ }
+
+ ~Schema() {
+ if (allocator_) {
+ allocator_->Free(enum_);
+ }
+ if (properties_) {
+ for (SizeType i = 0; i < propertyCount_; i++)
+ properties_[i].~Property();
+ AllocatorType::Free(properties_);
+ }
+ if (patternProperties_) {
+ for (SizeType i = 0; i < patternPropertyCount_; i++)
+ patternProperties_[i].~PatternProperty();
+ AllocatorType::Free(patternProperties_);
+ }
+ AllocatorType::Free(itemsTuple_);
+#if RAPIDJSON_SCHEMA_HAS_REGEX
+ if (pattern_) {
+ pattern_->~RegexType();
+ allocator_->Free(pattern_);
+ }
+#endif
+ }
+
+ bool BeginValue(Context& context) const {
+ if (context.inArray) {
+ if (uniqueItems_)
+ context.valueUniqueness = true;
+
+ if (itemsList_)
+ context.valueSchema = itemsList_;
+ else if (itemsTuple_) {
+ if (context.arrayElementIndex < itemsTupleCount_)
+ context.valueSchema = itemsTuple_[context.arrayElementIndex];
+ else if (additionalItemsSchema_)
+ context.valueSchema = additionalItemsSchema_;
+ else if (additionalItems_)
+ context.valueSchema = GetTypeless();
+ else
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetItemsString());
+ }
+ else
+ context.valueSchema = GetTypeless();
+
+ context.arrayElementIndex++;
+ }
+ return true;
+ }
+
+ RAPIDJSON_FORCEINLINE bool EndValue(Context& context) const {
+ if (context.patternPropertiesValidatorCount > 0) {
+ bool otherValid = false;
+ SizeType count = context.patternPropertiesValidatorCount;
+ if (context.objectPatternValidatorType != Context::kPatternValidatorOnly)
+ otherValid = context.patternPropertiesValidators[--count]->IsValid();
+
+ bool patternValid = true;
+ for (SizeType i = 0; i < count; i++)
+ if (!context.patternPropertiesValidators[i]->IsValid()) {
+ patternValid = false;
+ break;
+ }
+
+ if (context.objectPatternValidatorType == Context::kPatternValidatorOnly) {
+ if (!patternValid)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString());
+ }
+ else if (context.objectPatternValidatorType == Context::kPatternValidatorWithProperty) {
+ if (!patternValid || !otherValid)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString());
+ }
+ else if (!patternValid && !otherValid) // kPatternValidatorWithAdditionalProperty)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternPropertiesString());
+ }
+
+ if (enum_) {
+ const uint64_t h = context.factory.GetHashCode(context.hasher);
+ for (SizeType i = 0; i < enumCount_; i++)
+ if (enum_[i] == h)
+ goto foundEnum;
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetEnumString());
+ foundEnum:;
+ }
+
+ if (allOf_.schemas)
+ for (SizeType i = allOf_.begin; i < allOf_.begin + allOf_.count; i++)
+ if (!context.validators[i]->IsValid())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetAllOfString());
+
+ if (anyOf_.schemas) {
+ for (SizeType i = anyOf_.begin; i < anyOf_.begin + anyOf_.count; i++)
+ if (context.validators[i]->IsValid())
+ goto foundAny;
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetAnyOfString());
+ foundAny:;
+ }
+
+ if (oneOf_.schemas) {
+ bool oneValid = false;
+ for (SizeType i = oneOf_.begin; i < oneOf_.begin + oneOf_.count; i++)
+ if (context.validators[i]->IsValid()) {
+ if (oneValid)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString());
+ else
+ oneValid = true;
+ }
+ if (!oneValid)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetOneOfString());
+ }
+
+ if (not_ && context.validators[notValidatorIndex_]->IsValid())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetNotString());
+
+ return true;
+ }
+
+ bool Null(Context& context) const {
+ if (!(type_ & (1 << kNullSchemaType)))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+ return CreateParallelValidator(context);
+ }
+
+ bool Bool(Context& context, bool) const {
+ if (!(type_ & (1 << kBooleanSchemaType)))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+ return CreateParallelValidator(context);
+ }
+
+ bool Int(Context& context, int i) const {
+ if (!CheckInt(context, i))
+ return false;
+ return CreateParallelValidator(context);
+ }
+
+ bool Uint(Context& context, unsigned u) const {
+ if (!CheckUint(context, u))
+ return false;
+ return CreateParallelValidator(context);
+ }
+
+ bool Int64(Context& context, int64_t i) const {
+ if (!CheckInt(context, i))
+ return false;
+ return CreateParallelValidator(context);
+ }
+
+ bool Uint64(Context& context, uint64_t u) const {
+ if (!CheckUint(context, u))
+ return false;
+ return CreateParallelValidator(context);
+ }
+
+ bool Double(Context& context, double d) const {
+ if (!(type_ & (1 << kNumberSchemaType)))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+
+ if (!minimum_.IsNull() && !CheckDoubleMinimum(context, d))
+ return false;
+
+ if (!maximum_.IsNull() && !CheckDoubleMaximum(context, d))
+ return false;
+
+ if (!multipleOf_.IsNull() && !CheckDoubleMultipleOf(context, d))
+ return false;
+
+ return CreateParallelValidator(context);
+ }
+
+ bool String(Context& context, const Ch* str, SizeType length, bool) const {
+ if (!(type_ & (1 << kStringSchemaType)))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+
+ if (minLength_ != 0 || maxLength_ != SizeType(~0)) {
+ SizeType count;
+ if (internal::CountStringCodePoint<EncodingType>(str, length, &count)) {
+ if (count < minLength_)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinLengthString());
+ if (count > maxLength_)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxLengthString());
+ }
+ }
+
+ if (pattern_ && !IsPatternMatch(pattern_, str, length))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetPatternString());
+
+ return CreateParallelValidator(context);
+ }
+
+ bool StartObject(Context& context) const {
+ if (!(type_ & (1 << kObjectSchemaType)))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+
+ if (hasDependencies_ || hasRequired_) {
+ context.propertyExist = static_cast<bool*>(context.factory.MallocState(sizeof(bool) * propertyCount_));
+ std::memset(context.propertyExist, 0, sizeof(bool) * propertyCount_);
+ }
+
+ if (patternProperties_) { // pre-allocate schema array
+ SizeType count = patternPropertyCount_ + 1; // extra for valuePatternValidatorType
+ context.patternPropertiesSchemas = static_cast<const SchemaType**>(context.factory.MallocState(sizeof(const SchemaType*) * count));
+ context.patternPropertiesSchemaCount = 0;
+ std::memset(context.patternPropertiesSchemas, 0, sizeof(SchemaType*) * count);
+ }
+
+ return CreateParallelValidator(context);
+ }
+
+ bool Key(Context& context, const Ch* str, SizeType len, bool) const {
+ if (patternProperties_) {
+ context.patternPropertiesSchemaCount = 0;
+ for (SizeType i = 0; i < patternPropertyCount_; i++)
+ if (patternProperties_[i].pattern && IsPatternMatch(patternProperties_[i].pattern, str, len))
+ context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = patternProperties_[i].schema;
+ }
+
+ SizeType index;
+ if (FindPropertyIndex(ValueType(str, len).Move(), &index)) {
+ if (context.patternPropertiesSchemaCount > 0) {
+ context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = properties_[index].schema;
+ context.valueSchema = GetTypeless();
+ context.valuePatternValidatorType = Context::kPatternValidatorWithProperty;
+ }
+ else
+ context.valueSchema = properties_[index].schema;
+
+ if (context.propertyExist)
+ context.propertyExist[index] = true;
+
+ return true;
+ }
+
+ if (additionalPropertiesSchema_) {
+ if (additionalPropertiesSchema_ && context.patternPropertiesSchemaCount > 0) {
+ context.patternPropertiesSchemas[context.patternPropertiesSchemaCount++] = additionalPropertiesSchema_;
+ context.valueSchema = GetTypeless();
+ context.valuePatternValidatorType = Context::kPatternValidatorWithAdditionalProperty;
+ }
+ else
+ context.valueSchema = additionalPropertiesSchema_;
+ return true;
+ }
+ else if (additionalProperties_) {
+ context.valueSchema = GetTypeless();
+ return true;
+ }
+
+ if (context.patternPropertiesSchemaCount == 0) // patternProperties are not additional properties
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetAdditionalPropertiesString());
+
+ return true;
+ }
+
+ bool EndObject(Context& context, SizeType memberCount) const {
+ if (hasRequired_)
+ for (SizeType index = 0; index < propertyCount_; index++)
+ if (properties_[index].required)
+ if (!context.propertyExist[index])
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetRequiredString());
+
+ if (memberCount < minProperties_)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinPropertiesString());
+
+ if (memberCount > maxProperties_)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxPropertiesString());
+
+ if (hasDependencies_) {
+ for (SizeType sourceIndex = 0; sourceIndex < propertyCount_; sourceIndex++)
+ if (context.propertyExist[sourceIndex]) {
+ if (properties_[sourceIndex].dependencies) {
+ for (SizeType targetIndex = 0; targetIndex < propertyCount_; targetIndex++)
+ if (properties_[sourceIndex].dependencies[targetIndex] && !context.propertyExist[targetIndex])
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString());
+ }
+ else if (properties_[sourceIndex].dependenciesSchema)
+ if (!context.validators[properties_[sourceIndex].dependenciesValidatorIndex]->IsValid())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetDependenciesString());
+ }
+ }
+
+ return true;
+ }
+
+ bool StartArray(Context& context) const {
+ if (!(type_ & (1 << kArraySchemaType)))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+
+ context.arrayElementIndex = 0;
+ context.inArray = true;
+
+ return CreateParallelValidator(context);
+ }
+
+ bool EndArray(Context& context, SizeType elementCount) const {
+ context.inArray = false;
+
+ if (elementCount < minItems_)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinItemsString());
+
+ if (elementCount > maxItems_)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaxItemsString());
+
+ return true;
+ }
+
+ // Generate functions for string literal according to Ch
+#define RAPIDJSON_STRING_(name, ...) \
+ static const ValueType& Get##name##String() {\
+ static const Ch s[] = { __VA_ARGS__, '\0' };\
+ static const ValueType v(s, sizeof(s) / sizeof(Ch) - 1);\
+ return v;\
+ }
+
+ RAPIDJSON_STRING_(Null, 'n', 'u', 'l', 'l')
+ RAPIDJSON_STRING_(Boolean, 'b', 'o', 'o', 'l', 'e', 'a', 'n')
+ RAPIDJSON_STRING_(Object, 'o', 'b', 'j', 'e', 'c', 't')
+ RAPIDJSON_STRING_(Array, 'a', 'r', 'r', 'a', 'y')
+ RAPIDJSON_STRING_(String, 's', 't', 'r', 'i', 'n', 'g')
+ RAPIDJSON_STRING_(Number, 'n', 'u', 'm', 'b', 'e', 'r')
+ RAPIDJSON_STRING_(Integer, 'i', 'n', 't', 'e', 'g', 'e', 'r')
+ RAPIDJSON_STRING_(Type, 't', 'y', 'p', 'e')
+ RAPIDJSON_STRING_(Enum, 'e', 'n', 'u', 'm')
+ RAPIDJSON_STRING_(AllOf, 'a', 'l', 'l', 'O', 'f')
+ RAPIDJSON_STRING_(AnyOf, 'a', 'n', 'y', 'O', 'f')
+ RAPIDJSON_STRING_(OneOf, 'o', 'n', 'e', 'O', 'f')
+ RAPIDJSON_STRING_(Not, 'n', 'o', 't')
+ RAPIDJSON_STRING_(Properties, 'p', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
+ RAPIDJSON_STRING_(Required, 'r', 'e', 'q', 'u', 'i', 'r', 'e', 'd')
+ RAPIDJSON_STRING_(Dependencies, 'd', 'e', 'p', 'e', 'n', 'd', 'e', 'n', 'c', 'i', 'e', 's')
+ RAPIDJSON_STRING_(PatternProperties, 'p', 'a', 't', 't', 'e', 'r', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
+ RAPIDJSON_STRING_(AdditionalProperties, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
+ RAPIDJSON_STRING_(MinProperties, 'm', 'i', 'n', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
+ RAPIDJSON_STRING_(MaxProperties, 'm', 'a', 'x', 'P', 'r', 'o', 'p', 'e', 'r', 't', 'i', 'e', 's')
+ RAPIDJSON_STRING_(Items, 'i', 't', 'e', 'm', 's')
+ RAPIDJSON_STRING_(MinItems, 'm', 'i', 'n', 'I', 't', 'e', 'm', 's')
+ RAPIDJSON_STRING_(MaxItems, 'm', 'a', 'x', 'I', 't', 'e', 'm', 's')
+ RAPIDJSON_STRING_(AdditionalItems, 'a', 'd', 'd', 'i', 't', 'i', 'o', 'n', 'a', 'l', 'I', 't', 'e', 'm', 's')
+ RAPIDJSON_STRING_(UniqueItems, 'u', 'n', 'i', 'q', 'u', 'e', 'I', 't', 'e', 'm', 's')
+ RAPIDJSON_STRING_(MinLength, 'm', 'i', 'n', 'L', 'e', 'n', 'g', 't', 'h')
+ RAPIDJSON_STRING_(MaxLength, 'm', 'a', 'x', 'L', 'e', 'n', 'g', 't', 'h')
+ RAPIDJSON_STRING_(Pattern, 'p', 'a', 't', 't', 'e', 'r', 'n')
+ RAPIDJSON_STRING_(Minimum, 'm', 'i', 'n', 'i', 'm', 'u', 'm')
+ RAPIDJSON_STRING_(Maximum, 'm', 'a', 'x', 'i', 'm', 'u', 'm')
+ RAPIDJSON_STRING_(ExclusiveMinimum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'i', 'n', 'i', 'm', 'u', 'm')
+ RAPIDJSON_STRING_(ExclusiveMaximum, 'e', 'x', 'c', 'l', 'u', 's', 'i', 'v', 'e', 'M', 'a', 'x', 'i', 'm', 'u', 'm')
+ RAPIDJSON_STRING_(MultipleOf, 'm', 'u', 'l', 't', 'i', 'p', 'l', 'e', 'O', 'f')
+
+#undef RAPIDJSON_STRING_
+
+private:
+ enum SchemaValueType {
+ kNullSchemaType,
+ kBooleanSchemaType,
+ kObjectSchemaType,
+ kArraySchemaType,
+ kStringSchemaType,
+ kNumberSchemaType,
+ kIntegerSchemaType,
+ kTotalSchemaType
+ };
+
+#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
+ typedef internal::GenericRegex<EncodingType> RegexType;
+#elif RAPIDJSON_SCHEMA_USE_STDREGEX
+ typedef std::basic_regex<Ch> RegexType;
+#else
+ typedef char RegexType;
+#endif
+
+ struct SchemaArray {
+ SchemaArray() : schemas(), count() {}
+ ~SchemaArray() { AllocatorType::Free(schemas); }
+ const SchemaType** schemas;
+ SizeType begin; // begin index of context.validators
+ SizeType count;
+ };
+
+ static const SchemaType* GetTypeless() {
+ static SchemaType typeless(0, PointerType(), ValueType(kObjectType).Move(), ValueType(kObjectType).Move(), 0);
+ return &typeless;
+ }
+
+ template <typename V1, typename V2>
+ void AddUniqueElement(V1& a, const V2& v) {
+ for (typename V1::ConstValueIterator itr = a.Begin(); itr != a.End(); ++itr)
+ if (*itr == v)
+ return;
+ V1 c(v, *allocator_);
+ a.PushBack(c, *allocator_);
+ }
+
+ static const ValueType* GetMember(const ValueType& value, const ValueType& name) {
+ typename ValueType::ConstMemberIterator itr = value.FindMember(name);
+ return itr != value.MemberEnd() ? &(itr->value) : 0;
+ }
+
+ static void AssignIfExist(bool& out, const ValueType& value, const ValueType& name) {
+ if (const ValueType* v = GetMember(value, name))
+ if (v->IsBool())
+ out = v->GetBool();
+ }
+
+ static void AssignIfExist(SizeType& out, const ValueType& value, const ValueType& name) {
+ if (const ValueType* v = GetMember(value, name))
+ if (v->IsUint64() && v->GetUint64() <= SizeType(~0))
+ out = static_cast<SizeType>(v->GetUint64());
+ }
+
+ void AssignIfExist(SchemaArray& out, SchemaDocumentType& schemaDocument, const PointerType& p, const ValueType& value, const ValueType& name, const ValueType& document) {
+ if (const ValueType* v = GetMember(value, name)) {
+ if (v->IsArray() && v->Size() > 0) {
+ PointerType q = p.Append(name, allocator_);
+ out.count = v->Size();
+ out.schemas = static_cast<const Schema**>(allocator_->Malloc(out.count * sizeof(const Schema*)));
+ memset(out.schemas, 0, sizeof(Schema*)* out.count);
+ for (SizeType i = 0; i < out.count; i++)
+ schemaDocument.CreateSchema(&out.schemas[i], q.Append(i, allocator_), (*v)[i], document);
+ out.begin = validatorCount_;
+ validatorCount_ += out.count;
+ }
+ }
+ }
+
+#if RAPIDJSON_SCHEMA_USE_INTERNALREGEX
+ template <typename ValueType>
+ RegexType* CreatePattern(const ValueType& value) {
+ if (value.IsString()) {
+ RegexType* r = new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString());
+ if (!r->IsValid()) {
+ r->~RegexType();
+ AllocatorType::Free(r);
+ r = 0;
+ }
+ return r;
+ }
+ return 0;
+ }
+
+ static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType) {
+ return pattern->Search(str);
+ }
+#elif RAPIDJSON_SCHEMA_USE_STDREGEX
+ template <typename ValueType>
+ RegexType* CreatePattern(const ValueType& value) {
+ if (value.IsString())
+ try {
+ return new (allocator_->Malloc(sizeof(RegexType))) RegexType(value.GetString(), std::size_t(value.GetStringLength()), std::regex_constants::ECMAScript);
+ }
+ catch (const std::regex_error&) {
+ }
+ return 0;
+ }
+
+ static bool IsPatternMatch(const RegexType* pattern, const Ch *str, SizeType length) {
+ std::match_results<const Ch*> r;
+ return std::regex_search(str, str + length, r, *pattern);
+ }
+#else
+ template <typename ValueType>
+ RegexType* CreatePattern(const ValueType&) { return 0; }
+
+ static bool IsPatternMatch(const RegexType*, const Ch *, SizeType) { return true; }
+#endif // RAPIDJSON_SCHEMA_USE_STDREGEX
+
+ void AddType(const ValueType& type) {
+ if (type == GetNullString() ) type_ |= 1 << kNullSchemaType;
+ else if (type == GetBooleanString()) type_ |= 1 << kBooleanSchemaType;
+ else if (type == GetObjectString() ) type_ |= 1 << kObjectSchemaType;
+ else if (type == GetArrayString() ) type_ |= 1 << kArraySchemaType;
+ else if (type == GetStringString() ) type_ |= 1 << kStringSchemaType;
+ else if (type == GetIntegerString()) type_ |= 1 << kIntegerSchemaType;
+ else if (type == GetNumberString() ) type_ |= (1 << kNumberSchemaType) | (1 << kIntegerSchemaType);
+ }
+
+ bool CreateParallelValidator(Context& context) const {
+ if (enum_ || context.arrayUniqueness)
+ context.hasher = context.factory.CreateHasher();
+
+ if (validatorCount_) {
+ RAPIDJSON_ASSERT(context.validators == 0);
+ context.validators = static_cast<ISchemaValidator**>(context.factory.MallocState(sizeof(ISchemaValidator*) * validatorCount_));
+ context.validatorCount = validatorCount_;
+
+ if (allOf_.schemas)
+ CreateSchemaValidators(context, allOf_);
+
+ if (anyOf_.schemas)
+ CreateSchemaValidators(context, anyOf_);
+
+ if (oneOf_.schemas)
+ CreateSchemaValidators(context, oneOf_);
+
+ if (not_)
+ context.validators[notValidatorIndex_] = context.factory.CreateSchemaValidator(*not_);
+
+ if (hasSchemaDependencies_) {
+ for (SizeType i = 0; i < propertyCount_; i++)
+ if (properties_[i].dependenciesSchema)
+ context.validators[properties_[i].dependenciesValidatorIndex] = context.factory.CreateSchemaValidator(*properties_[i].dependenciesSchema);
+ }
+ }
+
+ return true;
+ }
+
+ void CreateSchemaValidators(Context& context, const SchemaArray& schemas) const {
+ for (SizeType i = 0; i < schemas.count; i++)
+ context.validators[schemas.begin + i] = context.factory.CreateSchemaValidator(*schemas.schemas[i]);
+ }
+
+ // O(n)
+ bool FindPropertyIndex(const ValueType& name, SizeType* outIndex) const {
+ SizeType len = name.GetStringLength();
+ const Ch* str = name.GetString();
+ for (SizeType index = 0; index < propertyCount_; index++)
+ if (properties_[index].name.GetStringLength() == len &&
+ (std::memcmp(properties_[index].name.GetString(), str, sizeof(Ch) * len) == 0))
+ {
+ *outIndex = index;
+ return true;
+ }
+ return false;
+ }
+
+ bool CheckInt(Context& context, int64_t i) const {
+ if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType))))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+
+ if (!minimum_.IsNull()) {
+ if (minimum_.IsInt64()) {
+ if (exclusiveMinimum_ ? i <= minimum_.GetInt64() : i < minimum_.GetInt64())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString());
+ }
+ else if (minimum_.IsUint64()) {
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString()); // i <= max(int64_t) < minimum.GetUint64()
+ }
+ else if (!CheckDoubleMinimum(context, static_cast<double>(i)))
+ return false;
+ }
+
+ if (!maximum_.IsNull()) {
+ if (maximum_.IsInt64()) {
+ if (exclusiveMaximum_ ? i >= maximum_.GetInt64() : i > maximum_.GetInt64())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString());
+ }
+ else if (maximum_.IsUint64())
+ /* do nothing */; // i <= max(int64_t) < maximum_.GetUint64()
+ else if (!CheckDoubleMaximum(context, static_cast<double>(i)))
+ return false;
+ }
+
+ if (!multipleOf_.IsNull()) {
+ if (multipleOf_.IsUint64()) {
+ if (static_cast<uint64_t>(i >= 0 ? i : -i) % multipleOf_.GetUint64() != 0)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString());
+ }
+ else if (!CheckDoubleMultipleOf(context, static_cast<double>(i)))
+ return false;
+ }
+
+ return true;
+ }
+
+ bool CheckUint(Context& context, uint64_t i) const {
+ if (!(type_ & ((1 << kIntegerSchemaType) | (1 << kNumberSchemaType))))
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetTypeString());
+
+ if (!minimum_.IsNull()) {
+ if (minimum_.IsUint64()) {
+ if (exclusiveMinimum_ ? i <= minimum_.GetUint64() : i < minimum_.GetUint64())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString());
+ }
+ else if (minimum_.IsInt64())
+ /* do nothing */; // i >= 0 > minimum.Getint64()
+ else if (!CheckDoubleMinimum(context, static_cast<double>(i)))
+ return false;
+ }
+
+ if (!maximum_.IsNull()) {
+ if (maximum_.IsUint64()) {
+ if (exclusiveMaximum_ ? i >= maximum_.GetUint64() : i > maximum_.GetUint64())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString());
+ }
+ else if (maximum_.IsInt64())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString()); // i >= 0 > maximum_
+ else if (!CheckDoubleMaximum(context, static_cast<double>(i)))
+ return false;
+ }
+
+ if (!multipleOf_.IsNull()) {
+ if (multipleOf_.IsUint64()) {
+ if (i % multipleOf_.GetUint64() != 0)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString());
+ }
+ else if (!CheckDoubleMultipleOf(context, static_cast<double>(i)))
+ return false;
+ }
+
+ return true;
+ }
+
+ bool CheckDoubleMinimum(Context& context, double d) const {
+ if (exclusiveMinimum_ ? d <= minimum_.GetDouble() : d < minimum_.GetDouble())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMinimumString());
+ return true;
+ }
+
+ bool CheckDoubleMaximum(Context& context, double d) const {
+ if (exclusiveMaximum_ ? d >= maximum_.GetDouble() : d > maximum_.GetDouble())
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMaximumString());
+ return true;
+ }
+
+ bool CheckDoubleMultipleOf(Context& context, double d) const {
+ double a = std::abs(d), b = std::abs(multipleOf_.GetDouble());
+ double q = std::floor(a / b);
+ double r = a - q * b;
+ if (r > 0.0)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(GetMultipleOfString());
+ return true;
+ }
+
+ struct Property {
+ Property() : schema(), dependenciesSchema(), dependenciesValidatorIndex(), dependencies(), required(false) {}
+ ~Property() { AllocatorType::Free(dependencies); }
+ SValue name;
+ const SchemaType* schema;
+ const SchemaType* dependenciesSchema;
+ SizeType dependenciesValidatorIndex;
+ bool* dependencies;
+ bool required;
+ };
+
+ struct PatternProperty {
+ PatternProperty() : schema(), pattern() {}
+ ~PatternProperty() {
+ if (pattern) {
+ pattern->~RegexType();
+ AllocatorType::Free(pattern);
+ }
+ }
+ const SchemaType* schema;
+ RegexType* pattern;
+ };
+
+ AllocatorType* allocator_;
+ uint64_t* enum_;
+ SizeType enumCount_;
+ SchemaArray allOf_;
+ SchemaArray anyOf_;
+ SchemaArray oneOf_;
+ const SchemaType* not_;
+ unsigned type_; // bitmask of kSchemaType
+ SizeType validatorCount_;
+ SizeType notValidatorIndex_;
+
+ Property* properties_;
+ const SchemaType* additionalPropertiesSchema_;
+ PatternProperty* patternProperties_;
+ SizeType patternPropertyCount_;
+ SizeType propertyCount_;
+ SizeType minProperties_;
+ SizeType maxProperties_;
+ bool additionalProperties_;
+ bool hasDependencies_;
+ bool hasRequired_;
+ bool hasSchemaDependencies_;
+
+ const SchemaType* additionalItemsSchema_;
+ const SchemaType* itemsList_;
+ const SchemaType** itemsTuple_;
+ SizeType itemsTupleCount_;
+ SizeType minItems_;
+ SizeType maxItems_;
+ bool additionalItems_;
+ bool uniqueItems_;
+
+ RegexType* pattern_;
+ SizeType minLength_;
+ SizeType maxLength_;
+
+ SValue minimum_;
+ SValue maximum_;
+ SValue multipleOf_;
+ bool exclusiveMinimum_;
+ bool exclusiveMaximum_;
+};
+
+template<typename Stack, typename Ch>
+struct TokenHelper {
+ RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) {
+ *documentStack.template Push<Ch>() = '/';
+ char buffer[21];
+ size_t length = static_cast<size_t>((sizeof(SizeType) == 4 ? u32toa(index, buffer) : u64toa(index, buffer)) - buffer);
+ for (size_t i = 0; i < length; i++)
+ *documentStack.template Push<Ch>() = buffer[i];
+ }
+};
+
+// Partial specialized version for char to prevent buffer copying.
+template <typename Stack>
+struct TokenHelper<Stack, char> {
+ RAPIDJSON_FORCEINLINE static void AppendIndexToken(Stack& documentStack, SizeType index) {
+ if (sizeof(SizeType) == 4) {
+ char *buffer = documentStack.template Push<char>(1 + 10); // '/' + uint
+ *buffer++ = '/';
+ const char* end = internal::u32toa(index, buffer);
+ documentStack.template Pop<char>(static_cast<size_t>(10 - (end - buffer)));
+ }
+ else {
+ char *buffer = documentStack.template Push<char>(1 + 20); // '/' + uint64
+ *buffer++ = '/';
+ const char* end = internal::u64toa(index, buffer);
+ documentStack.template Pop<char>(static_cast<size_t>(20 - (end - buffer)));
+ }
+ }
+};
+
+} // namespace internal
+
+///////////////////////////////////////////////////////////////////////////////
+// IGenericRemoteSchemaDocumentProvider
+
+template <typename SchemaDocumentType>
+class IGenericRemoteSchemaDocumentProvider {
+public:
+ typedef typename SchemaDocumentType::Ch Ch;
+
+ virtual ~IGenericRemoteSchemaDocumentProvider() {}
+ virtual const SchemaDocumentType* GetRemoteDocument(const Ch* uri, SizeType length) = 0;
+};
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericSchemaDocument
+
+//! JSON schema document.
+/*!
+ A JSON schema document is a compiled version of a JSON schema.
+ It is basically a tree of internal::Schema.
+
+ \note This is an immutable class (i.e. its instance cannot be modified after construction).
+ \tparam ValueT Type of JSON value (e.g. \c Value ), which also determine the encoding.
+ \tparam Allocator Allocator type for allocating memory of this document.
+*/
+template <typename ValueT, typename Allocator = CrtAllocator>
+class GenericSchemaDocument {
+public:
+ typedef ValueT ValueType;
+ typedef IGenericRemoteSchemaDocumentProvider<GenericSchemaDocument> IRemoteSchemaDocumentProviderType;
+ typedef Allocator AllocatorType;
+ typedef typename ValueType::EncodingType EncodingType;
+ typedef typename EncodingType::Ch Ch;
+ typedef internal::Schema<GenericSchemaDocument> SchemaType;
+ typedef GenericPointer<ValueType, Allocator> PointerType;
+ friend class internal::Schema<GenericSchemaDocument>;
+ template <typename, typename, typename>
+ friend class GenericSchemaValidator;
+
+ //! Constructor.
+ /*!
+ Compile a JSON document into schema document.
+
+ \param document A JSON document as source.
+ \param remoteProvider An optional remote schema document provider for resolving remote reference. Can be null.
+ \param allocator An optional allocator instance for allocating memory. Can be null.
+ */
+ explicit GenericSchemaDocument(const ValueType& document, IRemoteSchemaDocumentProviderType* remoteProvider = 0, Allocator* allocator = 0) :
+ remoteProvider_(remoteProvider),
+ allocator_(allocator),
+ ownAllocator_(),
+ root_(),
+ schemaMap_(allocator, kInitialSchemaMapSize),
+ schemaRef_(allocator, kInitialSchemaRefSize)
+ {
+ if (!allocator_)
+ ownAllocator_ = allocator_ = RAPIDJSON_NEW(Allocator());
+
+ // Generate root schema, it will call CreateSchema() to create sub-schemas,
+ // And call AddRefSchema() if there are $ref.
+ CreateSchemaRecursive(&root_, PointerType(), document, document);
+
+ // Resolve $ref
+ while (!schemaRef_.Empty()) {
+ SchemaRefEntry* refEntry = schemaRef_.template Pop<SchemaRefEntry>(1);
+ if (const SchemaType* s = GetSchema(refEntry->target)) {
+ if (refEntry->schema)
+ *refEntry->schema = s;
+
+ // Create entry in map if not exist
+ if (!GetSchema(refEntry->source)) {
+ new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(refEntry->source, const_cast<SchemaType*>(s), false, allocator_);
+ }
+ }
+ refEntry->~SchemaRefEntry();
+ }
+
+ RAPIDJSON_ASSERT(root_ != 0);
+
+ schemaRef_.ShrinkToFit(); // Deallocate all memory for ref
+ }
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ //! Move constructor in C++11
+ GenericSchemaDocument(GenericSchemaDocument&& rhs) RAPIDJSON_NOEXCEPT :
+ remoteProvider_(rhs.remoteProvider_),
+ allocator_(rhs.allocator_),
+ ownAllocator_(rhs.ownAllocator_),
+ root_(rhs.root_),
+ schemaMap_(std::move(rhs.schemaMap_)),
+ schemaRef_(std::move(rhs.schemaRef_))
+ {
+ rhs.remoteProvider_ = 0;
+ rhs.allocator_ = 0;
+ rhs.ownAllocator_ = 0;
+ }
+#endif
+
+ //! Destructor
+ ~GenericSchemaDocument() {
+ while (!schemaMap_.Empty())
+ schemaMap_.template Pop<SchemaEntry>(1)->~SchemaEntry();
+
+ RAPIDJSON_DELETE(ownAllocator_);
+ }
+
+ //! Get the root schema.
+ const SchemaType& GetRoot() const { return *root_; }
+
+private:
+ //! Prohibit copying
+ GenericSchemaDocument(const GenericSchemaDocument&);
+ //! Prohibit assignment
+ GenericSchemaDocument& operator=(const GenericSchemaDocument&);
+
+ struct SchemaRefEntry {
+ SchemaRefEntry(const PointerType& s, const PointerType& t, const SchemaType** outSchema, Allocator *allocator) : source(s, allocator), target(t, allocator), schema(outSchema) {}
+ PointerType source;
+ PointerType target;
+ const SchemaType** schema;
+ };
+
+ struct SchemaEntry {
+ SchemaEntry(const PointerType& p, SchemaType* s, bool o, Allocator* allocator) : pointer(p, allocator), schema(s), owned(o) {}
+ ~SchemaEntry() {
+ if (owned) {
+ schema->~SchemaType();
+ Allocator::Free(schema);
+ }
+ }
+ PointerType pointer;
+ SchemaType* schema;
+ bool owned;
+ };
+
+ void CreateSchemaRecursive(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) {
+ if (schema)
+ *schema = SchemaType::GetTypeless();
+
+ if (v.GetType() == kObjectType) {
+ const SchemaType* s = GetSchema(pointer);
+ if (!s)
+ CreateSchema(schema, pointer, v, document);
+
+ for (typename ValueType::ConstMemberIterator itr = v.MemberBegin(); itr != v.MemberEnd(); ++itr)
+ CreateSchemaRecursive(0, pointer.Append(itr->name, allocator_), itr->value, document);
+ }
+ else if (v.GetType() == kArrayType)
+ for (SizeType i = 0; i < v.Size(); i++)
+ CreateSchemaRecursive(0, pointer.Append(i, allocator_), v[i], document);
+ }
+
+ void CreateSchema(const SchemaType** schema, const PointerType& pointer, const ValueType& v, const ValueType& document) {
+ RAPIDJSON_ASSERT(pointer.IsValid());
+ if (v.IsObject()) {
+ if (!HandleRefSchema(pointer, schema, v, document)) {
+ SchemaType* s = new (allocator_->Malloc(sizeof(SchemaType))) SchemaType(this, pointer, v, document, allocator_);
+ new (schemaMap_.template Push<SchemaEntry>()) SchemaEntry(pointer, s, true, allocator_);
+ if (schema)
+ *schema = s;
+ }
+ }
+ }
+
+ bool HandleRefSchema(const PointerType& source, const SchemaType** schema, const ValueType& v, const ValueType& document) {
+ static const Ch kRefString[] = { '$', 'r', 'e', 'f', '\0' };
+ static const ValueType kRefValue(kRefString, 4);
+
+ typename ValueType::ConstMemberIterator itr = v.FindMember(kRefValue);
+ if (itr == v.MemberEnd())
+ return false;
+
+ if (itr->value.IsString()) {
+ SizeType len = itr->value.GetStringLength();
+ if (len > 0) {
+ const Ch* s = itr->value.GetString();
+ SizeType i = 0;
+ while (i < len && s[i] != '#') // Find the first #
+ i++;
+
+ if (i > 0) { // Remote reference, resolve immediately
+ if (remoteProvider_) {
+ if (const GenericSchemaDocument* remoteDocument = remoteProvider_->GetRemoteDocument(s, i - 1)) {
+ PointerType pointer(&s[i], len - i, allocator_);
+ if (pointer.IsValid()) {
+ if (const SchemaType* sc = remoteDocument->GetSchema(pointer)) {
+ if (schema)
+ *schema = sc;
+ return true;
+ }
+ }
+ }
+ }
+ }
+ else if (s[i] == '#') { // Local reference, defer resolution
+ PointerType pointer(&s[i], len - i, allocator_);
+ if (pointer.IsValid()) {
+ if (const ValueType* nv = pointer.Get(document))
+ if (HandleRefSchema(source, schema, *nv, document))
+ return true;
+
+ new (schemaRef_.template Push<SchemaRefEntry>()) SchemaRefEntry(source, pointer, schema, allocator_);
+ return true;
+ }
+ }
+ }
+ }
+ return false;
+ }
+
+ const SchemaType* GetSchema(const PointerType& pointer) const {
+ for (const SchemaEntry* target = schemaMap_.template Bottom<SchemaEntry>(); target != schemaMap_.template End<SchemaEntry>(); ++target)
+ if (pointer == target->pointer)
+ return target->schema;
+ return 0;
+ }
+
+ PointerType GetPointer(const SchemaType* schema) const {
+ for (const SchemaEntry* target = schemaMap_.template Bottom<SchemaEntry>(); target != schemaMap_.template End<SchemaEntry>(); ++target)
+ if (schema == target->schema)
+ return target->pointer;
+ return PointerType();
+ }
+
+ static const size_t kInitialSchemaMapSize = 64;
+ static const size_t kInitialSchemaRefSize = 64;
+
+ IRemoteSchemaDocumentProviderType* remoteProvider_;
+ Allocator *allocator_;
+ Allocator *ownAllocator_;
+ const SchemaType* root_; //!< Root schema.
+ internal::Stack<Allocator> schemaMap_; // Stores created Pointer -> Schemas
+ internal::Stack<Allocator> schemaRef_; // Stores Pointer from $ref and schema which holds the $ref
+};
+
+//! GenericSchemaDocument using Value type.
+typedef GenericSchemaDocument<Value> SchemaDocument;
+//! IGenericRemoteSchemaDocumentProvider using SchemaDocument.
+typedef IGenericRemoteSchemaDocumentProvider<SchemaDocument> IRemoteSchemaDocumentProvider;
+
+///////////////////////////////////////////////////////////////////////////////
+// GenericSchemaValidator
+
+//! JSON Schema Validator.
+/*!
+ A SAX style JSON schema validator.
+ It uses a \c GenericSchemaDocument to validate SAX events.
+ It delegates the incoming SAX events to an output handler.
+ The default output handler does nothing.
+ It can be reused multiple times by calling \c Reset().
+
+ \tparam SchemaDocumentType Type of schema document.
+ \tparam OutputHandler Type of output handler. Default handler does nothing.
+ \tparam StateAllocator Allocator for storing the internal validation states.
+*/
+template <
+ typename SchemaDocumentType,
+ typename OutputHandler = BaseReaderHandler<typename SchemaDocumentType::SchemaType::EncodingType>,
+ typename StateAllocator = CrtAllocator>
+class GenericSchemaValidator :
+ public internal::ISchemaStateFactory<typename SchemaDocumentType::SchemaType>,
+ public internal::ISchemaValidator
+{
+public:
+ typedef typename SchemaDocumentType::SchemaType SchemaType;
+ typedef typename SchemaDocumentType::PointerType PointerType;
+ typedef typename SchemaType::EncodingType EncodingType;
+ typedef typename EncodingType::Ch Ch;
+
+ //! Constructor without output handler.
+ /*!
+ \param schemaDocument The schema document to conform to.
+ \param allocator Optional allocator for storing internal validation states.
+ \param schemaStackCapacity Optional initial capacity of schema path stack.
+ \param documentStackCapacity Optional initial capacity of document path stack.
+ */
+ GenericSchemaValidator(
+ const SchemaDocumentType& schemaDocument,
+ StateAllocator* allocator = 0,
+ size_t schemaStackCapacity = kDefaultSchemaStackCapacity,
+ size_t documentStackCapacity = kDefaultDocumentStackCapacity)
+ :
+ schemaDocument_(&schemaDocument),
+ root_(schemaDocument.GetRoot()),
+ outputHandler_(GetNullHandler()),
+ stateAllocator_(allocator),
+ ownStateAllocator_(0),
+ schemaStack_(allocator, schemaStackCapacity),
+ documentStack_(allocator, documentStackCapacity),
+ valid_(true)
+#if RAPIDJSON_SCHEMA_VERBOSE
+ , depth_(0)
+#endif
+ {
+ }
+
+ //! Constructor with output handler.
+ /*!
+ \param schemaDocument The schema document to conform to.
+ \param allocator Optional allocator for storing internal validation states.
+ \param schemaStackCapacity Optional initial capacity of schema path stack.
+ \param documentStackCapacity Optional initial capacity of document path stack.
+ */
+ GenericSchemaValidator(
+ const SchemaDocumentType& schemaDocument,
+ OutputHandler& outputHandler,
+ StateAllocator* allocator = 0,
+ size_t schemaStackCapacity = kDefaultSchemaStackCapacity,
+ size_t documentStackCapacity = kDefaultDocumentStackCapacity)
+ :
+ schemaDocument_(&schemaDocument),
+ root_(schemaDocument.GetRoot()),
+ outputHandler_(outputHandler),
+ stateAllocator_(allocator),
+ ownStateAllocator_(0),
+ schemaStack_(allocator, schemaStackCapacity),
+ documentStack_(allocator, documentStackCapacity),
+ valid_(true)
+#if RAPIDJSON_SCHEMA_VERBOSE
+ , depth_(0)
+#endif
+ {
+ }
+
+ //! Destructor.
+ ~GenericSchemaValidator() {
+ Reset();
+ RAPIDJSON_DELETE(ownStateAllocator_);
+ }
+
+ //! Reset the internal states.
+ void Reset() {
+ while (!schemaStack_.Empty())
+ PopSchema();
+ documentStack_.Clear();
+ valid_ = true;
+ }
+
+ //! Checks whether the current state is valid.
+ // Implementation of ISchemaValidator
+ virtual bool IsValid() const { return valid_; }
+
+ //! Gets the JSON pointer pointed to the invalid schema.
+ PointerType GetInvalidSchemaPointer() const {
+ return schemaStack_.Empty() ? PointerType() : schemaDocument_->GetPointer(&CurrentSchema());
+ }
+
+ //! Gets the keyword of invalid schema.
+ const Ch* GetInvalidSchemaKeyword() const {
+ return schemaStack_.Empty() ? 0 : CurrentContext().invalidKeyword;
+ }
+
+ //! Gets the JSON pointer pointed to the invalid value.
+ PointerType GetInvalidDocumentPointer() const {
+ return documentStack_.Empty() ? PointerType() : PointerType(documentStack_.template Bottom<Ch>(), documentStack_.GetSize() / sizeof(Ch));
+ }
+
+#if RAPIDJSON_SCHEMA_VERBOSE
+#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_() \
+RAPIDJSON_MULTILINEMACRO_BEGIN\
+ *documentStack_.template Push<Ch>() = '\0';\
+ documentStack_.template Pop<Ch>(1);\
+ internal::PrintInvalidDocument(documentStack_.template Bottom<Ch>());\
+RAPIDJSON_MULTILINEMACRO_END
+#else
+#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_()
+#endif
+
+#define RAPIDJSON_SCHEMA_HANDLE_BEGIN_(method, arg1)\
+ if (!valid_) return false; \
+ if (!BeginValue() || !CurrentSchema().method arg1) {\
+ RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_();\
+ return valid_ = false;\
+ }
+
+#define RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2)\
+ for (Context* context = schemaStack_.template Bottom<Context>(); context != schemaStack_.template End<Context>(); context++) {\
+ if (context->hasher)\
+ static_cast<HasherType*>(context->hasher)->method arg2;\
+ if (context->validators)\
+ for (SizeType i_ = 0; i_ < context->validatorCount; i_++)\
+ static_cast<GenericSchemaValidator*>(context->validators[i_])->method arg2;\
+ if (context->patternPropertiesValidators)\
+ for (SizeType i_ = 0; i_ < context->patternPropertiesValidatorCount; i_++)\
+ static_cast<GenericSchemaValidator*>(context->patternPropertiesValidators[i_])->method arg2;\
+ }
+
+#define RAPIDJSON_SCHEMA_HANDLE_END_(method, arg2)\
+ return valid_ = EndValue() && outputHandler_.method arg2
+
+#define RAPIDJSON_SCHEMA_HANDLE_VALUE_(method, arg1, arg2) \
+ RAPIDJSON_SCHEMA_HANDLE_BEGIN_ (method, arg1);\
+ RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(method, arg2);\
+ RAPIDJSON_SCHEMA_HANDLE_END_ (method, arg2)
+
+ bool Null() { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Null, (CurrentContext() ), ( )); }
+ bool Bool(bool b) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Bool, (CurrentContext(), b), (b)); }
+ bool Int(int i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int, (CurrentContext(), i), (i)); }
+ bool Uint(unsigned u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint, (CurrentContext(), u), (u)); }
+ bool Int64(int64_t i) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Int64, (CurrentContext(), i), (i)); }
+ bool Uint64(uint64_t u) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Uint64, (CurrentContext(), u), (u)); }
+ bool Double(double d) { RAPIDJSON_SCHEMA_HANDLE_VALUE_(Double, (CurrentContext(), d), (d)); }
+ bool RawNumber(const Ch* str, SizeType length, bool copy)
+ { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); }
+ bool String(const Ch* str, SizeType length, bool copy)
+ { RAPIDJSON_SCHEMA_HANDLE_VALUE_(String, (CurrentContext(), str, length, copy), (str, length, copy)); }
+
+ bool StartObject() {
+ RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartObject, (CurrentContext()));
+ RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartObject, ());
+ return valid_ = outputHandler_.StartObject();
+ }
+
+ bool Key(const Ch* str, SizeType len, bool copy) {
+ if (!valid_) return false;
+ AppendToken(str, len);
+ if (!CurrentSchema().Key(CurrentContext(), str, len, copy)) return valid_ = false;
+ RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(Key, (str, len, copy));
+ return valid_ = outputHandler_.Key(str, len, copy);
+ }
+
+ bool EndObject(SizeType memberCount) {
+ if (!valid_) return false;
+ RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndObject, (memberCount));
+ if (!CurrentSchema().EndObject(CurrentContext(), memberCount)) return valid_ = false;
+ RAPIDJSON_SCHEMA_HANDLE_END_(EndObject, (memberCount));
+ }
+
+ bool StartArray() {
+ RAPIDJSON_SCHEMA_HANDLE_BEGIN_(StartArray, (CurrentContext()));
+ RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(StartArray, ());
+ return valid_ = outputHandler_.StartArray();
+ }
+
+ bool EndArray(SizeType elementCount) {
+ if (!valid_) return false;
+ RAPIDJSON_SCHEMA_HANDLE_PARALLEL_(EndArray, (elementCount));
+ if (!CurrentSchema().EndArray(CurrentContext(), elementCount)) return valid_ = false;
+ RAPIDJSON_SCHEMA_HANDLE_END_(EndArray, (elementCount));
+ }
+
+#undef RAPIDJSON_SCHEMA_HANDLE_BEGIN_VERBOSE_
+#undef RAPIDJSON_SCHEMA_HANDLE_BEGIN_
+#undef RAPIDJSON_SCHEMA_HANDLE_PARALLEL_
+#undef RAPIDJSON_SCHEMA_HANDLE_VALUE_
+
+ // Implementation of ISchemaStateFactory<SchemaType>
+ virtual ISchemaValidator* CreateSchemaValidator(const SchemaType& root) {
+ return new (GetStateAllocator().Malloc(sizeof(GenericSchemaValidator))) GenericSchemaValidator(*schemaDocument_, root,
+#if RAPIDJSON_SCHEMA_VERBOSE
+ depth_ + 1,
+#endif
+ &GetStateAllocator());
+ }
+
+ virtual void DestroySchemaValidator(ISchemaValidator* validator) {
+ GenericSchemaValidator* v = static_cast<GenericSchemaValidator*>(validator);
+ v->~GenericSchemaValidator();
+ StateAllocator::Free(v);
+ }
+
+ virtual void* CreateHasher() {
+ return new (GetStateAllocator().Malloc(sizeof(HasherType))) HasherType(&GetStateAllocator());
+ }
+
+ virtual uint64_t GetHashCode(void* hasher) {
+ return static_cast<HasherType*>(hasher)->GetHashCode();
+ }
+
+ virtual void DestroryHasher(void* hasher) {
+ HasherType* h = static_cast<HasherType*>(hasher);
+ h->~HasherType();
+ StateAllocator::Free(h);
+ }
+
+ virtual void* MallocState(size_t size) {
+ return GetStateAllocator().Malloc(size);
+ }
+
+ virtual void FreeState(void* p) {
+ return StateAllocator::Free(p);
+ }
+
+private:
+ typedef typename SchemaType::Context Context;
+ typedef GenericValue<UTF8<>, StateAllocator> HashCodeArray;
+ typedef internal::Hasher<EncodingType, StateAllocator> HasherType;
+
+ GenericSchemaValidator(
+ const SchemaDocumentType& schemaDocument,
+ const SchemaType& root,
+#if RAPIDJSON_SCHEMA_VERBOSE
+ unsigned depth,
+#endif
+ StateAllocator* allocator = 0,
+ size_t schemaStackCapacity = kDefaultSchemaStackCapacity,
+ size_t documentStackCapacity = kDefaultDocumentStackCapacity)
+ :
+ schemaDocument_(&schemaDocument),
+ root_(root),
+ outputHandler_(GetNullHandler()),
+ stateAllocator_(allocator),
+ ownStateAllocator_(0),
+ schemaStack_(allocator, schemaStackCapacity),
+ documentStack_(allocator, documentStackCapacity),
+ valid_(true)
+#if RAPIDJSON_SCHEMA_VERBOSE
+ , depth_(depth)
+#endif
+ {
+ }
+
+ StateAllocator& GetStateAllocator() {
+ if (!stateAllocator_)
+ stateAllocator_ = ownStateAllocator_ = RAPIDJSON_NEW(StateAllocator());
+ return *stateAllocator_;
+ }
+
+ bool BeginValue() {
+ if (schemaStack_.Empty())
+ PushSchema(root_);
+ else {
+ if (CurrentContext().inArray)
+ internal::TokenHelper<internal::Stack<StateAllocator>, Ch>::AppendIndexToken(documentStack_, CurrentContext().arrayElementIndex);
+
+ if (!CurrentSchema().BeginValue(CurrentContext()))
+ return false;
+
+ SizeType count = CurrentContext().patternPropertiesSchemaCount;
+ const SchemaType** sa = CurrentContext().patternPropertiesSchemas;
+ typename Context::PatternValidatorType patternValidatorType = CurrentContext().valuePatternValidatorType;
+ bool valueUniqueness = CurrentContext().valueUniqueness;
+ if (CurrentContext().valueSchema)
+ PushSchema(*CurrentContext().valueSchema);
+
+ if (count > 0) {
+ CurrentContext().objectPatternValidatorType = patternValidatorType;
+ ISchemaValidator**& va = CurrentContext().patternPropertiesValidators;
+ SizeType& validatorCount = CurrentContext().patternPropertiesValidatorCount;
+ va = static_cast<ISchemaValidator**>(MallocState(sizeof(ISchemaValidator*) * count));
+ for (SizeType i = 0; i < count; i++)
+ va[validatorCount++] = CreateSchemaValidator(*sa[i]);
+ }
+
+ CurrentContext().arrayUniqueness = valueUniqueness;
+ }
+ return true;
+ }
+
+ bool EndValue() {
+ if (!CurrentSchema().EndValue(CurrentContext()))
+ return false;
+
+#if RAPIDJSON_SCHEMA_VERBOSE
+ GenericStringBuffer<EncodingType> sb;
+ schemaDocument_->GetPointer(&CurrentSchema()).Stringify(sb);
+
+ *documentStack_.template Push<Ch>() = '\0';
+ documentStack_.template Pop<Ch>(1);
+ internal::PrintValidatorPointers(depth_, sb.GetString(), documentStack_.template Bottom<Ch>());
+#endif
+
+ uint64_t h = CurrentContext().arrayUniqueness ? static_cast<HasherType*>(CurrentContext().hasher)->GetHashCode() : 0;
+
+ PopSchema();
+
+ if (!schemaStack_.Empty()) {
+ Context& context = CurrentContext();
+ if (context.valueUniqueness) {
+ HashCodeArray* a = static_cast<HashCodeArray*>(context.arrayElementHashCodes);
+ if (!a)
+ CurrentContext().arrayElementHashCodes = a = new (GetStateAllocator().Malloc(sizeof(HashCodeArray))) HashCodeArray(kArrayType);
+ for (typename HashCodeArray::ConstValueIterator itr = a->Begin(); itr != a->End(); ++itr)
+ if (itr->GetUint64() == h)
+ RAPIDJSON_INVALID_KEYWORD_RETURN(SchemaType::GetUniqueItemsString());
+ a->PushBack(h, GetStateAllocator());
+ }
+ }
+
+ // Remove the last token of document pointer
+ while (!documentStack_.Empty() && *documentStack_.template Pop<Ch>(1) != '/')
+ ;
+
+ return true;
+ }
+
+ void AppendToken(const Ch* str, SizeType len) {
+ documentStack_.template Reserve<Ch>(1 + len * 2); // worst case all characters are escaped as two characters
+ *documentStack_.template PushUnsafe<Ch>() = '/';
+ for (SizeType i = 0; i < len; i++) {
+ if (str[i] == '~') {
+ *documentStack_.template PushUnsafe<Ch>() = '~';
+ *documentStack_.template PushUnsafe<Ch>() = '0';
+ }
+ else if (str[i] == '/') {
+ *documentStack_.template PushUnsafe<Ch>() = '~';
+ *documentStack_.template PushUnsafe<Ch>() = '1';
+ }
+ else
+ *documentStack_.template PushUnsafe<Ch>() = str[i];
+ }
+ }
+
+ RAPIDJSON_FORCEINLINE void PushSchema(const SchemaType& schema) { new (schemaStack_.template Push<Context>()) Context(*this, &schema); }
+
+ RAPIDJSON_FORCEINLINE void PopSchema() {
+ Context* c = schemaStack_.template Pop<Context>(1);
+ if (HashCodeArray* a = static_cast<HashCodeArray*>(c->arrayElementHashCodes)) {
+ a->~HashCodeArray();
+ StateAllocator::Free(a);
+ }
+ c->~Context();
+ }
+
+ const SchemaType& CurrentSchema() const { return *schemaStack_.template Top<Context>()->schema; }
+ Context& CurrentContext() { return *schemaStack_.template Top<Context>(); }
+ const Context& CurrentContext() const { return *schemaStack_.template Top<Context>(); }
+
+ static OutputHandler& GetNullHandler() {
+ static OutputHandler nullHandler;
+ return nullHandler;
+ }
+
+ static const size_t kDefaultSchemaStackCapacity = 1024;
+ static const size_t kDefaultDocumentStackCapacity = 256;
+ const SchemaDocumentType* schemaDocument_;
+ const SchemaType& root_;
+ OutputHandler& outputHandler_;
+ StateAllocator* stateAllocator_;
+ StateAllocator* ownStateAllocator_;
+ internal::Stack<StateAllocator> schemaStack_; //!< stack to store the current path of schema (BaseSchemaType *)
+ internal::Stack<StateAllocator> documentStack_; //!< stack to store the current path of validating document (Ch)
+ bool valid_;
+#if RAPIDJSON_SCHEMA_VERBOSE
+ unsigned depth_;
+#endif
+};
+
+typedef GenericSchemaValidator<SchemaDocument> SchemaValidator;
+
+///////////////////////////////////////////////////////////////////////////////
+// SchemaValidatingReader
+
+//! A helper class for parsing with validation.
+/*!
+ This helper class is a functor, designed as a parameter of \ref GenericDocument::Populate().
+
+ \tparam parseFlags Combination of \ref ParseFlag.
+ \tparam InputStream Type of input stream, implementing Stream concept.
+ \tparam SourceEncoding Encoding of the input stream.
+ \tparam SchemaDocumentType Type of schema document.
+ \tparam StackAllocator Allocator type for stack.
+*/
+template <
+ unsigned parseFlags,
+ typename InputStream,
+ typename SourceEncoding,
+ typename SchemaDocumentType = SchemaDocument,
+ typename StackAllocator = CrtAllocator>
+class SchemaValidatingReader {
+public:
+ typedef typename SchemaDocumentType::PointerType PointerType;
+ typedef typename InputStream::Ch Ch;
+
+ //! Constructor
+ /*!
+ \param is Input stream.
+ \param sd Schema document.
+ */
+ SchemaValidatingReader(InputStream& is, const SchemaDocumentType& sd) : is_(is), sd_(sd), invalidSchemaKeyword_(), isValid_(true) {}
+
+ template <typename Handler>
+ bool operator()(Handler& handler) {
+ GenericReader<SourceEncoding, typename SchemaDocumentType::EncodingType, StackAllocator> reader;
+ GenericSchemaValidator<SchemaDocumentType, Handler> validator(sd_, handler);
+ parseResult_ = reader.template Parse<parseFlags>(is_, validator);
+
+ isValid_ = validator.IsValid();
+ if (isValid_) {
+ invalidSchemaPointer_ = PointerType();
+ invalidSchemaKeyword_ = 0;
+ invalidDocumentPointer_ = PointerType();
+ }
+ else {
+ invalidSchemaPointer_ = validator.GetInvalidSchemaPointer();
+ invalidSchemaKeyword_ = validator.GetInvalidSchemaKeyword();
+ invalidDocumentPointer_ = validator.GetInvalidDocumentPointer();
+ }
+
+ return parseResult_;
+ }
+
+ const ParseResult& GetParseResult() const { return parseResult_; }
+ bool IsValid() const { return isValid_; }
+ const PointerType& GetInvalidSchemaPointer() const { return invalidSchemaPointer_; }
+ const Ch* GetInvalidSchemaKeyword() const { return invalidSchemaKeyword_; }
+ const PointerType& GetInvalidDocumentPointer() const { return invalidDocumentPointer_; }
+
+private:
+ InputStream& is_;
+ const SchemaDocumentType& sd_;
+
+ ParseResult parseResult_;
+ PointerType invalidSchemaPointer_;
+ const Ch* invalidSchemaKeyword_;
+ PointerType invalidDocumentPointer_;
+ bool isValid_;
+};
+
+RAPIDJSON_NAMESPACE_END
+RAPIDJSON_DIAG_POP
+
+#endif // RAPIDJSON_SCHEMA_H_
diff --git a/include/rapidjson/stream.h b/include/rapidjson/stream.h
new file mode 100644
index 00000000..fef82c25
--- /dev/null
+++ b/include/rapidjson/stream.h
@@ -0,0 +1,179 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#include "rapidjson.h"
+
+#ifndef RAPIDJSON_STREAM_H_
+#define RAPIDJSON_STREAM_H_
+
+#include "encodings.h"
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+///////////////////////////////////////////////////////////////////////////////
+// Stream
+
+/*! \class rapidjson::Stream
+ \brief Concept for reading and writing characters.
+
+ For read-only stream, no need to implement PutBegin(), Put(), Flush() and PutEnd().
+
+ For write-only stream, only need to implement Put() and Flush().
+
+\code
+concept Stream {
+ typename Ch; //!< Character type of the stream.
+
+ //! Read the current character from stream without moving the read cursor.
+ Ch Peek() const;
+
+ //! Read the current character from stream and moving the read cursor to next character.
+ Ch Take();
+
+ //! Get the current read cursor.
+ //! \return Number of characters read from start.
+ size_t Tell();
+
+ //! Begin writing operation at the current read pointer.
+ //! \return The begin writer pointer.
+ Ch* PutBegin();
+
+ //! Write a character.
+ void Put(Ch c);
+
+ //! Flush the buffer.
+ void Flush();
+
+ //! End the writing operation.
+ //! \param begin The begin write pointer returned by PutBegin().
+ //! \return Number of characters written.
+ size_t PutEnd(Ch* begin);
+}
+\endcode
+*/
+
+//! Provides additional information for stream.
+/*!
+ By using traits pattern, this type provides a default configuration for stream.
+ For custom stream, this type can be specialized for other configuration.
+ See TEST(Reader, CustomStringStream) in readertest.cpp for example.
+*/
+template<typename Stream>
+struct StreamTraits {
+ //! Whether to make local copy of stream for optimization during parsing.
+ /*!
+ By default, for safety, streams do not use local copy optimization.
+ Stream that can be copied fast should specialize this, like StreamTraits<StringStream>.
+ */
+ enum { copyOptimization = 0 };
+};
+
+//! Reserve n characters for writing to a stream.
+template<typename Stream>
+inline void PutReserve(Stream& stream, size_t count) {
+ (void)stream;
+ (void)count;
+}
+
+//! Write character to a stream, presuming buffer is reserved.
+template<typename Stream>
+inline void PutUnsafe(Stream& stream, typename Stream::Ch c) {
+ stream.Put(c);
+}
+
+//! Put N copies of a character to a stream.
+template<typename Stream, typename Ch>
+inline void PutN(Stream& stream, Ch c, size_t n) {
+ PutReserve(stream, n);
+ for (size_t i = 0; i < n; i++)
+ PutUnsafe(stream, c);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// StringStream
+
+//! Read-only string stream.
+/*! \note implements Stream concept
+*/
+template <typename Encoding>
+struct GenericStringStream {
+ typedef typename Encoding::Ch Ch;
+
+ GenericStringStream(const Ch *src) : src_(src), head_(src) {}
+
+ Ch Peek() const { return *src_; }
+ Ch Take() { return *src_++; }
+ size_t Tell() const { return static_cast<size_t>(src_ - head_); }
+
+ Ch* PutBegin() { RAPIDJSON_ASSERT(false); return 0; }
+ void Put(Ch) { RAPIDJSON_ASSERT(false); }
+ void Flush() { RAPIDJSON_ASSERT(false); }
+ size_t PutEnd(Ch*) { RAPIDJSON_ASSERT(false); return 0; }
+
+ const Ch* src_; //!< Current read position.
+ const Ch* head_; //!< Original head of the string.
+};
+
+template <typename Encoding>
+struct StreamTraits<GenericStringStream<Encoding> > {
+ enum { copyOptimization = 1 };
+};
+
+//! String stream with UTF8 encoding.
+typedef GenericStringStream<UTF8<> > StringStream;
+
+///////////////////////////////////////////////////////////////////////////////
+// InsituStringStream
+
+//! A read-write string stream.
+/*! This string stream is particularly designed for in-situ parsing.
+ \note implements Stream concept
+*/
+template <typename Encoding>
+struct GenericInsituStringStream {
+ typedef typename Encoding::Ch Ch;
+
+ GenericInsituStringStream(Ch *src) : src_(src), dst_(0), head_(src) {}
+
+ // Read
+ Ch Peek() { return *src_; }
+ Ch Take() { return *src_++; }
+ size_t Tell() { return static_cast<size_t>(src_ - head_); }
+
+ // Write
+ void Put(Ch c) { RAPIDJSON_ASSERT(dst_ != 0); *dst_++ = c; }
+
+ Ch* PutBegin() { return dst_ = src_; }
+ size_t PutEnd(Ch* begin) { return static_cast<size_t>(dst_ - begin); }
+ void Flush() {}
+
+ Ch* Push(size_t count) { Ch* begin = dst_; dst_ += count; return begin; }
+ void Pop(size_t count) { dst_ -= count; }
+
+ Ch* src_;
+ Ch* dst_;
+ Ch* head_;
+};
+
+template <typename Encoding>
+struct StreamTraits<GenericInsituStringStream<Encoding> > {
+ enum { copyOptimization = 1 };
+};
+
+//! Insitu string stream with UTF8 encoding.
+typedef GenericInsituStringStream<UTF8<> > InsituStringStream;
+
+RAPIDJSON_NAMESPACE_END
+
+#endif // RAPIDJSON_STREAM_H_
diff --git a/include/rapidjson/stringbuffer.h b/include/rapidjson/stringbuffer.h
new file mode 100644
index 00000000..78f34d20
--- /dev/null
+++ b/include/rapidjson/stringbuffer.h
@@ -0,0 +1,117 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_STRINGBUFFER_H_
+#define RAPIDJSON_STRINGBUFFER_H_
+
+#include "stream.h"
+#include "internal/stack.h"
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+#include <utility> // std::move
+#endif
+
+#include "internal/stack.h"
+
+#if defined(__clang__)
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(c++98-compat)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+//! Represents an in-memory output stream.
+/*!
+ \tparam Encoding Encoding of the stream.
+ \tparam Allocator type for allocating memory buffer.
+ \note implements Stream concept
+*/
+template <typename Encoding, typename Allocator = CrtAllocator>
+class GenericStringBuffer {
+public:
+ typedef typename Encoding::Ch Ch;
+
+ GenericStringBuffer(Allocator* allocator = 0, size_t capacity = kDefaultCapacity) : stack_(allocator, capacity) {}
+
+#if RAPIDJSON_HAS_CXX11_RVALUE_REFS
+ GenericStringBuffer(GenericStringBuffer&& rhs) : stack_(std::move(rhs.stack_)) {}
+ GenericStringBuffer& operator=(GenericStringBuffer&& rhs) {
+ if (&rhs != this)
+ stack_ = std::move(rhs.stack_);
+ return *this;
+ }
+#endif
+
+ void Put(Ch c) { *stack_.template Push<Ch>() = c; }
+ void PutUnsafe(Ch c) { *stack_.template PushUnsafe<Ch>() = c; }
+ void Flush() {}
+
+ void Clear() { stack_.Clear(); }
+ void ShrinkToFit() {
+ // Push and pop a null terminator. This is safe.
+ *stack_.template Push<Ch>() = '\0';
+ stack_.ShrinkToFit();
+ stack_.template Pop<Ch>(1);
+ }
+
+ void Reserve(size_t count) { stack_.template Reserve<Ch>(count); }
+ Ch* Push(size_t count) { return stack_.template Push<Ch>(count); }
+ Ch* PushUnsafe(size_t count) { return stack_.template PushUnsafe<Ch>(count); }
+ void Pop(size_t count) { stack_.template Pop<Ch>(count); }
+
+ const Ch* GetString() const {
+ // Push and pop a null terminator. This is safe.
+ *stack_.template Push<Ch>() = '\0';
+ stack_.template Pop<Ch>(1);
+
+ return stack_.template Bottom<Ch>();
+ }
+
+ size_t GetSize() const { return stack_.GetSize(); }
+
+ static const size_t kDefaultCapacity = 256;
+ mutable internal::Stack<Allocator> stack_;
+
+private:
+ // Prohibit copy constructor & assignment operator.
+ GenericStringBuffer(const GenericStringBuffer&);
+ GenericStringBuffer& operator=(const GenericStringBuffer&);
+};
+
+//! String buffer with UTF8 encoding
+typedef GenericStringBuffer<UTF8<> > StringBuffer;
+
+template<typename Encoding, typename Allocator>
+inline void PutReserve(GenericStringBuffer<Encoding, Allocator>& stream, size_t count) {
+ stream.Reserve(count);
+}
+
+template<typename Encoding, typename Allocator>
+inline void PutUnsafe(GenericStringBuffer<Encoding, Allocator>& stream, typename Encoding::Ch c) {
+ stream.PutUnsafe(c);
+}
+
+//! Implement specialized version of PutN() with memset() for better performance.
+template<>
+inline void PutN(GenericStringBuffer<UTF8<> >& stream, char c, size_t n) {
+ std::memset(stream.stack_.Push<char>(n), c, n * sizeof(c));
+}
+
+RAPIDJSON_NAMESPACE_END
+
+#if defined(__clang__)
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_STRINGBUFFER_H_
diff --git a/include/rapidjson/writer.h b/include/rapidjson/writer.h
new file mode 100644
index 00000000..94f22dd5
--- /dev/null
+++ b/include/rapidjson/writer.h
@@ -0,0 +1,610 @@
+// Tencent is pleased to support the open source community by making RapidJSON available.
+//
+// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
+//
+// Licensed under the MIT License (the "License"); you may not use this file except
+// in compliance with the License. You may obtain a copy of the License at
+//
+// http://opensource.org/licenses/MIT
+//
+// Unless required by applicable law or agreed to in writing, software distributed
+// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
+// CONDITIONS OF ANY KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations under the License.
+
+#ifndef RAPIDJSON_WRITER_H_
+#define RAPIDJSON_WRITER_H_
+
+#include "stream.h"
+#include "internal/stack.h"
+#include "internal/strfunc.h"
+#include "internal/dtoa.h"
+#include "internal/itoa.h"
+#include "stringbuffer.h"
+#include <new> // placement new
+
+#if defined(RAPIDJSON_SIMD) && defined(_MSC_VER)
+#include <intrin.h>
+#pragma intrinsic(_BitScanForward)
+#endif
+#ifdef RAPIDJSON_SSE42
+#include <nmmintrin.h>
+#elif defined(RAPIDJSON_SSE2)
+#include <emmintrin.h>
+#endif
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(4127) // conditional expression is constant
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_PUSH
+RAPIDJSON_DIAG_OFF(padded)
+RAPIDJSON_DIAG_OFF(unreachable-code)
+#endif
+
+RAPIDJSON_NAMESPACE_BEGIN
+
+///////////////////////////////////////////////////////////////////////////////
+// WriteFlag
+
+/*! \def RAPIDJSON_WRITE_DEFAULT_FLAGS
+ \ingroup RAPIDJSON_CONFIG
+ \brief User-defined kWriteDefaultFlags definition.
+
+ User can define this as any \c WriteFlag combinations.
+*/
+#ifndef RAPIDJSON_WRITE_DEFAULT_FLAGS
+#define RAPIDJSON_WRITE_DEFAULT_FLAGS kWriteNoFlags
+#endif
+
+//! Combination of writeFlags
+enum WriteFlag {
+ kWriteNoFlags = 0, //!< No flags are set.
+ kWriteValidateEncodingFlag = 1, //!< Validate encoding of JSON strings.
+ kWriteNanAndInfFlag = 2, //!< Allow writing of Infinity, -Infinity and NaN.
+ kWriteDefaultFlags = RAPIDJSON_WRITE_DEFAULT_FLAGS //!< Default write flags. Can be customized by defining RAPIDJSON_WRITE_DEFAULT_FLAGS
+};
+
+//! JSON writer
+/*! Writer implements the concept Handler.
+ It generates JSON text by events to an output os.
+
+ User may programmatically calls the functions of a writer to generate JSON text.
+
+ On the other side, a writer can also be passed to objects that generates events,
+
+ for example Reader::Parse() and Document::Accept().
+
+ \tparam OutputStream Type of output stream.
+ \tparam SourceEncoding Encoding of source string.
+ \tparam TargetEncoding Encoding of output stream.
+ \tparam StackAllocator Type of allocator for allocating memory of stack.
+ \note implements Handler concept
+*/
+template<typename OutputStream, typename SourceEncoding = UTF8<>, typename TargetEncoding = UTF8<>, typename StackAllocator = CrtAllocator, unsigned writeFlags = kWriteDefaultFlags>
+class Writer {
+public:
+ typedef typename SourceEncoding::Ch Ch;
+
+ static const int kDefaultMaxDecimalPlaces = 324;
+
+ //! Constructor
+ /*! \param os Output stream.
+ \param stackAllocator User supplied allocator. If it is null, it will create a private one.
+ \param levelDepth Initial capacity of stack.
+ */
+ explicit
+ Writer(OutputStream& os, StackAllocator* stackAllocator = 0, size_t levelDepth = kDefaultLevelDepth) :
+ os_(&os), level_stack_(stackAllocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {}
+
+ explicit
+ Writer(StackAllocator* allocator = 0, size_t levelDepth = kDefaultLevelDepth) :
+ os_(0), level_stack_(allocator, levelDepth * sizeof(Level)), maxDecimalPlaces_(kDefaultMaxDecimalPlaces), hasRoot_(false) {}
+
+ //! Reset the writer with a new stream.
+ /*!
+ This function reset the writer with a new stream and default settings,
+ in order to make a Writer object reusable for output multiple JSONs.
+
+ \param os New output stream.
+ \code
+ Writer<OutputStream> writer(os1);
+ writer.StartObject();
+ // ...
+ writer.EndObject();
+
+ writer.Reset(os2);
+ writer.StartObject();
+ // ...
+ writer.EndObject();
+ \endcode
+ */
+ void Reset(OutputStream& os) {
+ os_ = &os;
+ hasRoot_ = false;
+ level_stack_.Clear();
+ }
+
+ //! Checks whether the output is a complete JSON.
+ /*!
+ A complete JSON has a complete root object or array.
+ */
+ bool IsComplete() const {
+ return hasRoot_ && level_stack_.Empty();
+ }
+
+ int GetMaxDecimalPlaces() const {
+ return maxDecimalPlaces_;
+ }
+
+ //! Sets the maximum number of decimal places for double output.
+ /*!
+ This setting truncates the output with specified number of decimal places.
+
+ For example,
+
+ \code
+ writer.SetMaxDecimalPlaces(3);
+ writer.StartArray();
+ writer.Double(0.12345); // "0.123"
+ writer.Double(0.0001); // "0.0"
+ writer.Double(1.234567890123456e30); // "1.234567890123456e30" (do not truncate significand for positive exponent)
+ writer.Double(1.23e-4); // "0.0" (do truncate significand for negative exponent)
+ writer.EndArray();
+ \endcode
+
+ The default setting does not truncate any decimal places. You can restore to this setting by calling
+ \code
+ writer.SetMaxDecimalPlaces(Writer::kDefaultMaxDecimalPlaces);
+ \endcode
+ */
+ void SetMaxDecimalPlaces(int maxDecimalPlaces) {
+ maxDecimalPlaces_ = maxDecimalPlaces;
+ }
+
+ /*!@name Implementation of Handler
+ \see Handler
+ */
+ //@{
+
+ bool Null() { Prefix(kNullType); return EndValue(WriteNull()); }
+ bool Bool(bool b) { Prefix(b ? kTrueType : kFalseType); return EndValue(WriteBool(b)); }
+ bool Int(int i) { Prefix(kNumberType); return EndValue(WriteInt(i)); }
+ bool Uint(unsigned u) { Prefix(kNumberType); return EndValue(WriteUint(u)); }
+ bool Int64(int64_t i64) { Prefix(kNumberType); return EndValue(WriteInt64(i64)); }
+ bool Uint64(uint64_t u64) { Prefix(kNumberType); return EndValue(WriteUint64(u64)); }
+
+ //! Writes the given \c double value to the stream
+ /*!
+ \param d The value to be written.
+ \return Whether it is succeed.
+ */
+ bool Double(double d) { Prefix(kNumberType); return EndValue(WriteDouble(d)); }
+
+ bool RawNumber(const Ch* str, SizeType length, bool copy = false) {
+ (void)copy;
+ Prefix(kNumberType);
+ return EndValue(WriteString(str, length));
+ }
+
+ bool String(const Ch* str, SizeType length, bool copy = false) {
+ (void)copy;
+ Prefix(kStringType);
+ return EndValue(WriteString(str, length));
+ }
+
+#if RAPIDJSON_HAS_STDSTRING
+ bool String(const std::basic_string<Ch>& str) {
+ return String(str.data(), SizeType(str.size()));
+ }
+#endif
+
+ bool StartObject() {
+ Prefix(kObjectType);
+ new (level_stack_.template Push<Level>()) Level(false);
+ return WriteStartObject();
+ }
+
+ bool Key(const Ch* str, SizeType length, bool copy = false) { return String(str, length, copy); }
+
+ bool EndObject(SizeType memberCount = 0) {
+ (void)memberCount;
+ RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
+ RAPIDJSON_ASSERT(!level_stack_.template Top<Level>()->inArray);
+ level_stack_.template Pop<Level>(1);
+ return EndValue(WriteEndObject());
+ }
+
+ bool StartArray() {
+ Prefix(kArrayType);
+ new (level_stack_.template Push<Level>()) Level(true);
+ return WriteStartArray();
+ }
+
+ bool EndArray(SizeType elementCount = 0) {
+ (void)elementCount;
+ RAPIDJSON_ASSERT(level_stack_.GetSize() >= sizeof(Level));
+ RAPIDJSON_ASSERT(level_stack_.template Top<Level>()->inArray);
+ level_stack_.template Pop<Level>(1);
+ return EndValue(WriteEndArray());
+ }
+ //@}
+
+ /*! @name Convenience extensions */
+ //@{
+
+ //! Simpler but slower overload.
+ bool String(const Ch* str) { return String(str, internal::StrLen(str)); }
+ bool Key(const Ch* str) { return Key(str, internal::StrLen(str)); }
+
+ //@}
+
+ //! Write a raw JSON value.
+ /*!
+ For user to write a stringified JSON as a value.
+
+ \param json A well-formed JSON value. It should not contain null character within [0, length - 1] range.
+ \param length Length of the json.
+ \param type Type of the root of json.
+ */
+ bool RawValue(const Ch* json, size_t length, Type type) { Prefix(type); return EndValue(WriteRawValue(json, length)); }
+
+protected:
+ //! Information for each nested level
+ struct Level {
+ Level(bool inArray_) : valueCount(0), inArray(inArray_) {}
+ size_t valueCount; //!< number of values in this level
+ bool inArray; //!< true if in array, otherwise in object
+ };
+
+ static const size_t kDefaultLevelDepth = 32;
+
+ bool WriteNull() {
+ PutReserve(*os_, 4);
+ PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 'l'); return true;
+ }
+
+ bool WriteBool(bool b) {
+ if (b) {
+ PutReserve(*os_, 4);
+ PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'r'); PutUnsafe(*os_, 'u'); PutUnsafe(*os_, 'e');
+ }
+ else {
+ PutReserve(*os_, 5);
+ PutUnsafe(*os_, 'f'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'l'); PutUnsafe(*os_, 's'); PutUnsafe(*os_, 'e');
+ }
+ return true;
+ }
+
+ bool WriteInt(int i) {
+ char buffer[11];
+ const char* end = internal::i32toa(i, buffer);
+ PutReserve(*os_, static_cast<size_t>(end - buffer));
+ for (const char* p = buffer; p != end; ++p)
+ PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
+ return true;
+ }
+
+ bool WriteUint(unsigned u) {
+ char buffer[10];
+ const char* end = internal::u32toa(u, buffer);
+ PutReserve(*os_, static_cast<size_t>(end - buffer));
+ for (const char* p = buffer; p != end; ++p)
+ PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
+ return true;
+ }
+
+ bool WriteInt64(int64_t i64) {
+ char buffer[21];
+ const char* end = internal::i64toa(i64, buffer);
+ PutReserve(*os_, static_cast<size_t>(end - buffer));
+ for (const char* p = buffer; p != end; ++p)
+ PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
+ return true;
+ }
+
+ bool WriteUint64(uint64_t u64) {
+ char buffer[20];
+ char* end = internal::u64toa(u64, buffer);
+ PutReserve(*os_, static_cast<size_t>(end - buffer));
+ for (char* p = buffer; p != end; ++p)
+ PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
+ return true;
+ }
+
+ bool WriteDouble(double d) {
+ if (internal::Double(d).IsNanOrInf()) {
+ if (!(writeFlags & kWriteNanAndInfFlag))
+ return false;
+ if (internal::Double(d).IsNan()) {
+ PutReserve(*os_, 3);
+ PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N');
+ return true;
+ }
+ if (internal::Double(d).Sign()) {
+ PutReserve(*os_, 9);
+ PutUnsafe(*os_, '-');
+ }
+ else
+ PutReserve(*os_, 8);
+ PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f');
+ PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y');
+ return true;
+ }
+
+ char buffer[25];
+ char* end = internal::dtoa(d, buffer, maxDecimalPlaces_);
+ PutReserve(*os_, static_cast<size_t>(end - buffer));
+ for (char* p = buffer; p != end; ++p)
+ PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(*p));
+ return true;
+ }
+
+ bool WriteString(const Ch* str, SizeType length) {
+ static const typename TargetEncoding::Ch hexDigits[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+ static const char escape[256] = {
+#define Z16 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
+ //0 1 2 3 4 5 6 7 8 9 A B C D E F
+ 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'b', 't', 'n', 'u', 'f', 'r', 'u', 'u', // 00
+ 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', 'u', // 10
+ 0, 0, '"', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20
+ Z16, Z16, // 30~4F
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,'\\', 0, 0, 0, // 50
+ Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16, Z16 // 60~FF
+#undef Z16
+ };
+
+ if (TargetEncoding::supportUnicode)
+ PutReserve(*os_, 2 + length * 6); // "\uxxxx..."
+ else
+ PutReserve(*os_, 2 + length * 12); // "\uxxxx\uyyyy..."
+
+ PutUnsafe(*os_, '\"');
+ GenericStringStream<SourceEncoding> is(str);
+ while (ScanWriteUnescapedString(is, length)) {
+ const Ch c = is.Peek();
+ if (!TargetEncoding::supportUnicode && static_cast<unsigned>(c) >= 0x80) {
+ // Unicode escaping
+ unsigned codepoint;
+ if (RAPIDJSON_UNLIKELY(!SourceEncoding::Decode(is, &codepoint)))
+ return false;
+ PutUnsafe(*os_, '\\');
+ PutUnsafe(*os_, 'u');
+ if (codepoint <= 0xD7FF || (codepoint >= 0xE000 && codepoint <= 0xFFFF)) {
+ PutUnsafe(*os_, hexDigits[(codepoint >> 12) & 15]);
+ PutUnsafe(*os_, hexDigits[(codepoint >> 8) & 15]);
+ PutUnsafe(*os_, hexDigits[(codepoint >> 4) & 15]);
+ PutUnsafe(*os_, hexDigits[(codepoint ) & 15]);
+ }
+ else {
+ RAPIDJSON_ASSERT(codepoint >= 0x010000 && codepoint <= 0x10FFFF);
+ // Surrogate pair
+ unsigned s = codepoint - 0x010000;
+ unsigned lead = (s >> 10) + 0xD800;
+ unsigned trail = (s & 0x3FF) + 0xDC00;
+ PutUnsafe(*os_, hexDigits[(lead >> 12) & 15]);
+ PutUnsafe(*os_, hexDigits[(lead >> 8) & 15]);
+ PutUnsafe(*os_, hexDigits[(lead >> 4) & 15]);
+ PutUnsafe(*os_, hexDigits[(lead ) & 15]);
+ PutUnsafe(*os_, '\\');
+ PutUnsafe(*os_, 'u');
+ PutUnsafe(*os_, hexDigits[(trail >> 12) & 15]);
+ PutUnsafe(*os_, hexDigits[(trail >> 8) & 15]);
+ PutUnsafe(*os_, hexDigits[(trail >> 4) & 15]);
+ PutUnsafe(*os_, hexDigits[(trail ) & 15]);
+ }
+ }
+ else if ((sizeof(Ch) == 1 || static_cast<unsigned>(c) < 256) && RAPIDJSON_UNLIKELY(escape[static_cast<unsigned char>(c)])) {
+ is.Take();
+ PutUnsafe(*os_, '\\');
+ PutUnsafe(*os_, static_cast<typename TargetEncoding::Ch>(escape[static_cast<unsigned char>(c)]));
+ if (escape[static_cast<unsigned char>(c)] == 'u') {
+ PutUnsafe(*os_, '0');
+ PutUnsafe(*os_, '0');
+ PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) >> 4]);
+ PutUnsafe(*os_, hexDigits[static_cast<unsigned char>(c) & 0xF]);
+ }
+ }
+ else if (RAPIDJSON_UNLIKELY(!(writeFlags & kWriteValidateEncodingFlag ?
+ Transcoder<SourceEncoding, TargetEncoding>::Validate(is, *os_) :
+ Transcoder<SourceEncoding, TargetEncoding>::TranscodeUnsafe(is, *os_))))
+ return false;
+ }
+ PutUnsafe(*os_, '\"');
+ return true;
+ }
+
+ bool ScanWriteUnescapedString(GenericStringStream<SourceEncoding>& is, size_t length) {
+ return RAPIDJSON_LIKELY(is.Tell() < length);
+ }
+
+ bool WriteStartObject() { os_->Put('{'); return true; }
+ bool WriteEndObject() { os_->Put('}'); return true; }
+ bool WriteStartArray() { os_->Put('['); return true; }
+ bool WriteEndArray() { os_->Put(']'); return true; }
+
+ bool WriteRawValue(const Ch* json, size_t length) {
+ PutReserve(*os_, length);
+ for (size_t i = 0; i < length; i++) {
+ RAPIDJSON_ASSERT(json[i] != '\0');
+ PutUnsafe(*os_, json[i]);
+ }
+ return true;
+ }
+
+ void Prefix(Type type) {
+ (void)type;
+ if (RAPIDJSON_LIKELY(level_stack_.GetSize() != 0)) { // this value is not at root
+ Level* level = level_stack_.template Top<Level>();
+ if (level->valueCount > 0) {
+ if (level->inArray)
+ os_->Put(','); // add comma if it is not the first element in array
+ else // in object
+ os_->Put((level->valueCount % 2 == 0) ? ',' : ':');
+ }
+ if (!level->inArray && level->valueCount % 2 == 0)
+ RAPIDJSON_ASSERT(type == kStringType); // if it's in object, then even number should be a name
+ level->valueCount++;
+ }
+ else {
+ RAPIDJSON_ASSERT(!hasRoot_); // Should only has one and only one root.
+ hasRoot_ = true;
+ }
+ }
+
+ // Flush the value if it is the top level one.
+ bool EndValue(bool ret) {
+ if (RAPIDJSON_UNLIKELY(level_stack_.Empty())) // end of json text
+ os_->Flush();
+ return ret;
+ }
+
+ OutputStream* os_;
+ internal::Stack<StackAllocator> level_stack_;
+ int maxDecimalPlaces_;
+ bool hasRoot_;
+
+private:
+ // Prohibit copy constructor & assignment operator.
+ Writer(const Writer&);
+ Writer& operator=(const Writer&);
+};
+
+// Full specialization for StringStream to prevent memory copying
+
+template<>
+inline bool Writer<StringBuffer>::WriteInt(int i) {
+ char *buffer = os_->Push(11);
+ const char* end = internal::i32toa(i, buffer);
+ os_->Pop(static_cast<size_t>(11 - (end - buffer)));
+ return true;
+}
+
+template<>
+inline bool Writer<StringBuffer>::WriteUint(unsigned u) {
+ char *buffer = os_->Push(10);
+ const char* end = internal::u32toa(u, buffer);
+ os_->Pop(static_cast<size_t>(10 - (end - buffer)));
+ return true;
+}
+
+template<>
+inline bool Writer<StringBuffer>::WriteInt64(int64_t i64) {
+ char *buffer = os_->Push(21);
+ const char* end = internal::i64toa(i64, buffer);
+ os_->Pop(static_cast<size_t>(21 - (end - buffer)));
+ return true;
+}
+
+template<>
+inline bool Writer<StringBuffer>::WriteUint64(uint64_t u) {
+ char *buffer = os_->Push(20);
+ const char* end = internal::u64toa(u, buffer);
+ os_->Pop(static_cast<size_t>(20 - (end - buffer)));
+ return true;
+}
+
+template<>
+inline bool Writer<StringBuffer>::WriteDouble(double d) {
+ if (internal::Double(d).IsNanOrInf()) {
+ // Note: This code path can only be reached if (RAPIDJSON_WRITE_DEFAULT_FLAGS & kWriteNanAndInfFlag).
+ if (!(kWriteDefaultFlags & kWriteNanAndInfFlag))
+ return false;
+ if (internal::Double(d).IsNan()) {
+ PutReserve(*os_, 3);
+ PutUnsafe(*os_, 'N'); PutUnsafe(*os_, 'a'); PutUnsafe(*os_, 'N');
+ return true;
+ }
+ if (internal::Double(d).Sign()) {
+ PutReserve(*os_, 9);
+ PutUnsafe(*os_, '-');
+ }
+ else
+ PutReserve(*os_, 8);
+ PutUnsafe(*os_, 'I'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'f');
+ PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 'n'); PutUnsafe(*os_, 'i'); PutUnsafe(*os_, 't'); PutUnsafe(*os_, 'y');
+ return true;
+ }
+
+ char *buffer = os_->Push(25);
+ char* end = internal::dtoa(d, buffer, maxDecimalPlaces_);
+ os_->Pop(static_cast<size_t>(25 - (end - buffer)));
+ return true;
+}
+
+#if defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
+template<>
+inline bool Writer<StringBuffer>::ScanWriteUnescapedString(StringStream& is, size_t length) {
+ if (length < 16)
+ return RAPIDJSON_LIKELY(is.Tell() < length);
+
+ if (!RAPIDJSON_LIKELY(is.Tell() < length))
+ return false;
+
+ const char* p = is.src_;
+ const char* end = is.head_ + length;
+ const char* nextAligned = reinterpret_cast<const char*>((reinterpret_cast<size_t>(p) + 15) & static_cast<size_t>(~15));
+ const char* endAligned = reinterpret_cast<const char*>(reinterpret_cast<size_t>(end) & static_cast<size_t>(~15));
+ if (nextAligned > end)
+ return true;
+
+ while (p != nextAligned)
+ if (*p < 0x20 || *p == '\"' || *p == '\\') {
+ is.src_ = p;
+ return RAPIDJSON_LIKELY(is.Tell() < length);
+ }
+ else
+ os_->PutUnsafe(*p++);
+
+ // The rest of string using SIMD
+ static const char dquote[16] = { '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"', '\"' };
+ static const char bslash[16] = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' };
+ static const char space[16] = { 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19, 0x19 };
+ const __m128i dq = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&dquote[0]));
+ const __m128i bs = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&bslash[0]));
+ const __m128i sp = _mm_loadu_si128(reinterpret_cast<const __m128i *>(&space[0]));
+
+ for (; p != endAligned; p += 16) {
+ const __m128i s = _mm_load_si128(reinterpret_cast<const __m128i *>(p));
+ const __m128i t1 = _mm_cmpeq_epi8(s, dq);
+ const __m128i t2 = _mm_cmpeq_epi8(s, bs);
+ const __m128i t3 = _mm_cmpeq_epi8(_mm_max_epu8(s, sp), sp); // s < 0x20 <=> max(s, 0x19) == 0x19
+ const __m128i x = _mm_or_si128(_mm_or_si128(t1, t2), t3);
+ unsigned short r = static_cast<unsigned short>(_mm_movemask_epi8(x));
+ if (RAPIDJSON_UNLIKELY(r != 0)) { // some of characters is escaped
+ SizeType len;
+#ifdef _MSC_VER // Find the index of first escaped
+ unsigned long offset;
+ _BitScanForward(&offset, r);
+ len = offset;
+#else
+ len = static_cast<SizeType>(__builtin_ffs(r) - 1);
+#endif
+ char* q = reinterpret_cast<char*>(os_->PushUnsafe(len));
+ for (size_t i = 0; i < len; i++)
+ q[i] = p[i];
+
+ p += len;
+ break;
+ }
+ _mm_storeu_si128(reinterpret_cast<__m128i *>(os_->PushUnsafe(16)), s);
+ }
+
+ is.src_ = p;
+ return RAPIDJSON_LIKELY(is.Tell() < length);
+}
+#endif // defined(RAPIDJSON_SSE2) || defined(RAPIDJSON_SSE42)
+
+RAPIDJSON_NAMESPACE_END
+
+#ifdef _MSC_VER
+RAPIDJSON_DIAG_POP
+#endif
+
+#ifdef __clang__
+RAPIDJSON_DIAG_POP
+#endif
+
+#endif // RAPIDJSON_RAPIDJSON_H_
diff --git a/include/spdlog/async.h b/include/spdlog/async.h
new file mode 100644
index 00000000..f7956305
--- /dev/null
+++ b/include/spdlog/async.h
@@ -0,0 +1,93 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+//
+// Async logging using global thread pool
+// All loggers created here share same global thread pool.
+// Each log message is pushed to a queue along with a shared pointer to the
+// logger.
+// If a logger deleted while having pending messages in the queue, it's actual
+// destruction will defer
+// until all its messages are processed by the thread pool.
+// This is because each message in the queue holds a shared_ptr to the
+// originating logger.
+
+#include <spdlog/async_logger.h>
+#include <spdlog/details/registry.h>
+#include <spdlog/details/thread_pool.h>
+
+#include <memory>
+#include <mutex>
+#include <functional>
+
+namespace spdlog {
+
+namespace details {
+static const size_t default_async_q_size = 8192;
+}
+
+// async logger factory - creates async loggers backed with thread pool.
+// if a global thread pool doesn't already exist, create it with default queue
+// size of 8192 items and single thread.
+template<async_overflow_policy OverflowPolicy = async_overflow_policy::block>
+struct async_factory_impl
+{
+ template<typename Sink, typename... SinkArgs>
+ static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&...args)
+ {
+ auto &registry_inst = details::registry::instance();
+
+ // create global thread pool if not already exists..
+
+ auto &mutex = registry_inst.tp_mutex();
+ std::lock_guard<std::recursive_mutex> tp_lock(mutex);
+ auto tp = registry_inst.get_tp();
+ if (tp == nullptr)
+ {
+ tp = std::make_shared<details::thread_pool>(details::default_async_q_size, 1);
+ registry_inst.set_tp(tp);
+ }
+
+ auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
+ auto new_logger = std::make_shared<async_logger>(std::move(logger_name), std::move(sink), std::move(tp), OverflowPolicy);
+ registry_inst.initialize_logger(new_logger);
+ return new_logger;
+ }
+};
+
+using async_factory = async_factory_impl<async_overflow_policy::block>;
+using async_factory_nonblock = async_factory_impl<async_overflow_policy::overrun_oldest>;
+
+template<typename Sink, typename... SinkArgs>
+inline std::shared_ptr<spdlog::logger> create_async(std::string logger_name, SinkArgs &&...sink_args)
+{
+ return async_factory::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
+}
+
+template<typename Sink, typename... SinkArgs>
+inline std::shared_ptr<spdlog::logger> create_async_nb(std::string logger_name, SinkArgs &&...sink_args)
+{
+ return async_factory_nonblock::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
+}
+
+// set global thread pool.
+inline void init_thread_pool(size_t q_size, size_t thread_count, std::function<void()> on_thread_start)
+{
+ auto tp = std::make_shared<details::thread_pool>(q_size, thread_count, on_thread_start);
+ details::registry::instance().set_tp(std::move(tp));
+}
+
+// set global thread pool.
+inline void init_thread_pool(size_t q_size, size_t thread_count)
+{
+ init_thread_pool(q_size, thread_count, [] {});
+}
+
+// get the global thread pool.
+inline std::shared_ptr<spdlog::details::thread_pool> thread_pool()
+{
+ return details::registry::instance().get_tp();
+}
+} // namespace spdlog
diff --git a/include/spdlog/async_logger-inl.h b/include/spdlog/async_logger-inl.h
new file mode 100644
index 00000000..f8c9694c
--- /dev/null
+++ b/include/spdlog/async_logger-inl.h
@@ -0,0 +1,92 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/async_logger.h>
+#endif
+
+#include <spdlog/sinks/sink.h>
+#include <spdlog/details/thread_pool.h>
+
+#include <memory>
+#include <string>
+
+SPDLOG_INLINE spdlog::async_logger::async_logger(
+ std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
+ : async_logger(std::move(logger_name), sinks_list.begin(), sinks_list.end(), std::move(tp), overflow_policy)
+{}
+
+SPDLOG_INLINE spdlog::async_logger::async_logger(
+ std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp, async_overflow_policy overflow_policy)
+ : async_logger(std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy)
+{}
+
+// send the log message to the thread pool
+SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg)
+{
+ if (auto pool_ptr = thread_pool_.lock())
+ {
+ pool_ptr->post_log(shared_from_this(), msg, overflow_policy_);
+ }
+ else
+ {
+ throw_spdlog_ex("async log: thread pool doesn't exist anymore");
+ }
+}
+
+// send flush request to the thread pool
+SPDLOG_INLINE void spdlog::async_logger::flush_()
+{
+ if (auto pool_ptr = thread_pool_.lock())
+ {
+ pool_ptr->post_flush(shared_from_this(), overflow_policy_);
+ }
+ else
+ {
+ throw_spdlog_ex("async flush: thread pool doesn't exist anymore");
+ }
+}
+
+//
+// backend functions - called from the thread pool to do the actual job
+//
+SPDLOG_INLINE void spdlog::async_logger::backend_sink_it_(const details::log_msg &msg)
+{
+ for (auto &sink : sinks_)
+ {
+ if (sink->should_log(msg.level))
+ {
+ SPDLOG_TRY
+ {
+ sink->log(msg);
+ }
+ SPDLOG_LOGGER_CATCH()
+ }
+ }
+
+ if (should_flush_(msg))
+ {
+ backend_flush_();
+ }
+}
+
+SPDLOG_INLINE void spdlog::async_logger::backend_flush_()
+{
+ for (auto &sink : sinks_)
+ {
+ SPDLOG_TRY
+ {
+ sink->flush();
+ }
+ SPDLOG_LOGGER_CATCH()
+ }
+}
+
+SPDLOG_INLINE std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name)
+{
+ auto cloned = std::make_shared<spdlog::async_logger>(*this);
+ cloned->name_ = std::move(new_name);
+ return cloned;
+}
diff --git a/include/spdlog/async_logger.h b/include/spdlog/async_logger.h
new file mode 100644
index 00000000..6f299672
--- /dev/null
+++ b/include/spdlog/async_logger.h
@@ -0,0 +1,68 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+// Fast asynchronous logger.
+// Uses pre allocated queue.
+// Creates a single back thread to pop messages from the queue and log them.
+//
+// Upon each log write the logger:
+// 1. Checks if its log level is enough to log the message
+// 2. Push a new copy of the message to a queue (or block the caller until
+// space is available in the queue)
+// Upon destruction, logs all remaining messages in the queue before
+// destructing..
+
+#include <spdlog/logger.h>
+
+namespace spdlog {
+
+// Async overflow policy - block by default.
+enum class async_overflow_policy
+{
+ block, // Block until message can be enqueued
+ overrun_oldest // Discard oldest message in the queue if full when trying to
+ // add new item.
+};
+
+namespace details {
+class thread_pool;
+}
+
+class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>, public logger
+{
+ friend class details::thread_pool;
+
+public:
+ template<typename It>
+ async_logger(std::string logger_name, It begin, It end, std::weak_ptr<details::thread_pool> tp,
+ async_overflow_policy overflow_policy = async_overflow_policy::block)
+ : logger(std::move(logger_name), begin, end)
+ , thread_pool_(std::move(tp))
+ , overflow_policy_(overflow_policy)
+ {}
+
+ async_logger(std::string logger_name, sinks_init_list sinks_list, std::weak_ptr<details::thread_pool> tp,
+ async_overflow_policy overflow_policy = async_overflow_policy::block);
+
+ async_logger(std::string logger_name, sink_ptr single_sink, std::weak_ptr<details::thread_pool> tp,
+ async_overflow_policy overflow_policy = async_overflow_policy::block);
+
+ std::shared_ptr<logger> clone(std::string new_name) override;
+
+protected:
+ void sink_it_(const details::log_msg &msg) override;
+ void flush_() override;
+ void backend_sink_it_(const details::log_msg &incoming_log_msg);
+ void backend_flush_();
+
+private:
+ std::weak_ptr<details::thread_pool> thread_pool_;
+ async_overflow_policy overflow_policy_;
+};
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "async_logger-inl.h"
+#endif
diff --git a/include/spdlog/cfg/argv.h b/include/spdlog/cfg/argv.h
new file mode 100644
index 00000000..36d9f1c4
--- /dev/null
+++ b/include/spdlog/cfg/argv.h
@@ -0,0 +1,44 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+#include <spdlog/cfg/helpers.h>
+#include <spdlog/details/registry.h>
+
+//
+// Init log levels using each argv entry that starts with "SPDLOG_LEVEL="
+//
+// set all loggers to debug level:
+// example.exe "SPDLOG_LEVEL=debug"
+
+// set logger1 to trace level
+// example.exe "SPDLOG_LEVEL=logger1=trace"
+
+// turn off all logging except for logger1 and logger2:
+// example.exe "SPDLOG_LEVEL=off,logger1=debug,logger2=info"
+
+namespace spdlog {
+namespace cfg {
+
+// search for SPDLOG_LEVEL= in the args and use it to init the levels
+inline void load_argv_levels(int argc, const char **argv)
+{
+ const std::string spdlog_level_prefix = "SPDLOG_LEVEL=";
+ for (int i = 1; i < argc; i++)
+ {
+ std::string arg = argv[i];
+ if (arg.find(spdlog_level_prefix) == 0)
+ {
+ auto levels_string = arg.substr(spdlog_level_prefix.size());
+ helpers::load_levels(levels_string);
+ }
+ }
+}
+
+inline void load_argv_levels(int argc, char **argv)
+{
+ load_argv_levels(argc, const_cast<const char **>(argv));
+}
+
+} // namespace cfg
+} // namespace spdlog
diff --git a/include/spdlog/cfg/env.h b/include/spdlog/cfg/env.h
new file mode 100644
index 00000000..1f39ebbb
--- /dev/null
+++ b/include/spdlog/cfg/env.h
@@ -0,0 +1,38 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+#include <spdlog/cfg/helpers.h>
+#include <spdlog/details/registry.h>
+#include <spdlog/details/os.h>
+
+//
+// Init levels and patterns from env variables SPDLOG_LEVEL
+// Inspired from Rust's "env_logger" crate (https://crates.io/crates/env_logger).
+// Note - fallback to "info" level on unrecognized levels
+//
+// Examples:
+//
+// set global level to debug:
+// export SPDLOG_LEVEL=debug
+//
+// turn off all logging except for logger1:
+// export SPDLOG_LEVEL="*=off,logger1=debug"
+//
+
+// turn off all logging except for logger1 and logger2:
+// export SPDLOG_LEVEL="off,logger1=debug,logger2=info"
+
+namespace spdlog {
+namespace cfg {
+inline void load_env_levels()
+{
+ auto env_val = details::os::getenv("SPDLOG_LEVEL");
+ if (!env_val.empty())
+ {
+ helpers::load_levels(env_val);
+ }
+}
+
+} // namespace cfg
+} // namespace spdlog
diff --git a/include/spdlog/cfg/helpers-inl.h b/include/spdlog/cfg/helpers-inl.h
new file mode 100644
index 00000000..9e4daede
--- /dev/null
+++ b/include/spdlog/cfg/helpers-inl.h
@@ -0,0 +1,120 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/cfg/helpers.h>
+#endif
+
+#include <spdlog/spdlog.h>
+#include <spdlog/details/os.h>
+#include <spdlog/details/registry.h>
+
+#include <algorithm>
+#include <string>
+#include <utility>
+#include <sstream>
+
+namespace spdlog {
+namespace cfg {
+namespace helpers {
+
+// inplace convert to lowercase
+inline std::string &to_lower_(std::string &str)
+{
+ std::transform(
+ str.begin(), str.end(), str.begin(), [](char ch) { return static_cast<char>((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch); });
+ return str;
+}
+
+// inplace trim spaces
+inline std::string &trim_(std::string &str)
+{
+ const char *spaces = " \n\r\t";
+ str.erase(str.find_last_not_of(spaces) + 1);
+ str.erase(0, str.find_first_not_of(spaces));
+ return str;
+}
+
+// return (name,value) trimmed pair from given "name=value" string.
+// return empty string on missing parts
+// "key=val" => ("key", "val")
+// " key = val " => ("key", "val")
+// "key=" => ("key", "")
+// "val" => ("", "val")
+
+inline std::pair<std::string, std::string> extract_kv_(char sep, const std::string &str)
+{
+ auto n = str.find(sep);
+ std::string k, v;
+ if (n == std::string::npos)
+ {
+ v = str;
+ }
+ else
+ {
+ k = str.substr(0, n);
+ v = str.substr(n + 1);
+ }
+ return std::make_pair(trim_(k), trim_(v));
+}
+
+// return vector of key/value pairs from sequence of "K1=V1,K2=V2,.."
+// "a=AAA,b=BBB,c=CCC,.." => {("a","AAA"),("b","BBB"),("c", "CCC"),...}
+inline std::unordered_map<std::string, std::string> extract_key_vals_(const std::string &str)
+{
+ std::string token;
+ std::istringstream token_stream(str);
+ std::unordered_map<std::string, std::string> rv{};
+ while (std::getline(token_stream, token, ','))
+ {
+ if (token.empty())
+ {
+ continue;
+ }
+ auto kv = extract_kv_('=', token);
+ rv[kv.first] = kv.second;
+ }
+ return rv;
+}
+
+SPDLOG_INLINE void load_levels(const std::string &input)
+{
+ if (input.empty() || input.size() > 512)
+ {
+ return;
+ }
+
+ auto key_vals = extract_key_vals_(input);
+ std::unordered_map<std::string, level::level_enum> levels;
+ level::level_enum global_level = level::info;
+ bool global_level_found = false;
+
+ for (auto &name_level : key_vals)
+ {
+ auto &logger_name = name_level.first;
+ auto level_name = to_lower_(name_level.second);
+ auto level = level::from_str(level_name);
+ // ignore unrecognized level names
+ if (level == level::off && level_name != "off")
+ {
+ continue;
+ }
+ if (logger_name.empty()) // no logger name indicate global level
+ {
+ global_level_found = true;
+ global_level = level;
+ }
+ else
+ {
+ levels[logger_name] = level;
+ }
+ }
+
+ details::registry::instance().set_levels(std::move(levels), global_level_found ? &global_level : nullptr);
+}
+
+} // namespace helpers
+} // namespace cfg
+} // namespace spdlog
diff --git a/include/spdlog/cfg/helpers.h b/include/spdlog/cfg/helpers.h
new file mode 100644
index 00000000..a795f39a
--- /dev/null
+++ b/include/spdlog/cfg/helpers.h
@@ -0,0 +1,29 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <unordered_map>
+
+namespace spdlog {
+namespace cfg {
+namespace helpers {
+//
+// Init levels from given string
+//
+// Examples:
+//
+// set global level to debug: "debug"
+// turn off all logging except for logger1: "off,logger1=debug"
+// turn off all logging except for logger1 and logger2: "off,logger1=debug,logger2=info"
+//
+SPDLOG_API void load_levels(const std::string &txt);
+} // namespace helpers
+
+} // namespace cfg
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "helpers-inl.h"
+#endif // SPDLOG_HEADER_ONLY
diff --git a/include/spdlog/common-inl.h b/include/spdlog/common-inl.h
new file mode 100644
index 00000000..378efe60
--- /dev/null
+++ b/include/spdlog/common-inl.h
@@ -0,0 +1,82 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/common.h>
+#endif
+
+namespace spdlog {
+namespace level {
+
+static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
+
+static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES;
+
+SPDLOG_INLINE const string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
+{
+ return level_string_views[l];
+}
+
+SPDLOG_INLINE void set_string_view(spdlog::level::level_enum l, const string_view_t &s) SPDLOG_NOEXCEPT
+{
+ level_string_views[l] = s;
+}
+
+SPDLOG_INLINE const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT
+{
+ return short_level_names[l];
+}
+
+SPDLOG_INLINE spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT
+{
+ int level = 0;
+ for (const auto &level_str : level_string_views)
+ {
+ if (level_str == name)
+ {
+ return static_cast<level::level_enum>(level);
+ }
+ level++;
+ }
+ // check also for "warn" and "err" before giving up..
+ if (name == "warn")
+ {
+ return level::warn;
+ }
+ if (name == "err")
+ {
+ return level::err;
+ }
+ return level::off;
+}
+} // namespace level
+
+SPDLOG_INLINE spdlog_ex::spdlog_ex(std::string msg)
+ : msg_(std::move(msg))
+{}
+
+SPDLOG_INLINE spdlog_ex::spdlog_ex(const std::string &msg, int last_errno)
+{
+ memory_buf_t outbuf;
+ fmt::format_system_error(outbuf, last_errno, msg);
+ msg_ = fmt::to_string(outbuf);
+}
+
+SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT
+{
+ return msg_.c_str();
+}
+
+SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno)
+{
+ SPDLOG_THROW(spdlog_ex(msg, last_errno));
+}
+
+SPDLOG_INLINE void throw_spdlog_ex(std::string msg)
+{
+ SPDLOG_THROW(spdlog_ex(std::move(msg)));
+}
+
+} // namespace spdlog
diff --git a/include/spdlog/common.h b/include/spdlog/common.h
new file mode 100644
index 00000000..fb9a3660
--- /dev/null
+++ b/include/spdlog/common.h
@@ -0,0 +1,249 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/tweakme.h>
+#include <spdlog/details/null_mutex.h>
+
+#include <atomic>
+#include <chrono>
+#include <initializer_list>
+#include <memory>
+#include <exception>
+#include <string>
+#include <type_traits>
+#include <functional>
+
+#ifdef SPDLOG_COMPILED_LIB
+#undef SPDLOG_HEADER_ONLY
+#if defined(_WIN32) && defined(SPDLOG_SHARED_LIB)
+#ifdef spdlog_EXPORTS
+#define SPDLOG_API __declspec(dllexport)
+#else
+#define SPDLOG_API __declspec(dllimport)
+#endif
+#else // !defined(_WIN32) || !defined(SPDLOG_SHARED_LIB)
+#define SPDLOG_API
+#endif
+#define SPDLOG_INLINE
+#else // !defined(SPDLOG_COMPILED_LIB)
+#define SPDLOG_API
+#define SPDLOG_HEADER_ONLY
+#define SPDLOG_INLINE inline
+#endif // #ifdef SPDLOG_COMPILED_LIB
+
+#include <spdlog/fmt/fmt.h>
+
+// visual studio upto 2013 does not support noexcept nor constexpr
+#if defined(_MSC_VER) && (_MSC_VER < 1900)
+#define SPDLOG_NOEXCEPT _NOEXCEPT
+#define SPDLOG_CONSTEXPR
+#else
+#define SPDLOG_NOEXCEPT noexcept
+#define SPDLOG_CONSTEXPR constexpr
+#endif
+
+#if defined(__GNUC__) || defined(__clang__)
+#define SPDLOG_DEPRECATED __attribute__((deprecated))
+#elif defined(_MSC_VER)
+#define SPDLOG_DEPRECATED __declspec(deprecated)
+#else
+#define SPDLOG_DEPRECATED
+#endif
+
+// disable thread local on msvc 2013
+#ifndef SPDLOG_NO_TLS
+#if (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt)
+#define SPDLOG_NO_TLS 1
+#endif
+#endif
+
+#ifndef SPDLOG_FUNCTION
+#define SPDLOG_FUNCTION static_cast<const char *>(__FUNCTION__)
+#endif
+
+#ifdef SPDLOG_NO_EXCEPTIONS
+#define SPDLOG_TRY
+#define SPDLOG_THROW(ex) \
+ do \
+ { \
+ printf("spdlog fatal error: %s\n", ex.what()); \
+ std::abort(); \
+ } while (0)
+#define SPDLOG_CATCH_ALL()
+#else
+#define SPDLOG_TRY try
+#define SPDLOG_THROW(ex) throw(ex)
+#define SPDLOG_CATCH_ALL() catch (...)
+#endif
+
+namespace spdlog {
+
+class formatter;
+
+namespace sinks {
+class sink;
+}
+
+#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
+using filename_t = std::wstring;
+// allow macro expansion to occur in SPDLOG_FILENAME_T
+#define SPDLOG_FILENAME_T_INNER(s) L##s
+#define SPDLOG_FILENAME_T(s) SPDLOG_FILENAME_T_INNER(s)
+#else
+using filename_t = std::string;
+#define SPDLOG_FILENAME_T(s) s
+#endif
+
+using log_clock = std::chrono::system_clock;
+using sink_ptr = std::shared_ptr<sinks::sink>;
+using sinks_init_list = std::initializer_list<sink_ptr>;
+using err_handler = std::function<void(const std::string &err_msg)>;
+using string_view_t = fmt::basic_string_view<char>;
+using wstring_view_t = fmt::basic_string_view<wchar_t>;
+using memory_buf_t = fmt::basic_memory_buffer<char, 250>;
+using wmemory_buf_t = fmt::basic_memory_buffer<wchar_t, 250>;
+
+#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
+#ifndef _WIN32
+#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
+#else
+template<typename T>
+struct is_convertible_to_wstring_view : std::is_convertible<T, wstring_view_t>
+{};
+#endif // _WIN32
+#else
+template<typename>
+struct is_convertible_to_wstring_view : std::false_type
+{};
+#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
+
+#if defined(SPDLOG_NO_ATOMIC_LEVELS)
+using level_t = details::null_atomic_int;
+#else
+using level_t = std::atomic<int>;
+#endif
+
+#define SPDLOG_LEVEL_TRACE 0
+#define SPDLOG_LEVEL_DEBUG 1
+#define SPDLOG_LEVEL_INFO 2
+#define SPDLOG_LEVEL_WARN 3
+#define SPDLOG_LEVEL_ERROR 4
+#define SPDLOG_LEVEL_CRITICAL 5
+#define SPDLOG_LEVEL_OFF 6
+
+#if !defined(SPDLOG_ACTIVE_LEVEL)
+#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
+#endif
+
+// Log level enum
+namespace level {
+enum level_enum
+{
+ trace = SPDLOG_LEVEL_TRACE,
+ debug = SPDLOG_LEVEL_DEBUG,
+ info = SPDLOG_LEVEL_INFO,
+ warn = SPDLOG_LEVEL_WARN,
+ err = SPDLOG_LEVEL_ERROR,
+ critical = SPDLOG_LEVEL_CRITICAL,
+ off = SPDLOG_LEVEL_OFF,
+ n_levels
+};
+
+#if !defined(SPDLOG_LEVEL_NAMES)
+#define SPDLOG_LEVEL_NAMES \
+ { \
+ "trace", "debug", "info", "warning", "error", "critical", "off" \
+ }
+#endif
+
+#if !defined(SPDLOG_SHORT_LEVEL_NAMES)
+
+#define SPDLOG_SHORT_LEVEL_NAMES \
+ { \
+ "T", "D", "I", "W", "E", "C", "O" \
+ }
+#endif
+
+SPDLOG_API const string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
+SPDLOG_API void set_string_view(spdlog::level::level_enum l, const string_view_t &s) SPDLOG_NOEXCEPT;
+SPDLOG_API const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
+SPDLOG_API spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT;
+
+} // namespace level
+
+//
+// Color mode used by sinks with color support.
+//
+enum class color_mode
+{
+ always,
+ automatic,
+ never
+};
+
+//
+// Pattern time - specific time getting to use for pattern_formatter.
+// local time by default
+//
+enum class pattern_time_type
+{
+ local, // log localtime
+ utc // log utc
+};
+
+//
+// Log exception
+//
+class SPDLOG_API spdlog_ex : public std::exception
+{
+public:
+ explicit spdlog_ex(std::string msg);
+ spdlog_ex(const std::string &msg, int last_errno);
+ const char *what() const SPDLOG_NOEXCEPT override;
+
+private:
+ std::string msg_;
+};
+
+[[noreturn]] SPDLOG_API void throw_spdlog_ex(const std::string &msg, int last_errno);
+[[noreturn]] SPDLOG_API void throw_spdlog_ex(std::string msg);
+
+struct source_loc
+{
+ SPDLOG_CONSTEXPR source_loc() = default;
+ SPDLOG_CONSTEXPR source_loc(const char *filename_in, int line_in, const char *funcname_in)
+ : filename{filename_in}
+ , line{line_in}
+ , funcname{funcname_in}
+ {}
+
+ SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT
+ {
+ return line == 0;
+ }
+ const char *filename{nullptr};
+ int line{0};
+ const char *funcname{nullptr};
+};
+
+namespace details {
+// make_unique support for pre c++14
+
+#if __cplusplus >= 201402L // C++14 and beyond
+using std::make_unique;
+#else
+template<typename T, typename... Args>
+std::unique_ptr<T> make_unique(Args &&...args)
+{
+ static_assert(!std::is_array<T>::value, "arrays not supported");
+ return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+#endif
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "common-inl.h"
+#endif
diff --git a/include/spdlog/details/backtracer-inl.h b/include/spdlog/details/backtracer-inl.h
new file mode 100644
index 00000000..21553c26
--- /dev/null
+++ b/include/spdlog/details/backtracer-inl.h
@@ -0,0 +1,69 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/backtracer.h>
+#endif
+namespace spdlog {
+namespace details {
+SPDLOG_INLINE backtracer::backtracer(const backtracer &other)
+{
+ std::lock_guard<std::mutex> lock(other.mutex_);
+ enabled_ = other.enabled();
+ messages_ = other.messages_;
+}
+
+SPDLOG_INLINE backtracer::backtracer(backtracer &&other) SPDLOG_NOEXCEPT
+{
+ std::lock_guard<std::mutex> lock(other.mutex_);
+ enabled_ = other.enabled();
+ messages_ = std::move(other.messages_);
+}
+
+SPDLOG_INLINE backtracer &backtracer::operator=(backtracer other)
+{
+ std::lock_guard<std::mutex> lock(mutex_);
+ enabled_ = other.enabled();
+ messages_ = std::move(other.messages_);
+ return *this;
+}
+
+SPDLOG_INLINE void backtracer::enable(size_t size)
+{
+ std::lock_guard<std::mutex> lock{mutex_};
+ enabled_.store(true, std::memory_order_relaxed);
+ messages_ = circular_q<log_msg_buffer>{size};
+}
+
+SPDLOG_INLINE void backtracer::disable()
+{
+ std::lock_guard<std::mutex> lock{mutex_};
+ enabled_.store(false, std::memory_order_relaxed);
+}
+
+SPDLOG_INLINE bool backtracer::enabled() const
+{
+ return enabled_.load(std::memory_order_relaxed);
+}
+
+SPDLOG_INLINE void backtracer::push_back(const log_msg &msg)
+{
+ std::lock_guard<std::mutex> lock{mutex_};
+ messages_.push_back(log_msg_buffer{msg});
+}
+
+// pop all items in the q and apply the given fun on each of them.
+SPDLOG_INLINE void backtracer::foreach_pop(std::function<void(const details::log_msg &)> fun)
+{
+ std::lock_guard<std::mutex> lock{mutex_};
+ while (!messages_.empty())
+ {
+ auto &front_msg = messages_.front();
+ fun(front_msg);
+ messages_.pop_front();
+ }
+}
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/backtracer.h b/include/spdlog/details/backtracer.h
new file mode 100644
index 00000000..1da5d4c7
--- /dev/null
+++ b/include/spdlog/details/backtracer.h
@@ -0,0 +1,45 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/log_msg_buffer.h>
+#include <spdlog/details/circular_q.h>
+
+#include <atomic>
+#include <mutex>
+#include <functional>
+
+// Store log messages in circular buffer.
+// Useful for storing debug data in case of error/warning happens.
+
+namespace spdlog {
+namespace details {
+class SPDLOG_API backtracer
+{
+ mutable std::mutex mutex_;
+ std::atomic<bool> enabled_{false};
+ circular_q<log_msg_buffer> messages_;
+
+public:
+ backtracer() = default;
+ backtracer(const backtracer &other);
+
+ backtracer(backtracer &&other) SPDLOG_NOEXCEPT;
+ backtracer &operator=(backtracer other);
+
+ void enable(size_t size);
+ void disable();
+ bool enabled() const;
+ void push_back(const log_msg &msg);
+
+ // pop all items in the q and apply the given fun on each of them.
+ void foreach_pop(std::function<void(const details::log_msg &)> fun);
+};
+
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "backtracer-inl.h"
+#endif
diff --git a/include/spdlog/details/circular_q.h b/include/spdlog/details/circular_q.h
new file mode 100644
index 00000000..1f2712e7
--- /dev/null
+++ b/include/spdlog/details/circular_q.h
@@ -0,0 +1,141 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+// circular q view of std::vector.
+#pragma once
+
+#include <vector>
+#include <cassert>
+
+namespace spdlog {
+namespace details {
+template<typename T>
+class circular_q
+{
+ size_t max_items_ = 0;
+ typename std::vector<T>::size_type head_ = 0;
+ typename std::vector<T>::size_type tail_ = 0;
+ size_t overrun_counter_ = 0;
+ std::vector<T> v_;
+
+public:
+ using value_type = T;
+
+ // empty ctor - create a disabled queue with no elements allocated at all
+ circular_q() = default;
+
+ explicit circular_q(size_t max_items)
+ : max_items_(max_items + 1) // one item is reserved as marker for full q
+ , v_(max_items_)
+ {}
+
+ circular_q(const circular_q &) = default;
+ circular_q &operator=(const circular_q &) = default;
+
+ // move cannot be default,
+ // since we need to reset head_, tail_, etc to zero in the moved object
+ circular_q(circular_q &&other) SPDLOG_NOEXCEPT
+ {
+ copy_moveable(std::move(other));
+ }
+
+ circular_q &operator=(circular_q &&other) SPDLOG_NOEXCEPT
+ {
+ copy_moveable(std::move(other));
+ return *this;
+ }
+
+ // push back, overrun (oldest) item if no room left
+ void push_back(T &&item)
+ {
+ if (max_items_ > 0)
+ {
+ v_[tail_] = std::move(item);
+ tail_ = (tail_ + 1) % max_items_;
+
+ if (tail_ == head_) // overrun last item if full
+ {
+ head_ = (head_ + 1) % max_items_;
+ ++overrun_counter_;
+ }
+ }
+ }
+
+ // Return reference to the front item.
+ // If there are no elements in the container, the behavior is undefined.
+ const T &front() const
+ {
+ return v_[head_];
+ }
+
+ T &front()
+ {
+ return v_[head_];
+ }
+
+ // Return number of elements actually stored
+ size_t size() const
+ {
+ if (tail_ >= head_)
+ {
+ return tail_ - head_;
+ }
+ else
+ {
+ return max_items_ - (head_ - tail_);
+ }
+ }
+
+ // Return const reference to item by index.
+ // If index is out of range 0…size()-1, the behavior is undefined.
+ const T &at(size_t i) const
+ {
+ assert(i < size());
+ return v_[(head_ + i) % max_items_];
+ }
+
+ // Pop item from front.
+ // If there are no elements in the container, the behavior is undefined.
+ void pop_front()
+ {
+ head_ = (head_ + 1) % max_items_;
+ }
+
+ bool empty() const
+ {
+ return tail_ == head_;
+ }
+
+ bool full() const
+ {
+ // head is ahead of the tail by 1
+ if (max_items_ > 0)
+ {
+ return ((tail_ + 1) % max_items_) == head_;
+ }
+ return false;
+ }
+
+ size_t overrun_counter() const
+ {
+ return overrun_counter_;
+ }
+
+private:
+ // copy from other&& and reset it to disabled state
+ void copy_moveable(circular_q &&other) SPDLOG_NOEXCEPT
+ {
+ max_items_ = other.max_items_;
+ head_ = other.head_;
+ tail_ = other.tail_;
+ overrun_counter_ = other.overrun_counter_;
+ v_ = std::move(other.v_);
+
+ // put &&other in disabled, but valid state
+ other.max_items_ = 0;
+ other.head_ = other.tail_ = 0;
+ other.overrun_counter_ = 0;
+ }
+};
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/console_globals.h b/include/spdlog/details/console_globals.h
new file mode 100644
index 00000000..665201dd
--- /dev/null
+++ b/include/spdlog/details/console_globals.h
@@ -0,0 +1,32 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/null_mutex.h>
+#include <mutex>
+
+namespace spdlog {
+namespace details {
+
+struct console_mutex
+{
+ using mutex_t = std::mutex;
+ static mutex_t &mutex()
+ {
+ static mutex_t s_mutex;
+ return s_mutex;
+ }
+};
+
+struct console_nullmutex
+{
+ using mutex_t = null_mutex;
+ static mutex_t &mutex()
+ {
+ static mutex_t s_mutex;
+ return s_mutex;
+ }
+};
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/file_helper-inl.h b/include/spdlog/details/file_helper-inl.h
new file mode 100644
index 00000000..30f3cf55
--- /dev/null
+++ b/include/spdlog/details/file_helper-inl.h
@@ -0,0 +1,147 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/file_helper.h>
+#endif
+
+#include <spdlog/details/os.h>
+#include <spdlog/common.h>
+
+#include <cerrno>
+#include <chrono>
+#include <cstdio>
+#include <string>
+#include <thread>
+#include <tuple>
+
+namespace spdlog {
+namespace details {
+
+SPDLOG_INLINE file_helper::~file_helper()
+{
+ close();
+}
+
+SPDLOG_INLINE void file_helper::open(const filename_t &fname, bool truncate)
+{
+ close();
+ filename_ = fname;
+
+ auto *mode = SPDLOG_FILENAME_T("ab");
+ auto *trunc_mode = SPDLOG_FILENAME_T("wb");
+
+ for (int tries = 0; tries < open_tries_; ++tries)
+ {
+ // create containing folder if not exists already.
+ os::create_dir(os::dir_name(fname));
+ if (truncate)
+ {
+ // Truncate by opening-and-closing a tmp file in "wb" mode, always
+ // opening the actual log-we-write-to in "ab" mode, since that
+ // interacts more politely with eternal processes that might
+ // rotate/truncate the file underneath us.
+ std::FILE *tmp;
+ if (os::fopen_s(&tmp, fname, trunc_mode))
+ {
+ continue;
+ }
+ std::fclose(tmp);
+ }
+ if (!os::fopen_s(&fd_, fname, mode))
+ {
+ return;
+ }
+
+ details::os::sleep_for_millis(open_interval_);
+ }
+
+ throw_spdlog_ex("Failed opening file " + os::filename_to_str(filename_) + " for writing", errno);
+}
+
+SPDLOG_INLINE void file_helper::reopen(bool truncate)
+{
+ if (filename_.empty())
+ {
+ throw_spdlog_ex("Failed re opening file - was not opened before");
+ }
+ this->open(filename_, truncate);
+}
+
+SPDLOG_INLINE void file_helper::flush()
+{
+ std::fflush(fd_);
+}
+
+SPDLOG_INLINE void file_helper::close()
+{
+ if (fd_ != nullptr)
+ {
+ std::fclose(fd_);
+ fd_ = nullptr;
+ }
+}
+
+SPDLOG_INLINE void file_helper::write(const memory_buf_t &buf)
+{
+ size_t msg_size = buf.size();
+ auto data = buf.data();
+ if (std::fwrite(data, 1, msg_size, fd_) != msg_size)
+ {
+ throw_spdlog_ex("Failed writing to file " + os::filename_to_str(filename_), errno);
+ }
+}
+
+SPDLOG_INLINE size_t file_helper::size() const
+{
+ if (fd_ == nullptr)
+ {
+ throw_spdlog_ex("Cannot use size() on closed file " + os::filename_to_str(filename_));
+ }
+ return os::filesize(fd_);
+}
+
+SPDLOG_INLINE const filename_t &file_helper::filename() const
+{
+ return filename_;
+}
+
+//
+// return file path and its extension:
+//
+// "mylog.txt" => ("mylog", ".txt")
+// "mylog" => ("mylog", "")
+// "mylog." => ("mylog.", "")
+// "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt")
+//
+// the starting dot in filenames is ignored (hidden files):
+//
+// ".mylog" => (".mylog". "")
+// "my_folder/.mylog" => ("my_folder/.mylog", "")
+// "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
+SPDLOG_INLINE std::tuple<filename_t, filename_t> file_helper::split_by_extension(const filename_t &fname)
+{
+ auto ext_index = fname.rfind('.');
+
+ // no valid extension found - return whole path and empty string as
+ // extension
+ if (ext_index == filename_t::npos || ext_index == 0 || ext_index == fname.size() - 1)
+ {
+ return std::make_tuple(fname, filename_t());
+ }
+
+ // treat cases like "/etc/rc.d/somelogfile or "/abc/.hiddenfile"
+ auto folder_index = fname.find_last_of(details::os::folder_seps_filename);
+ if (folder_index != filename_t::npos && folder_index >= ext_index - 1)
+ {
+ return std::make_tuple(fname, filename_t());
+ }
+
+ // finally - return a valid base and extension tuple
+ return std::make_tuple(fname.substr(0, ext_index), fname.substr(ext_index));
+}
+
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/file_helper.h b/include/spdlog/details/file_helper.h
new file mode 100644
index 00000000..5395d9cb
--- /dev/null
+++ b/include/spdlog/details/file_helper.h
@@ -0,0 +1,59 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <tuple>
+
+namespace spdlog {
+namespace details {
+
+// Helper class for file sinks.
+// When failing to open a file, retry several times(5) with a delay interval(10 ms).
+// Throw spdlog_ex exception on errors.
+
+class SPDLOG_API file_helper
+{
+public:
+ explicit file_helper() = default;
+
+ file_helper(const file_helper &) = delete;
+ file_helper &operator=(const file_helper &) = delete;
+ ~file_helper();
+
+ void open(const filename_t &fname, bool truncate = false);
+ void reopen(bool truncate);
+ void flush();
+ void close();
+ void write(const memory_buf_t &buf);
+ size_t size() const;
+ const filename_t &filename() const;
+
+ //
+ // return file path and its extension:
+ //
+ // "mylog.txt" => ("mylog", ".txt")
+ // "mylog" => ("mylog", "")
+ // "mylog." => ("mylog.", "")
+ // "/dir1/dir2/mylog.txt" => ("/dir1/dir2/mylog", ".txt")
+ //
+ // the starting dot in filenames is ignored (hidden files):
+ //
+ // ".mylog" => (".mylog". "")
+ // "my_folder/.mylog" => ("my_folder/.mylog", "")
+ // "my_folder/.mylog.txt" => ("my_folder/.mylog", ".txt")
+ static std::tuple<filename_t, filename_t> split_by_extension(const filename_t &fname);
+
+private:
+ const int open_tries_ = 5;
+ const int open_interval_ = 10;
+ std::FILE *fd_{nullptr};
+ filename_t filename_;
+};
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "file_helper-inl.h"
+#endif
diff --git a/include/spdlog/details/fmt_helper.h b/include/spdlog/details/fmt_helper.h
new file mode 100644
index 00000000..5dc311a0
--- /dev/null
+++ b/include/spdlog/details/fmt_helper.h
@@ -0,0 +1,116 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+#pragma once
+
+#include <chrono>
+#include <type_traits>
+#include <spdlog/fmt/fmt.h>
+#include <spdlog/common.h>
+
+// Some fmt helpers to efficiently format and pad ints and strings
+namespace spdlog {
+namespace details {
+namespace fmt_helper {
+
+inline spdlog::string_view_t to_string_view(const memory_buf_t &buf) SPDLOG_NOEXCEPT
+{
+ return spdlog::string_view_t{buf.data(), buf.size()};
+}
+
+inline void append_string_view(spdlog::string_view_t view, memory_buf_t &dest)
+{
+ auto *buf_ptr = view.data();
+ dest.append(buf_ptr, buf_ptr + view.size());
+}
+
+template<typename T>
+inline void append_int(T n, memory_buf_t &dest)
+{
+ fmt::format_int i(n);
+ dest.append(i.data(), i.data() + i.size());
+}
+
+template<typename T>
+inline unsigned int count_digits(T n)
+{
+ using count_type = typename std::conditional<(sizeof(T) > sizeof(uint32_t)), uint64_t, uint32_t>::type;
+ return static_cast<unsigned int>(fmt::
+// fmt 7.0.0 renamed the internal namespace to detail.
+// See: https://github.com/fmtlib/fmt/issues/1538
+#if FMT_VERSION < 70000
+ internal
+#else
+ detail
+#endif
+ ::count_digits(static_cast<count_type>(n)));
+}
+
+inline void pad2(int n, memory_buf_t &dest)
+{
+ if (n >= 0 && n < 100) // 0-99
+ {
+ dest.push_back(static_cast<char>('0' + n / 10));
+ dest.push_back(static_cast<char>('0' + n % 10));
+ }
+ else // unlikely, but just in case, let fmt deal with it
+ {
+ fmt::format_to(dest, "{:02}", n);
+ }
+}
+
+template<typename T>
+inline void pad_uint(T n, unsigned int width, memory_buf_t &dest)
+{
+ static_assert(std::is_unsigned<T>::value, "pad_uint must get unsigned T");
+ for (auto digits = count_digits(n); digits < width; digits++)
+ {
+ dest.push_back('0');
+ }
+ append_int(n, dest);
+}
+
+template<typename T>
+inline void pad3(T n, memory_buf_t &dest)
+{
+ static_assert(std::is_unsigned<T>::value, "pad3 must get unsigned T");
+ if (n < 1000)
+ {
+ dest.push_back(static_cast<char>(n / 100 + '0'));
+ n = n % 100;
+ dest.push_back(static_cast<char>((n / 10) + '0'));
+ dest.push_back(static_cast<char>((n % 10) + '0'));
+ }
+ else
+ {
+ append_int(n, dest);
+ }
+}
+
+template<typename T>
+inline void pad6(T n, memory_buf_t &dest)
+{
+ pad_uint(n, 6, dest);
+}
+
+template<typename T>
+inline void pad9(T n, memory_buf_t &dest)
+{
+ pad_uint(n, 9, dest);
+}
+
+// return fraction of a second of the given time_point.
+// e.g.
+// fraction<std::milliseconds>(tp) -> will return the millis part of the second
+template<typename ToDuration>
+inline ToDuration time_fraction(log_clock::time_point tp)
+{
+ using std::chrono::duration_cast;
+ using std::chrono::seconds;
+ auto duration = tp.time_since_epoch();
+ auto secs = duration_cast<seconds>(duration);
+ return duration_cast<ToDuration>(duration) - duration_cast<ToDuration>(secs);
+}
+
+} // namespace fmt_helper
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/log_msg-inl.h b/include/spdlog/details/log_msg-inl.h
new file mode 100644
index 00000000..af11e0da
--- /dev/null
+++ b/include/spdlog/details/log_msg-inl.h
@@ -0,0 +1,37 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/log_msg.h>
+#endif
+
+#include <spdlog/details/os.h>
+
+namespace spdlog {
+namespace details {
+
+SPDLOG_INLINE log_msg::log_msg(spdlog::log_clock::time_point log_time, spdlog::source_loc loc, string_view_t a_logger_name,
+ spdlog::level::level_enum lvl, spdlog::string_view_t msg)
+ : logger_name(a_logger_name)
+ , level(lvl)
+ , time(log_time)
+#ifndef SPDLOG_NO_THREAD_ID
+ , thread_id(os::thread_id())
+#endif
+ , source(loc)
+ , payload(msg)
+{}
+
+SPDLOG_INLINE log_msg::log_msg(
+ spdlog::source_loc loc, string_view_t a_logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg)
+ : log_msg(os::now(), loc, a_logger_name, lvl, msg)
+{}
+
+SPDLOG_INLINE log_msg::log_msg(string_view_t a_logger_name, spdlog::level::level_enum lvl, spdlog::string_view_t msg)
+ : log_msg(os::now(), source_loc{}, a_logger_name, lvl, msg)
+{}
+
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/log_msg.h b/include/spdlog/details/log_msg.h
new file mode 100644
index 00000000..834ca4df
--- /dev/null
+++ b/include/spdlog/details/log_msg.h
@@ -0,0 +1,36 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <string>
+
+namespace spdlog {
+namespace details {
+struct SPDLOG_API log_msg
+{
+ log_msg() = default;
+ log_msg(log_clock::time_point log_time, source_loc loc, string_view_t logger_name, level::level_enum lvl, string_view_t msg);
+ log_msg(source_loc loc, string_view_t logger_name, level::level_enum lvl, string_view_t msg);
+ log_msg(string_view_t logger_name, level::level_enum lvl, string_view_t msg);
+ log_msg(const log_msg &other) = default;
+
+ string_view_t logger_name;
+ level::level_enum level{level::off};
+ log_clock::time_point time;
+ size_t thread_id{0};
+
+ // wrapping the formatted text with color (updated by pattern_formatter).
+ mutable size_t color_range_start{0};
+ mutable size_t color_range_end{0};
+
+ source_loc source;
+ string_view_t payload;
+};
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "log_msg-inl.h"
+#endif
diff --git a/include/spdlog/details/log_msg_buffer-inl.h b/include/spdlog/details/log_msg_buffer-inl.h
new file mode 100644
index 00000000..ca9429bb
--- /dev/null
+++ b/include/spdlog/details/log_msg_buffer-inl.h
@@ -0,0 +1,60 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/log_msg_buffer.h>
+#endif
+
+namespace spdlog {
+namespace details {
+
+SPDLOG_INLINE log_msg_buffer::log_msg_buffer(const log_msg &orig_msg)
+ : log_msg{orig_msg}
+{
+ buffer.append(logger_name.begin(), logger_name.end());
+ buffer.append(payload.begin(), payload.end());
+ update_string_views();
+}
+
+SPDLOG_INLINE log_msg_buffer::log_msg_buffer(const log_msg_buffer &other)
+ : log_msg{other}
+{
+ buffer.append(logger_name.begin(), logger_name.end());
+ buffer.append(payload.begin(), payload.end());
+ update_string_views();
+}
+
+SPDLOG_INLINE log_msg_buffer::log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT
+ : log_msg{other}
+ , buffer{std::move(other.buffer)}
+{
+ update_string_views();
+}
+
+SPDLOG_INLINE log_msg_buffer &log_msg_buffer::operator=(const log_msg_buffer &other)
+{
+ log_msg::operator=(other);
+ buffer.clear();
+ buffer.append(other.buffer.data(), other.buffer.data() + other.buffer.size());
+ update_string_views();
+ return *this;
+}
+
+SPDLOG_INLINE log_msg_buffer &log_msg_buffer::operator=(log_msg_buffer &&other) SPDLOG_NOEXCEPT
+{
+ log_msg::operator=(other);
+ buffer = std::move(other.buffer);
+ update_string_views();
+ return *this;
+}
+
+SPDLOG_INLINE void log_msg_buffer::update_string_views()
+{
+ logger_name = string_view_t{buffer.data(), logger_name.size()};
+ payload = string_view_t{buffer.data() + logger_name.size(), payload.size()};
+}
+
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/log_msg_buffer.h b/include/spdlog/details/log_msg_buffer.h
new file mode 100644
index 00000000..4410110f
--- /dev/null
+++ b/include/spdlog/details/log_msg_buffer.h
@@ -0,0 +1,33 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/log_msg.h>
+
+namespace spdlog {
+namespace details {
+
+// Extend log_msg with internal buffer to store its payload.
+// This is needed since log_msg holds string_views that points to stack data.
+
+class SPDLOG_API log_msg_buffer : public log_msg
+{
+ memory_buf_t buffer;
+ void update_string_views();
+
+public:
+ log_msg_buffer() = default;
+ explicit log_msg_buffer(const log_msg &orig_msg);
+ log_msg_buffer(const log_msg_buffer &other);
+ log_msg_buffer(log_msg_buffer &&other) SPDLOG_NOEXCEPT;
+ log_msg_buffer &operator=(const log_msg_buffer &other);
+ log_msg_buffer &operator=(log_msg_buffer &&other) SPDLOG_NOEXCEPT;
+};
+
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "log_msg_buffer-inl.h"
+#endif
diff --git a/include/spdlog/details/mpmc_blocking_q.h b/include/spdlog/details/mpmc_blocking_q.h
new file mode 100644
index 00000000..5c3cca76
--- /dev/null
+++ b/include/spdlog/details/mpmc_blocking_q.h
@@ -0,0 +1,126 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+// multi producer-multi consumer blocking queue.
+// enqueue(..) - will block until room found to put the new message.
+// enqueue_nowait(..) - will return immediately with false if no room left in
+// the queue.
+// dequeue_for(..) - will block until the queue is not empty or timeout have
+// passed.
+
+#include <spdlog/details/circular_q.h>
+
+#include <condition_variable>
+#include <mutex>
+
+namespace spdlog {
+namespace details {
+
+template<typename T>
+class mpmc_blocking_queue
+{
+public:
+ using item_type = T;
+ explicit mpmc_blocking_queue(size_t max_items)
+ : q_(max_items)
+ {}
+
+#ifndef __MINGW32__
+ // try to enqueue and block if no room left
+ void enqueue(T &&item)
+ {
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ pop_cv_.wait(lock, [this] { return !this->q_.full(); });
+ q_.push_back(std::move(item));
+ }
+ push_cv_.notify_one();
+ }
+
+ // enqueue immediately. overrun oldest message in the queue if no room left.
+ void enqueue_nowait(T &&item)
+ {
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ q_.push_back(std::move(item));
+ }
+ push_cv_.notify_one();
+ }
+
+ // try to dequeue item. if no item found. wait upto timeout and try again
+ // Return true, if succeeded dequeue item, false otherwise
+ bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration)
+ {
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); }))
+ {
+ return false;
+ }
+ popped_item = std::move(q_.front());
+ q_.pop_front();
+ }
+ pop_cv_.notify_one();
+ return true;
+ }
+
+#else
+ // apparently mingw deadlocks if the mutex is released before cv.notify_one(),
+ // so release the mutex at the very end each function.
+
+ // try to enqueue and block if no room left
+ void enqueue(T &&item)
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ pop_cv_.wait(lock, [this] { return !this->q_.full(); });
+ q_.push_back(std::move(item));
+ push_cv_.notify_one();
+ }
+
+ // enqueue immediately. overrun oldest message in the queue if no room left.
+ void enqueue_nowait(T &&item)
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ q_.push_back(std::move(item));
+ push_cv_.notify_one();
+ }
+
+ // try to dequeue item. if no item found. wait upto timeout and try again
+ // Return true, if succeeded dequeue item, false otherwise
+ bool dequeue_for(T &popped_item, std::chrono::milliseconds wait_duration)
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ if (!push_cv_.wait_for(lock, wait_duration, [this] { return !this->q_.empty(); }))
+ {
+ return false;
+ }
+ popped_item = std::move(q_.front());
+ q_.pop_front();
+ pop_cv_.notify_one();
+ return true;
+ }
+
+#endif
+
+ size_t overrun_counter()
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ return q_.overrun_counter();
+ }
+
+ size_t size()
+ {
+ std::unique_lock<std::mutex> lock(queue_mutex_);
+ return q_.size();
+ }
+
+private:
+ std::mutex queue_mutex_;
+ std::condition_variable push_cv_;
+ std::condition_variable pop_cv_;
+ spdlog::details::circular_q<T> q_;
+};
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/null_mutex.h b/include/spdlog/details/null_mutex.h
new file mode 100644
index 00000000..83533d4f
--- /dev/null
+++ b/include/spdlog/details/null_mutex.h
@@ -0,0 +1,49 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <atomic>
+#include <utility>
+// null, no cost dummy "mutex" and dummy "atomic" int
+
+namespace spdlog {
+namespace details {
+struct null_mutex
+{
+ void lock() const {}
+ void unlock() const {}
+ bool try_lock() const
+ {
+ return true;
+ }
+};
+
+struct null_atomic_int
+{
+ int value;
+ null_atomic_int() = default;
+
+ explicit null_atomic_int(int new_value)
+ : value(new_value)
+ {}
+
+ int load(std::memory_order = std::memory_order_relaxed) const
+ {
+ return value;
+ }
+
+ void store(int new_value, std::memory_order = std::memory_order_relaxed)
+ {
+ value = new_value;
+ }
+
+ int exchange(int new_value, std::memory_order = std::memory_order_relaxed)
+ {
+ std::swap(new_value, value);
+ return new_value; // return value before the call
+ }
+};
+
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/os-inl.h b/include/spdlog/details/os-inl.h
new file mode 100644
index 00000000..a701e13f
--- /dev/null
+++ b/include/spdlog/details/os-inl.h
@@ -0,0 +1,589 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/os.h>
+#endif
+
+#include <spdlog/common.h>
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <ctime>
+#include <string>
+#include <thread>
+#include <array>
+#include <sys/stat.h>
+#include <sys/types.h>
+
+#ifdef _WIN32
+
+#include <io.h> // _get_osfhandle and _isatty support
+#include <process.h> // _get_pid support
+#include <spdlog/details/windows_include.h>
+
+#ifdef __MINGW32__
+#include <share.h>
+#endif
+
+#if defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)
+#include <limits>
+#endif
+
+#include <direct.h> // for _mkdir/_wmkdir
+
+#else // unix
+
+#include <fcntl.h>
+#include <unistd.h>
+
+#ifdef __linux__
+#include <sys/syscall.h> //Use gettid() syscall under linux to get thread id
+
+#elif defined(_AIX)
+#include <pthread.h> // for pthread_getthreadid_np
+
+#elif defined(__DragonFly__) || defined(__FreeBSD__)
+#include <pthread_np.h> // for pthread_getthreadid_np
+
+#elif defined(__NetBSD__)
+#include <lwp.h> // for _lwp_self
+
+#elif defined(__sun)
+#include <thread.h> // for thr_self
+#endif
+
+#endif // unix
+
+#ifndef __has_feature // Clang - feature checking macros.
+#define __has_feature(x) 0 // Compatibility with non-clang compilers.
+#endif
+
+namespace spdlog {
+namespace details {
+namespace os {
+
+SPDLOG_INLINE spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT
+{
+
+#if defined __linux__ && defined SPDLOG_CLOCK_COARSE
+ timespec ts;
+ ::clock_gettime(CLOCK_REALTIME_COARSE, &ts);
+ return std::chrono::time_point<log_clock, typename log_clock::duration>(
+ std::chrono::duration_cast<typename log_clock::duration>(std::chrono::seconds(ts.tv_sec) + std::chrono::nanoseconds(ts.tv_nsec)));
+
+#else
+ return log_clock::now();
+#endif
+}
+SPDLOG_INLINE std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
+{
+
+#ifdef _WIN32
+ std::tm tm;
+ ::localtime_s(&tm, &time_tt);
+#else
+ std::tm tm;
+ ::localtime_r(&time_tt, &tm);
+#endif
+ return tm;
+}
+
+SPDLOG_INLINE std::tm localtime() SPDLOG_NOEXCEPT
+{
+ std::time_t now_t = ::time(nullptr);
+ return localtime(now_t);
+}
+
+SPDLOG_INLINE std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT
+{
+
+#ifdef _WIN32
+ std::tm tm;
+ ::gmtime_s(&tm, &time_tt);
+#else
+ std::tm tm;
+ ::gmtime_r(&time_tt, &tm);
+#endif
+ return tm;
+}
+
+SPDLOG_INLINE std::tm gmtime() SPDLOG_NOEXCEPT
+{
+ std::time_t now_t = ::time(nullptr);
+ return gmtime(now_t);
+}
+
+// fopen_s on non windows for writing
+SPDLOG_INLINE bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode)
+{
+#ifdef _WIN32
+#ifdef SPDLOG_WCHAR_FILENAMES
+ *fp = ::_wfsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
+#else
+ *fp = ::_fsopen((filename.c_str()), mode.c_str(), _SH_DENYNO);
+#endif
+#if defined(SPDLOG_PREVENT_CHILD_FD)
+ if (*fp != nullptr)
+ {
+ auto file_handle = reinterpret_cast<HANDLE>(_get_osfhandle(::_fileno(*fp)));
+ if (!::SetHandleInformation(file_handle, HANDLE_FLAG_INHERIT, 0))
+ {
+ ::fclose(*fp);
+ *fp = nullptr;
+ }
+ }
+#endif
+#else // unix
+#if defined(SPDLOG_PREVENT_CHILD_FD)
+ const int mode_flag = mode == SPDLOG_FILENAME_T("ab") ? O_APPEND : O_TRUNC;
+ const int fd = ::open((filename.c_str()), O_CREAT | O_WRONLY | O_CLOEXEC | mode_flag, mode_t(0644));
+ if (fd == -1)
+ {
+ return false;
+ }
+ *fp = ::fdopen(fd, mode.c_str());
+ if (*fp == nullptr)
+ {
+ ::close(fd);
+ }
+#else
+ *fp = ::fopen((filename.c_str()), mode.c_str());
+#endif
+#endif
+
+ return *fp == nullptr;
+}
+
+SPDLOG_INLINE int remove(const filename_t &filename) SPDLOG_NOEXCEPT
+{
+#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
+ return ::_wremove(filename.c_str());
+#else
+ return std::remove(filename.c_str());
+#endif
+}
+
+SPDLOG_INLINE int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT
+{
+ return path_exists(filename) ? remove(filename) : 0;
+}
+
+SPDLOG_INLINE int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT
+{
+#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
+ return ::_wrename(filename1.c_str(), filename2.c_str());
+#else
+ return std::rename(filename1.c_str(), filename2.c_str());
+#endif
+}
+
+// Return true if path exists (file or directory)
+SPDLOG_INLINE bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT
+{
+#ifdef _WIN32
+#ifdef SPDLOG_WCHAR_FILENAMES
+ auto attribs = ::GetFileAttributesW(filename.c_str());
+#else
+ auto attribs = ::GetFileAttributesA(filename.c_str());
+#endif
+ return attribs != INVALID_FILE_ATTRIBUTES;
+#else // common linux/unix all have the stat system call
+ struct stat buffer;
+ return (::stat(filename.c_str(), &buffer) == 0);
+#endif
+}
+
+// Return file size according to open FILE* object
+SPDLOG_INLINE size_t filesize(FILE *f)
+{
+ if (f == nullptr)
+ {
+ throw_spdlog_ex("Failed getting file size. fd is null");
+ }
+#if defined(_WIN32) && !defined(__CYGWIN__)
+ int fd = ::_fileno(f);
+#if _WIN64 // 64 bits
+ __int64 ret = ::_filelengthi64(fd);
+ if (ret >= 0)
+ {
+ return static_cast<size_t>(ret);
+ }
+
+#else // windows 32 bits
+ long ret = ::_filelength(fd);
+ if (ret >= 0)
+ {
+ return static_cast<size_t>(ret);
+ }
+#endif
+
+#else // unix
+// OpenBSD doesn't compile with :: before the fileno(..)
+#if defined(__OpenBSD__)
+ int fd = fileno(f);
+#else
+ int fd = ::fileno(f);
+#endif
+// 64 bits(but not in osx or cygwin, where fstat64 is deprecated)
+#if (defined(__linux__) || defined(__sun) || defined(_AIX)) && (defined(__LP64__) || defined(_LP64))
+ struct stat64 st;
+ if (::fstat64(fd, &st) == 0)
+ {
+ return static_cast<size_t>(st.st_size);
+ }
+#else // other unix or linux 32 bits or cygwin
+ struct stat st;
+ if (::fstat(fd, &st) == 0)
+ {
+ return static_cast<size_t>(st.st_size);
+ }
+#endif
+#endif
+ throw_spdlog_ex("Failed getting file size from fd", errno);
+ return 0; // will not be reached.
+}
+
+// Return utc offset in minutes or throw spdlog_ex on failure
+SPDLOG_INLINE int utc_minutes_offset(const std::tm &tm)
+{
+
+#ifdef _WIN32
+#if _WIN32_WINNT < _WIN32_WINNT_WS08
+ TIME_ZONE_INFORMATION tzinfo;
+ auto rv = ::GetTimeZoneInformation(&tzinfo);
+#else
+ DYNAMIC_TIME_ZONE_INFORMATION tzinfo;
+ auto rv = ::GetDynamicTimeZoneInformation(&tzinfo);
+#endif
+ if (rv == TIME_ZONE_ID_INVALID)
+ throw_spdlog_ex("Failed getting timezone info. ", errno);
+
+ int offset = -tzinfo.Bias;
+ if (tm.tm_isdst)
+ {
+ offset -= tzinfo.DaylightBias;
+ }
+ else
+ {
+ offset -= tzinfo.StandardBias;
+ }
+ return offset;
+#else
+
+#if defined(sun) || defined(__sun) || defined(_AIX) || (!defined(_BSD_SOURCE) && !defined(_GNU_SOURCE))
+ // 'tm_gmtoff' field is BSD extension and it's missing on SunOS/Solaris
+ struct helper
+ {
+ static long int calculate_gmt_offset(const std::tm &localtm = details::os::localtime(), const std::tm &gmtm = details::os::gmtime())
+ {
+ int local_year = localtm.tm_year + (1900 - 1);
+ int gmt_year = gmtm.tm_year + (1900 - 1);
+
+ long int days = (
+ // difference in day of year
+ localtm.tm_yday -
+ gmtm.tm_yday
+
+ // + intervening leap days
+ + ((local_year >> 2) - (gmt_year >> 2)) - (local_year / 100 - gmt_year / 100) +
+ ((local_year / 100 >> 2) - (gmt_year / 100 >> 2))
+
+ // + difference in years * 365 */
+ + (long int)(local_year - gmt_year) * 365);
+
+ long int hours = (24 * days) + (localtm.tm_hour - gmtm.tm_hour);
+ long int mins = (60 * hours) + (localtm.tm_min - gmtm.tm_min);
+ long int secs = (60 * mins) + (localtm.tm_sec - gmtm.tm_sec);
+
+ return secs;
+ }
+ };
+
+ auto offset_seconds = helper::calculate_gmt_offset(tm);
+#else
+ auto offset_seconds = tm.tm_gmtoff;
+#endif
+
+ return static_cast<int>(offset_seconds / 60);
+#endif
+}
+
+// Return current thread id as size_t
+// It exists because the std::this_thread::get_id() is much slower(especially
+// under VS 2013)
+SPDLOG_INLINE size_t _thread_id() SPDLOG_NOEXCEPT
+{
+#ifdef _WIN32
+ return static_cast<size_t>(::GetCurrentThreadId());
+#elif defined(__linux__)
+#if defined(__ANDROID__) && defined(__ANDROID_API__) && (__ANDROID_API__ < 21)
+#define SYS_gettid __NR_gettid
+#endif
+ return static_cast<size_t>(::syscall(SYS_gettid));
+#elif defined(_AIX) || defined(__DragonFly__) || defined(__FreeBSD__)
+ return static_cast<size_t>(::pthread_getthreadid_np());
+#elif defined(__NetBSD__)
+ return static_cast<size_t>(::_lwp_self());
+#elif defined(__OpenBSD__)
+ return static_cast<size_t>(::getthrid());
+#elif defined(__sun)
+ return static_cast<size_t>(::thr_self());
+#elif __APPLE__
+ uint64_t tid;
+ pthread_threadid_np(nullptr, &tid);
+ return static_cast<size_t>(tid);
+#else // Default to standard C++11 (other Unix)
+ return static_cast<size_t>(std::hash<std::thread::id>()(std::this_thread::get_id()));
+#endif
+}
+
+// Return current thread id as size_t (from thread local storage)
+SPDLOG_INLINE size_t thread_id() SPDLOG_NOEXCEPT
+{
+#if defined(SPDLOG_NO_TLS)
+ return _thread_id();
+#else // cache thread id in tls
+ static thread_local const size_t tid = _thread_id();
+ return tid;
+#endif
+}
+
+// This is avoid msvc issue in sleep_for that happens if the clock changes.
+// See https://github.com/gabime/spdlog/issues/609
+SPDLOG_INLINE void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT
+{
+#if defined(_WIN32)
+ ::Sleep(milliseconds);
+#else
+ std::this_thread::sleep_for(std::chrono::milliseconds(milliseconds));
+#endif
+}
+
+// wchar support for windows file names (SPDLOG_WCHAR_FILENAMES must be defined)
+#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
+SPDLOG_INLINE std::string filename_to_str(const filename_t &filename)
+{
+ memory_buf_t buf;
+ wstr_to_utf8buf(filename, buf);
+ return fmt::to_string(buf);
+}
+#else
+SPDLOG_INLINE std::string filename_to_str(const filename_t &filename)
+{
+ return filename;
+}
+#endif
+
+SPDLOG_INLINE int pid() SPDLOG_NOEXCEPT
+{
+
+#ifdef _WIN32
+ return static_cast<int>(::GetCurrentProcessId());
+#else
+ return static_cast<int>(::getpid());
+#endif
+}
+
+// Determine if the terminal supports colors
+// Based on: https://github.com/agauniyal/rang/
+SPDLOG_INLINE bool is_color_terminal() SPDLOG_NOEXCEPT
+{
+#ifdef _WIN32
+ return true;
+#else
+
+ static const bool result = []() {
+ const char *env_colorterm_p = std::getenv("COLORTERM");
+ if (env_colorterm_p != nullptr)
+ {
+ return true;
+ }
+
+ static constexpr std::array<const char *, 15> terms = {{"ansi", "color", "console", "cygwin", "gnome", "konsole", "kterm", "linux",
+ "msys", "putty", "rxvt", "screen", "vt100", "xterm", "alacritty"}};
+
+ const char *env_term_p = std::getenv("TERM");
+ if (env_term_p == nullptr)
+ {
+ return false;
+ }
+
+ return std::any_of(terms.begin(), terms.end(), [&](const char *term) { return std::strstr(env_term_p, term) != nullptr; });
+ }();
+
+ return result;
+#endif
+}
+
+// Determine if the terminal attached
+// Source: https://github.com/agauniyal/rang/
+SPDLOG_INLINE bool in_terminal(FILE *file) SPDLOG_NOEXCEPT
+{
+
+#ifdef _WIN32
+ return ::_isatty(_fileno(file)) != 0;
+#else
+ return ::isatty(fileno(file)) != 0;
+#endif
+}
+
+#if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
+SPDLOG_INLINE void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target)
+{
+ if (wstr.size() > static_cast<size_t>((std::numeric_limits<int>::max)()) / 2 - 1)
+ {
+ throw_spdlog_ex("UTF-16 string is too big to be converted to UTF-8");
+ }
+
+ int wstr_size = static_cast<int>(wstr.size());
+ if (wstr_size == 0)
+ {
+ target.resize(0);
+ return;
+ }
+
+ int result_size = static_cast<int>(target.capacity());
+ if ((wstr_size + 1) * 2 > result_size)
+ {
+ result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, NULL, 0, NULL, NULL);
+ }
+
+ if (result_size > 0)
+ {
+ target.resize(result_size);
+ result_size = ::WideCharToMultiByte(CP_UTF8, 0, wstr.data(), wstr_size, target.data(), result_size, NULL, NULL);
+
+ if (result_size > 0)
+ {
+ target.resize(result_size);
+ return;
+ }
+ }
+
+ throw_spdlog_ex(fmt::format("WideCharToMultiByte failed. Last error: {}", ::GetLastError()));
+}
+
+SPDLOG_INLINE void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target)
+{
+ if (str.size() > static_cast<size_t>((std::numeric_limits<int>::max)()) - 1)
+ {
+ throw_spdlog_ex("UTF-8 string is too big to be converted to UTF-16");
+ }
+
+ int str_size = static_cast<int>(str.size());
+ if (str_size == 0)
+ {
+ target.resize(0);
+ return;
+ }
+
+ int result_size = static_cast<int>(target.capacity());
+ if (str_size + 1 > result_size)
+ {
+ result_size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, NULL, 0);
+ }
+
+ if (result_size > 0)
+ {
+ target.resize(result_size);
+ result_size = ::MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, str.data(), str_size, target.data(), result_size);
+
+ if (result_size > 0)
+ {
+ target.resize(result_size);
+ return;
+ }
+ }
+
+ throw_spdlog_ex(fmt::format("MultiByteToWideChar failed. Last error: {}", ::GetLastError()));
+}
+#endif // (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
+
+// return true on success
+static SPDLOG_INLINE bool mkdir_(const filename_t &path)
+{
+#ifdef _WIN32
+#ifdef SPDLOG_WCHAR_FILENAMES
+ return ::_wmkdir(path.c_str()) == 0;
+#else
+ return ::_mkdir(path.c_str()) == 0;
+#endif
+#else
+ return ::mkdir(path.c_str(), mode_t(0755)) == 0;
+#endif
+}
+
+// create the given directory - and all directories leading to it
+// return true on success or if the directory already exists
+SPDLOG_INLINE bool create_dir(filename_t path)
+{
+ if (path_exists(path))
+ {
+ return true;
+ }
+
+ if (path.empty())
+ {
+ return false;
+ }
+
+ size_t search_offset = 0;
+ do
+ {
+ auto token_pos = path.find_first_of(folder_seps_filename, search_offset);
+ // treat the entire path as a folder if no folder separator not found
+ if (token_pos == filename_t::npos)
+ {
+ token_pos = path.size();
+ }
+
+ auto subdir = path.substr(0, token_pos);
+
+ if (!subdir.empty() && !path_exists(subdir) && !mkdir_(subdir))
+ {
+ return false; // return error if failed creating dir
+ }
+ search_offset = token_pos + 1;
+ } while (search_offset < path.size());
+
+ return true;
+}
+
+// Return directory name from given path or empty string
+// "abc/file" => "abc"
+// "abc/" => "abc"
+// "abc" => ""
+// "abc///" => "abc//"
+SPDLOG_INLINE filename_t dir_name(filename_t path)
+{
+ auto pos = path.find_last_of(folder_seps_filename);
+ return pos != filename_t::npos ? path.substr(0, pos) : filename_t{};
+}
+
+std::string SPDLOG_INLINE getenv(const char *field)
+{
+
+#if defined(_MSC_VER)
+#if defined(__cplusplus_winrt)
+ return std::string{}; // not supported under uwp
+#else
+ size_t len = 0;
+ char buf[128];
+ bool ok = ::getenv_s(&len, buf, sizeof(buf), field) == 0;
+ return ok ? buf : std::string{};
+#endif
+#else // revert to getenv
+ char *buf = ::getenv(field);
+ return buf ? buf : std::string{};
+#endif
+}
+
+} // namespace os
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/os.h b/include/spdlog/details/os.h
new file mode 100644
index 00000000..9fda1447
--- /dev/null
+++ b/include/spdlog/details/os.h
@@ -0,0 +1,118 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <ctime> // std::time_t
+
+namespace spdlog {
+namespace details {
+namespace os {
+
+SPDLOG_API spdlog::log_clock::time_point now() SPDLOG_NOEXCEPT;
+
+SPDLOG_API std::tm localtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
+
+SPDLOG_API std::tm localtime() SPDLOG_NOEXCEPT;
+
+SPDLOG_API std::tm gmtime(const std::time_t &time_tt) SPDLOG_NOEXCEPT;
+
+SPDLOG_API std::tm gmtime() SPDLOG_NOEXCEPT;
+
+// eol definition
+#if !defined(SPDLOG_EOL)
+#ifdef _WIN32
+#define SPDLOG_EOL "\r\n"
+#else
+#define SPDLOG_EOL "\n"
+#endif
+#endif
+
+SPDLOG_CONSTEXPR static const char *default_eol = SPDLOG_EOL;
+
+// folder separator
+#if !defined(SPDLOG_FOLDER_SEPS)
+#ifdef _WIN32
+#define SPDLOG_FOLDER_SEPS "\\/"
+#else
+#define SPDLOG_FOLDER_SEPS "/"
+#endif
+#endif
+
+SPDLOG_CONSTEXPR static const char folder_seps[] = SPDLOG_FOLDER_SEPS;
+SPDLOG_CONSTEXPR static const filename_t::value_type folder_seps_filename[] = SPDLOG_FILENAME_T(SPDLOG_FOLDER_SEPS);
+
+// fopen_s on non windows for writing
+SPDLOG_API bool fopen_s(FILE **fp, const filename_t &filename, const filename_t &mode);
+
+// Remove filename. return 0 on success
+SPDLOG_API int remove(const filename_t &filename) SPDLOG_NOEXCEPT;
+
+// Remove file if exists. return 0 on success
+// Note: Non atomic (might return failure to delete if concurrently deleted by other process/thread)
+SPDLOG_API int remove_if_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
+
+SPDLOG_API int rename(const filename_t &filename1, const filename_t &filename2) SPDLOG_NOEXCEPT;
+
+// Return if file exists.
+SPDLOG_API bool path_exists(const filename_t &filename) SPDLOG_NOEXCEPT;
+
+// Return file size according to open FILE* object
+SPDLOG_API size_t filesize(FILE *f);
+
+// Return utc offset in minutes or throw spdlog_ex on failure
+SPDLOG_API int utc_minutes_offset(const std::tm &tm = details::os::localtime());
+
+// Return current thread id as size_t
+// It exists because the std::this_thread::get_id() is much slower(especially
+// under VS 2013)
+SPDLOG_API size_t _thread_id() SPDLOG_NOEXCEPT;
+
+// Return current thread id as size_t (from thread local storage)
+SPDLOG_API size_t thread_id() SPDLOG_NOEXCEPT;
+
+// This is avoid msvc issue in sleep_for that happens if the clock changes.
+// See https://github.com/gabime/spdlog/issues/609
+SPDLOG_API void sleep_for_millis(int milliseconds) SPDLOG_NOEXCEPT;
+
+SPDLOG_API std::string filename_to_str(const filename_t &filename);
+
+SPDLOG_API int pid() SPDLOG_NOEXCEPT;
+
+// Determine if the terminal supports colors
+// Source: https://github.com/agauniyal/rang/
+SPDLOG_API bool is_color_terminal() SPDLOG_NOEXCEPT;
+
+// Determine if the terminal attached
+// Source: https://github.com/agauniyal/rang/
+SPDLOG_API bool in_terminal(FILE *file) SPDLOG_NOEXCEPT;
+
+#if (defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT) || defined(SPDLOG_WCHAR_FILENAMES)) && defined(_WIN32)
+SPDLOG_API void wstr_to_utf8buf(wstring_view_t wstr, memory_buf_t &target);
+
+SPDLOG_API void utf8_to_wstrbuf(string_view_t str, wmemory_buf_t &target);
+#endif
+
+// Return directory name from given path or empty string
+// "abc/file" => "abc"
+// "abc/" => "abc"
+// "abc" => ""
+// "abc///" => "abc//"
+SPDLOG_API filename_t dir_name(filename_t path);
+
+// Create a dir from the given path.
+// Return true if succeeded or if this dir already exists.
+SPDLOG_API bool create_dir(filename_t path);
+
+// non thread safe, cross platform getenv/getenv_s
+// return empty string if field not found
+SPDLOG_API std::string getenv(const char *field);
+
+} // namespace os
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "os-inl.h"
+#endif
diff --git a/include/spdlog/details/periodic_worker-inl.h b/include/spdlog/details/periodic_worker-inl.h
new file mode 100644
index 00000000..1d794994
--- /dev/null
+++ b/include/spdlog/details/periodic_worker-inl.h
@@ -0,0 +1,49 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/periodic_worker.h>
+#endif
+
+namespace spdlog {
+namespace details {
+
+SPDLOG_INLINE periodic_worker::periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval)
+{
+ active_ = (interval > std::chrono::seconds::zero());
+ if (!active_)
+ {
+ return;
+ }
+
+ worker_thread_ = std::thread([this, callback_fun, interval]() {
+ for (;;)
+ {
+ std::unique_lock<std::mutex> lock(this->mutex_);
+ if (this->cv_.wait_for(lock, interval, [this] { return !this->active_; }))
+ {
+ return; // active_ == false, so exit this thread
+ }
+ callback_fun();
+ }
+ });
+}
+
+// stop the worker thread and join it
+SPDLOG_INLINE periodic_worker::~periodic_worker()
+{
+ if (worker_thread_.joinable())
+ {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ active_ = false;
+ }
+ cv_.notify_one();
+ worker_thread_.join();
+ }
+}
+
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/periodic_worker.h b/include/spdlog/details/periodic_worker.h
new file mode 100644
index 00000000..42373665
--- /dev/null
+++ b/include/spdlog/details/periodic_worker.h
@@ -0,0 +1,40 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+// periodic worker thread - periodically executes the given callback function.
+//
+// RAII over the owned thread:
+// creates the thread on construction.
+// stops and joins the thread on destruction (if the thread is executing a callback, wait for it to finish first).
+
+#include <chrono>
+#include <condition_variable>
+#include <functional>
+#include <mutex>
+#include <thread>
+namespace spdlog {
+namespace details {
+
+class SPDLOG_API periodic_worker
+{
+public:
+ periodic_worker(const std::function<void()> &callback_fun, std::chrono::seconds interval);
+ periodic_worker(const periodic_worker &) = delete;
+ periodic_worker &operator=(const periodic_worker &) = delete;
+ // stop the worker thread and join it
+ ~periodic_worker();
+
+private:
+ bool active_;
+ std::thread worker_thread_;
+ std::mutex mutex_;
+ std::condition_variable cv_;
+};
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "periodic_worker-inl.h"
+#endif
diff --git a/include/spdlog/details/registry-inl.h b/include/spdlog/details/registry-inl.h
new file mode 100644
index 00000000..a60faabc
--- /dev/null
+++ b/include/spdlog/details/registry-inl.h
@@ -0,0 +1,313 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/registry.h>
+#endif
+
+#include <spdlog/common.h>
+#include <spdlog/details/periodic_worker.h>
+#include <spdlog/logger.h>
+#include <spdlog/pattern_formatter.h>
+
+#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
+// support for the default stdout color logger
+#ifdef _WIN32
+#include <spdlog/sinks/wincolor_sink.h>
+#else
+#include <spdlog/sinks/ansicolor_sink.h>
+#endif
+#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
+
+#include <chrono>
+#include <functional>
+#include <memory>
+#include <string>
+#include <unordered_map>
+
+namespace spdlog {
+namespace details {
+
+SPDLOG_INLINE registry::registry()
+ : formatter_(new pattern_formatter())
+{
+
+#ifndef SPDLOG_DISABLE_DEFAULT_LOGGER
+ // create default logger (ansicolor_stdout_sink_mt or wincolor_stdout_sink_mt in windows).
+#ifdef _WIN32
+ auto color_sink = std::make_shared<sinks::wincolor_stdout_sink_mt>();
+#else
+ auto color_sink = std::make_shared<sinks::ansicolor_stdout_sink_mt>();
+#endif
+
+ const char *default_logger_name = "";
+ default_logger_ = std::make_shared<spdlog::logger>(default_logger_name, std::move(color_sink));
+ loggers_[default_logger_name] = default_logger_;
+
+#endif // SPDLOG_DISABLE_DEFAULT_LOGGER
+}
+
+SPDLOG_INLINE registry::~registry() = default;
+
+SPDLOG_INLINE void registry::register_logger(std::shared_ptr<logger> new_logger)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ register_logger_(std::move(new_logger));
+}
+
+SPDLOG_INLINE void registry::initialize_logger(std::shared_ptr<logger> new_logger)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ new_logger->set_formatter(formatter_->clone());
+
+ if (err_handler_)
+ {
+ new_logger->set_error_handler(err_handler_);
+ }
+
+ // set new level according to previously configured level or default level
+ auto it = log_levels_.find(new_logger->name());
+ auto new_level = it != log_levels_.end() ? it->second : global_log_level_;
+ new_logger->set_level(new_level);
+
+ new_logger->flush_on(flush_level_);
+
+ if (backtrace_n_messages_ > 0)
+ {
+ new_logger->enable_backtrace(backtrace_n_messages_);
+ }
+
+ if (automatic_registration_)
+ {
+ register_logger_(std::move(new_logger));
+ }
+}
+
+SPDLOG_INLINE std::shared_ptr<logger> registry::get(const std::string &logger_name)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ auto found = loggers_.find(logger_name);
+ return found == loggers_.end() ? nullptr : found->second;
+}
+
+SPDLOG_INLINE std::shared_ptr<logger> registry::default_logger()
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ return default_logger_;
+}
+
+// Return raw ptr to the default logger.
+// To be used directly by the spdlog default api (e.g. spdlog::info)
+// This make the default API faster, but cannot be used concurrently with set_default_logger().
+// e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
+SPDLOG_INLINE logger *registry::get_default_raw()
+{
+ return default_logger_.get();
+}
+
+// set default logger.
+// default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map.
+SPDLOG_INLINE void registry::set_default_logger(std::shared_ptr<logger> new_default_logger)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ // remove previous default logger from the map
+ if (default_logger_ != nullptr)
+ {
+ loggers_.erase(default_logger_->name());
+ }
+ if (new_default_logger != nullptr)
+ {
+ loggers_[new_default_logger->name()] = new_default_logger;
+ }
+ default_logger_ = std::move(new_default_logger);
+}
+
+SPDLOG_INLINE void registry::set_tp(std::shared_ptr<thread_pool> tp)
+{
+ std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
+ tp_ = std::move(tp);
+}
+
+SPDLOG_INLINE std::shared_ptr<thread_pool> registry::get_tp()
+{
+ std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
+ return tp_;
+}
+
+// Set global formatter. Each sink in each logger will get a clone of this object
+SPDLOG_INLINE void registry::set_formatter(std::unique_ptr<formatter> formatter)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ formatter_ = std::move(formatter);
+ for (auto &l : loggers_)
+ {
+ l.second->set_formatter(formatter_->clone());
+ }
+}
+
+SPDLOG_INLINE void registry::enable_backtrace(size_t n_messages)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ backtrace_n_messages_ = n_messages;
+
+ for (auto &l : loggers_)
+ {
+ l.second->enable_backtrace(n_messages);
+ }
+}
+
+SPDLOG_INLINE void registry::disable_backtrace()
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ backtrace_n_messages_ = 0;
+ for (auto &l : loggers_)
+ {
+ l.second->disable_backtrace();
+ }
+}
+
+SPDLOG_INLINE void registry::set_level(level::level_enum log_level)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ for (auto &l : loggers_)
+ {
+ l.second->set_level(log_level);
+ }
+ global_log_level_ = log_level;
+}
+
+SPDLOG_INLINE void registry::flush_on(level::level_enum log_level)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ for (auto &l : loggers_)
+ {
+ l.second->flush_on(log_level);
+ }
+ flush_level_ = log_level;
+}
+
+SPDLOG_INLINE void registry::flush_every(std::chrono::seconds interval)
+{
+ std::lock_guard<std::mutex> lock(flusher_mutex_);
+ auto clbk = [this]() { this->flush_all(); };
+ periodic_flusher_ = details::make_unique<periodic_worker>(clbk, interval);
+}
+
+SPDLOG_INLINE void registry::set_error_handler(void (*handler)(const std::string &msg))
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ for (auto &l : loggers_)
+ {
+ l.second->set_error_handler(handler);
+ }
+ err_handler_ = handler;
+}
+
+SPDLOG_INLINE void registry::apply_all(const std::function<void(const std::shared_ptr<logger>)> &fun)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ for (auto &l : loggers_)
+ {
+ fun(l.second);
+ }
+}
+
+SPDLOG_INLINE void registry::flush_all()
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ for (auto &l : loggers_)
+ {
+ l.second->flush();
+ }
+}
+
+SPDLOG_INLINE void registry::drop(const std::string &logger_name)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ loggers_.erase(logger_name);
+ if (default_logger_ && default_logger_->name() == logger_name)
+ {
+ default_logger_.reset();
+ }
+}
+
+SPDLOG_INLINE void registry::drop_all()
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ loggers_.clear();
+ default_logger_.reset();
+}
+
+// clean all resources and threads started by the registry
+SPDLOG_INLINE void registry::shutdown()
+{
+ {
+ std::lock_guard<std::mutex> lock(flusher_mutex_);
+ periodic_flusher_.reset();
+ }
+
+ drop_all();
+
+ {
+ std::lock_guard<std::recursive_mutex> lock(tp_mutex_);
+ tp_.reset();
+ }
+}
+
+SPDLOG_INLINE std::recursive_mutex &registry::tp_mutex()
+{
+ return tp_mutex_;
+}
+
+SPDLOG_INLINE void registry::set_automatic_registration(bool automatic_registration)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ automatic_registration_ = automatic_registration;
+}
+
+SPDLOG_INLINE void registry::set_levels(log_levels levels, level::level_enum *global_level)
+{
+ std::lock_guard<std::mutex> lock(logger_map_mutex_);
+ log_levels_ = std::move(levels);
+ auto global_level_requested = global_level != nullptr;
+ global_log_level_ = global_level_requested ? *global_level : global_log_level_;
+
+ for (auto &logger : loggers_)
+ {
+ auto logger_entry = log_levels_.find(logger.first);
+ if (logger_entry != log_levels_.end())
+ {
+ logger.second->set_level(logger_entry->second);
+ }
+ else if (global_level_requested)
+ {
+ logger.second->set_level(*global_level);
+ }
+ }
+}
+
+SPDLOG_INLINE registry &registry::instance()
+{
+ static registry s_instance;
+ return s_instance;
+}
+
+SPDLOG_INLINE void registry::throw_if_exists_(const std::string &logger_name)
+{
+ if (loggers_.find(logger_name) != loggers_.end())
+ {
+ throw_spdlog_ex("logger with name '" + logger_name + "' already exists");
+ }
+}
+
+SPDLOG_INLINE void registry::register_logger_(std::shared_ptr<logger> new_logger)
+{
+ auto logger_name = new_logger->name();
+ throw_if_exists_(logger_name);
+ loggers_[logger_name] = std::move(new_logger);
+}
+
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h
new file mode 100644
index 00000000..b069c3f5
--- /dev/null
+++ b/include/spdlog/details/registry.h
@@ -0,0 +1,115 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+// Loggers registry of unique name->logger pointer
+// An attempt to create a logger with an already existing name will result with spdlog_ex exception.
+// If user requests a non existing logger, nullptr will be returned
+// This class is thread safe
+
+#include <spdlog/common.h>
+
+#include <chrono>
+#include <functional>
+#include <memory>
+#include <string>
+#include <unordered_map>
+#include <mutex>
+
+namespace spdlog {
+class logger;
+
+namespace details {
+class thread_pool;
+class periodic_worker;
+
+class SPDLOG_API registry
+{
+public:
+ using log_levels = std::unordered_map<std::string, level::level_enum>;
+ registry(const registry &) = delete;
+ registry &operator=(const registry &) = delete;
+
+ void register_logger(std::shared_ptr<logger> new_logger);
+ void initialize_logger(std::shared_ptr<logger> new_logger);
+ std::shared_ptr<logger> get(const std::string &logger_name);
+ std::shared_ptr<logger> default_logger();
+
+ // Return raw ptr to the default logger.
+ // To be used directly by the spdlog default api (e.g. spdlog::info)
+ // This make the default API faster, but cannot be used concurrently with set_default_logger().
+ // e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
+ logger *get_default_raw();
+
+ // set default logger.
+ // default logger is stored in default_logger_ (for faster retrieval) and in the loggers_ map.
+ void set_default_logger(std::shared_ptr<logger> new_default_logger);
+
+ void set_tp(std::shared_ptr<thread_pool> tp);
+
+ std::shared_ptr<thread_pool> get_tp();
+
+ // Set global formatter. Each sink in each logger will get a clone of this object
+ void set_formatter(std::unique_ptr<formatter> formatter);
+
+ void enable_backtrace(size_t n_messages);
+
+ void disable_backtrace();
+
+ void set_level(level::level_enum log_level);
+
+ void flush_on(level::level_enum log_level);
+
+ void flush_every(std::chrono::seconds interval);
+
+ void set_error_handler(void (*handler)(const std::string &msg));
+
+ void apply_all(const std::function<void(const std::shared_ptr<logger>)> &fun);
+
+ void flush_all();
+
+ void drop(const std::string &logger_name);
+
+ void drop_all();
+
+ // clean all resources and threads started by the registry
+ void shutdown();
+
+ std::recursive_mutex &tp_mutex();
+
+ void set_automatic_registration(bool automatic_registration);
+
+ // set levels for all existing/future loggers. global_level can be null if should not set.
+ void set_levels(log_levels levels, level::level_enum *global_level);
+
+ static registry &instance();
+
+private:
+ registry();
+ ~registry();
+
+ void throw_if_exists_(const std::string &logger_name);
+ void register_logger_(std::shared_ptr<logger> new_logger);
+ bool set_level_from_cfg_(logger *logger);
+ std::mutex logger_map_mutex_, flusher_mutex_;
+ std::recursive_mutex tp_mutex_;
+ std::unordered_map<std::string, std::shared_ptr<logger>> loggers_;
+ log_levels log_levels_;
+ std::unique_ptr<formatter> formatter_;
+ spdlog::level::level_enum global_log_level_ = level::info;
+ level::level_enum flush_level_ = level::off;
+ void (*err_handler_)(const std::string &msg) = nullptr;
+ std::shared_ptr<thread_pool> tp_;
+ std::unique_ptr<periodic_worker> periodic_flusher_;
+ std::shared_ptr<logger> default_logger_;
+ bool automatic_registration_ = true;
+ size_t backtrace_n_messages_ = 0;
+};
+
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "registry-inl.h"
+#endif
diff --git a/include/spdlog/details/synchronous_factory.h b/include/spdlog/details/synchronous_factory.h
new file mode 100644
index 00000000..e1e42268
--- /dev/null
+++ b/include/spdlog/details/synchronous_factory.h
@@ -0,0 +1,24 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include "registry.h"
+
+namespace spdlog {
+
+// Default logger factory- creates synchronous loggers
+class logger;
+
+struct synchronous_factory
+{
+ template<typename Sink, typename... SinkArgs>
+ static std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs &&...args)
+ {
+ auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
+ auto new_logger = std::make_shared<spdlog::logger>(std::move(logger_name), std::move(sink));
+ details::registry::instance().initialize_logger(new_logger);
+ return new_logger;
+ }
+};
+} // namespace spdlog
diff --git a/include/spdlog/details/tcp_client-windows.h b/include/spdlog/details/tcp_client-windows.h
new file mode 100644
index 00000000..7ee72927
--- /dev/null
+++ b/include/spdlog/details/tcp_client-windows.h
@@ -0,0 +1,175 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#define WIN32_LEAN_AND_MEAN
+// tcp client helper
+#include <spdlog/common.h>
+#include <spdlog/details/os.h>
+
+#include <winsock2.h>
+#include <windows.h>
+#include <ws2tcpip.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <string>
+
+#pragma comment(lib, "Ws2_32.lib")
+#pragma comment(lib, "Mswsock.lib")
+#pragma comment(lib, "AdvApi32.lib")
+
+namespace spdlog {
+namespace details {
+class tcp_client
+{
+ SOCKET socket_ = INVALID_SOCKET;
+
+ static bool winsock_initialized_()
+ {
+ SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (s == INVALID_SOCKET)
+ {
+ return false;
+ }
+ else
+ {
+ closesocket(s);
+ return true;
+ }
+ }
+
+ static void init_winsock_()
+ {
+ WSADATA wsaData;
+ auto rv = WSAStartup(MAKEWORD(2, 2), &wsaData);
+ if (rv != 0)
+ {
+ throw_winsock_error_("WSAStartup failed", ::WSAGetLastError());
+ }
+ }
+
+ static void throw_winsock_error_(const std::string &msg, int last_error)
+ {
+ char buf[512];
+ ::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, last_error,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, (sizeof(buf) / sizeof(char)), NULL);
+
+ throw_spdlog_ex(fmt::format("tcp_sink - {}: {}", msg, buf));
+ }
+
+public:
+ bool is_connected() const
+ {
+ return socket_ != INVALID_SOCKET;
+ }
+
+ void close()
+ {
+ ::closesocket(socket_);
+ socket_ = INVALID_SOCKET;
+ WSACleanup();
+ }
+
+ SOCKET fd() const
+ {
+ return socket_;
+ }
+
+ ~tcp_client()
+ {
+ close();
+ }
+
+ // try to connect or throw on failure
+ void connect(const std::string &host, int port)
+ {
+ // initialize winsock if needed
+ if (!winsock_initialized_())
+ {
+ init_winsock_();
+ }
+
+ if (is_connected())
+ {
+ close();
+ }
+ struct addrinfo hints
+ {};
+ ZeroMemory(&hints, sizeof(hints));
+
+ hints.ai_family = AF_INET; // IPv4
+ hints.ai_socktype = SOCK_STREAM; // TCP
+ hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value
+ hints.ai_protocol = 0;
+
+ auto port_str = std::to_string(port);
+ struct addrinfo *addrinfo_result;
+ auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
+ int last_error = 0;
+ if (rv != 0)
+ {
+ last_error = ::WSAGetLastError();
+ WSACleanup();
+ throw_winsock_error_("getaddrinfo failed", last_error);
+ }
+
+ // Try each address until we successfully connect(2).
+
+ for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next)
+ {
+ socket_ = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
+ if (socket_ == INVALID_SOCKET)
+ {
+ last_error = ::WSAGetLastError();
+ WSACleanup();
+ continue;
+ }
+ if (::connect(socket_, rp->ai_addr, (int)rp->ai_addrlen) == 0)
+ {
+ break;
+ }
+ else
+ {
+ last_error = ::WSAGetLastError();
+ close();
+ }
+ }
+ ::freeaddrinfo(addrinfo_result);
+ if (socket_ == INVALID_SOCKET)
+ {
+ WSACleanup();
+ throw_winsock_error_("connect failed", last_error);
+ }
+
+ // set TCP_NODELAY
+ int enable_flag = 1;
+ ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (char *)&enable_flag, sizeof(enable_flag));
+ }
+
+ // Send exactly n_bytes of the given data.
+ // On error close the connection and throw.
+ void send(const char *data, size_t n_bytes)
+ {
+ size_t bytes_sent = 0;
+ while (bytes_sent < n_bytes)
+ {
+ const int send_flags = 0;
+ auto write_result = ::send(socket_, data + bytes_sent, (int)(n_bytes - bytes_sent), send_flags);
+ if (write_result == SOCKET_ERROR)
+ {
+ int last_error = ::WSAGetLastError();
+ close();
+ throw_winsock_error_("send failed", last_error);
+ }
+
+ if (write_result == 0) // (probably should not happen but in any case..)
+ {
+ break;
+ }
+ bytes_sent += static_cast<size_t>(write_result);
+ }
+ }
+};
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/tcp_client.h b/include/spdlog/details/tcp_client.h
new file mode 100644
index 00000000..9f3bb99e
--- /dev/null
+++ b/include/spdlog/details/tcp_client.h
@@ -0,0 +1,146 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifdef _WIN32
+#error include tcp_client-windows.h instead
+#endif
+
+// tcp client helper
+#include <spdlog/common.h>
+#include <spdlog/details/os.h>
+
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <unistd.h>
+#include <netdb.h>
+#include <netinet/tcp.h>
+
+#include <string>
+
+namespace spdlog {
+namespace details {
+class tcp_client
+{
+ int socket_ = -1;
+
+public:
+ bool is_connected() const
+ {
+ return socket_ != -1;
+ }
+
+ void close()
+ {
+ if (is_connected())
+ {
+ ::close(socket_);
+ socket_ = -1;
+ }
+ }
+
+ int fd() const
+ {
+ return socket_;
+ }
+
+ ~tcp_client()
+ {
+ close();
+ }
+
+ // try to connect or throw on failure
+ void connect(const std::string &host, int port)
+ {
+ close();
+ struct addrinfo hints
+ {};
+ memset(&hints, 0, sizeof(struct addrinfo));
+ hints.ai_family = AF_INET; // IPv4
+ hints.ai_socktype = SOCK_STREAM; // TCP
+ hints.ai_flags = AI_NUMERICSERV; // port passed as as numeric value
+ hints.ai_protocol = 0;
+
+ auto port_str = std::to_string(port);
+ struct addrinfo *addrinfo_result;
+ auto rv = ::getaddrinfo(host.c_str(), port_str.c_str(), &hints, &addrinfo_result);
+ if (rv != 0)
+ {
+ auto msg = fmt::format("::getaddrinfo failed: {}", gai_strerror(rv));
+ throw_spdlog_ex(msg);
+ }
+
+ // Try each address until we successfully connect(2).
+ int last_errno = 0;
+ for (auto *rp = addrinfo_result; rp != nullptr; rp = rp->ai_next)
+ {
+#if defined(SOCK_CLOEXEC)
+ const int flags = SOCK_CLOEXEC;
+#else
+ const int flags = 0;
+#endif
+ socket_ = ::socket(rp->ai_family, rp->ai_socktype | flags, rp->ai_protocol);
+ if (socket_ == -1)
+ {
+ last_errno = errno;
+ continue;
+ }
+ rv = ::connect(socket_, rp->ai_addr, rp->ai_addrlen);
+ if (rv == 0)
+ {
+ break;
+ }
+ last_errno = errno;
+ ::close(socket_);
+ socket_ = -1;
+ }
+ ::freeaddrinfo(addrinfo_result);
+ if (socket_ == -1)
+ {
+ throw_spdlog_ex("::connect failed", last_errno);
+ }
+
+ // set TCP_NODELAY
+ int enable_flag = 1;
+ ::setsockopt(socket_, IPPROTO_TCP, TCP_NODELAY, (char *)&enable_flag, sizeof(enable_flag));
+
+ // prevent sigpipe on systems where MSG_NOSIGNAL is not available
+#if defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
+ ::setsockopt(socket_, SOL_SOCKET, SO_NOSIGPIPE, (char *)&enable_flag, sizeof(enable_flag));
+#endif
+
+#if !defined(SO_NOSIGPIPE) && !defined(MSG_NOSIGNAL)
+#error "tcp_sink would raise SIGPIPE since niether SO_NOSIGPIPE nor MSG_NOSIGNAL are available"
+#endif
+ }
+
+ // Send exactly n_bytes of the given data.
+ // On error close the connection and throw.
+ void send(const char *data, size_t n_bytes)
+ {
+ size_t bytes_sent = 0;
+ while (bytes_sent < n_bytes)
+ {
+#if defined(MSG_NOSIGNAL)
+ const int send_flags = MSG_NOSIGNAL;
+#else
+ const int send_flags = 0;
+#endif
+ auto write_result = ::send(socket_, data + bytes_sent, n_bytes - bytes_sent, send_flags);
+ if (write_result < 0)
+ {
+ close();
+ throw_spdlog_ex("write(2) failed", errno);
+ }
+
+ if (write_result == 0) // (probably should not happen but in any case..)
+ {
+ break;
+ }
+ bytes_sent += static_cast<size_t>(write_result);
+ }
+ }
+};
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/thread_pool-inl.h b/include/spdlog/details/thread_pool-inl.h
new file mode 100644
index 00000000..c1df4361
--- /dev/null
+++ b/include/spdlog/details/thread_pool-inl.h
@@ -0,0 +1,129 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/details/thread_pool.h>
+#endif
+
+#include <spdlog/common.h>
+#include <cassert>
+
+namespace spdlog {
+namespace details {
+
+SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start)
+ : q_(q_max_items)
+{
+ if (threads_n == 0 || threads_n > 1000)
+ {
+ throw_spdlog_ex("spdlog::thread_pool(): invalid threads_n param (valid "
+ "range is 1-1000)");
+ }
+ for (size_t i = 0; i < threads_n; i++)
+ {
+ threads_.emplace_back([this, on_thread_start] {
+ on_thread_start();
+ this->thread_pool::worker_loop_();
+ });
+ }
+}
+
+SPDLOG_INLINE thread_pool::thread_pool(size_t q_max_items, size_t threads_n)
+ : thread_pool(q_max_items, threads_n, [] {})
+{}
+
+// message all threads to terminate gracefully join them
+SPDLOG_INLINE thread_pool::~thread_pool()
+{
+ SPDLOG_TRY
+ {
+ for (size_t i = 0; i < threads_.size(); i++)
+ {
+ post_async_msg_(async_msg(async_msg_type::terminate), async_overflow_policy::block);
+ }
+
+ for (auto &t : threads_)
+ {
+ t.join();
+ }
+ }
+ SPDLOG_CATCH_ALL() {}
+}
+
+void SPDLOG_INLINE thread_pool::post_log(async_logger_ptr &&worker_ptr, const details::log_msg &msg, async_overflow_policy overflow_policy)
+{
+ async_msg async_m(std::move(worker_ptr), async_msg_type::log, msg);
+ post_async_msg_(std::move(async_m), overflow_policy);
+}
+
+void SPDLOG_INLINE thread_pool::post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy)
+{
+ post_async_msg_(async_msg(std::move(worker_ptr), async_msg_type::flush), overflow_policy);
+}
+
+size_t SPDLOG_INLINE thread_pool::overrun_counter()
+{
+ return q_.overrun_counter();
+}
+
+size_t SPDLOG_INLINE thread_pool::queue_size()
+{
+ return q_.size();
+}
+
+void SPDLOG_INLINE thread_pool::post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy)
+{
+ if (overflow_policy == async_overflow_policy::block)
+ {
+ q_.enqueue(std::move(new_msg));
+ }
+ else
+ {
+ q_.enqueue_nowait(std::move(new_msg));
+ }
+}
+
+void SPDLOG_INLINE thread_pool::worker_loop_()
+{
+ while (process_next_msg_()) {}
+}
+
+// process next message in the queue
+// return true if this thread should still be active (while no terminate msg
+// was received)
+bool SPDLOG_INLINE thread_pool::process_next_msg_()
+{
+ async_msg incoming_async_msg;
+ bool dequeued = q_.dequeue_for(incoming_async_msg, std::chrono::seconds(10));
+ if (!dequeued)
+ {
+ return true;
+ }
+
+ switch (incoming_async_msg.msg_type)
+ {
+ case async_msg_type::log: {
+ incoming_async_msg.worker_ptr->backend_sink_it_(incoming_async_msg);
+ return true;
+ }
+ case async_msg_type::flush: {
+ incoming_async_msg.worker_ptr->backend_flush_();
+ return true;
+ }
+
+ case async_msg_type::terminate: {
+ return false;
+ }
+
+ default: {
+ assert(false);
+ }
+ }
+
+ return true;
+}
+
+} // namespace details
+} // namespace spdlog
diff --git a/include/spdlog/details/thread_pool.h b/include/spdlog/details/thread_pool.h
new file mode 100644
index 00000000..61e25252
--- /dev/null
+++ b/include/spdlog/details/thread_pool.h
@@ -0,0 +1,121 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/log_msg_buffer.h>
+#include <spdlog/details/mpmc_blocking_q.h>
+#include <spdlog/details/os.h>
+
+#include <chrono>
+#include <memory>
+#include <thread>
+#include <vector>
+#include <functional>
+
+namespace spdlog {
+class async_logger;
+
+namespace details {
+
+using async_logger_ptr = std::shared_ptr<spdlog::async_logger>;
+
+enum class async_msg_type
+{
+ log,
+ flush,
+ terminate
+};
+
+#include <spdlog/details/log_msg_buffer.h>
+// Async msg to move to/from the queue
+// Movable only. should never be copied
+struct async_msg : log_msg_buffer
+{
+ async_msg_type msg_type{async_msg_type::log};
+ async_logger_ptr worker_ptr;
+
+ async_msg() = default;
+ ~async_msg() = default;
+
+ // should only be moved in or out of the queue..
+ async_msg(const async_msg &) = delete;
+
+// support for vs2013 move
+#if defined(_MSC_VER) && _MSC_VER <= 1800
+ async_msg(async_msg &&other)
+ : log_msg_buffer(std::move(other))
+ , msg_type(other.msg_type)
+ , worker_ptr(std::move(other.worker_ptr))
+ {}
+
+ async_msg &operator=(async_msg &&other)
+ {
+ *static_cast<log_msg_buffer *>(this) = std::move(other);
+ msg_type = other.msg_type;
+ worker_ptr = std::move(other.worker_ptr);
+ return *this;
+ }
+#else // (_MSC_VER) && _MSC_VER <= 1800
+ async_msg(async_msg &&) = default;
+ async_msg &operator=(async_msg &&) = default;
+#endif
+
+ // construct from log_msg with given type
+ async_msg(async_logger_ptr &&worker, async_msg_type the_type, const details::log_msg &m)
+ : log_msg_buffer{m}
+ , msg_type{the_type}
+ , worker_ptr{std::move(worker)}
+ {}
+
+ async_msg(async_logger_ptr &&worker, async_msg_type the_type)
+ : log_msg_buffer{}
+ , msg_type{the_type}
+ , worker_ptr{std::move(worker)}
+ {}
+
+ explicit async_msg(async_msg_type the_type)
+ : async_msg{nullptr, the_type}
+ {}
+};
+
+class SPDLOG_API thread_pool
+{
+public:
+ using item_type = async_msg;
+ using q_type = details::mpmc_blocking_queue<item_type>;
+
+ thread_pool(size_t q_max_items, size_t threads_n, std::function<void()> on_thread_start);
+ thread_pool(size_t q_max_items, size_t threads_n);
+
+ // message all threads to terminate gracefully join them
+ ~thread_pool();
+
+ thread_pool(const thread_pool &) = delete;
+ thread_pool &operator=(thread_pool &&) = delete;
+
+ void post_log(async_logger_ptr &&worker_ptr, const details::log_msg &msg, async_overflow_policy overflow_policy);
+ void post_flush(async_logger_ptr &&worker_ptr, async_overflow_policy overflow_policy);
+ size_t overrun_counter();
+ size_t queue_size();
+
+private:
+ q_type q_;
+
+ std::vector<std::thread> threads_;
+
+ void post_async_msg_(async_msg &&new_msg, async_overflow_policy overflow_policy);
+ void worker_loop_();
+
+ // process next message in the queue
+ // return true if this thread should still be active (while no terminate msg
+ // was received)
+ bool process_next_msg_();
+};
+
+} // namespace details
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "thread_pool-inl.h"
+#endif
diff --git a/include/spdlog/details/windows_include.h b/include/spdlog/details/windows_include.h
new file mode 100644
index 00000000..6a2f14f9
--- /dev/null
+++ b/include/spdlog/details/windows_include.h
@@ -0,0 +1,11 @@
+#pragma once
+
+#ifndef NOMINMAX
+#define NOMINMAX // prevent windows redefining min/max
+#endif
+
+#ifndef WIN32_LEAN_AND_MEAN
+#define WIN32_LEAN_AND_MEAN
+#endif
+
+#include <windows.h>
diff --git a/include/spdlog/fmt/bin_to_hex.h b/include/spdlog/fmt/bin_to_hex.h
new file mode 100644
index 00000000..1e2b054b
--- /dev/null
+++ b/include/spdlog/fmt/bin_to_hex.h
@@ -0,0 +1,216 @@
+//
+// Copyright(c) 2015 Gabi Melman.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+//
+
+#pragma once
+
+#include <cctype>
+
+//
+// Support for logging binary data as hex
+// format flags, any combination of the followng:
+// {:X} - print in uppercase.
+// {:s} - don't separate each byte with space.
+// {:p} - don't print the position on each line start.
+// {:n} - don't split the output to lines.
+// {:a} - show ASCII if :n is not set
+
+//
+// Examples:
+//
+// std::vector<char> v(200, 0x0b);
+// logger->info("Some buffer {}", spdlog::to_hex(v));
+// char buf[128];
+// logger->info("Some buffer {:X}", spdlog::to_hex(std::begin(buf), std::end(buf)));
+// logger->info("Some buffer {:X}", spdlog::to_hex(std::begin(buf), std::end(buf), 16));
+
+namespace spdlog {
+namespace details {
+
+template<typename It>
+class dump_info
+{
+public:
+ dump_info(It range_begin, It range_end, size_t size_per_line)
+ : begin_(range_begin)
+ , end_(range_end)
+ , size_per_line_(size_per_line)
+ {}
+
+ It begin() const
+ {
+ return begin_;
+ }
+ It end() const
+ {
+ return end_;
+ }
+ size_t size_per_line() const
+ {
+ return size_per_line_;
+ }
+
+private:
+ It begin_, end_;
+ size_t size_per_line_;
+};
+} // namespace details
+
+// create a dump_info that wraps the given container
+template<typename Container>
+inline details::dump_info<typename Container::const_iterator> to_hex(const Container &container, size_t size_per_line = 32)
+{
+ static_assert(sizeof(typename Container::value_type) == 1, "sizeof(Container::value_type) != 1");
+ using Iter = typename Container::const_iterator;
+ return details::dump_info<Iter>(std::begin(container), std::end(container), size_per_line);
+}
+
+// create dump_info from ranges
+template<typename It>
+inline details::dump_info<It> to_hex(const It range_begin, const It range_end, size_t size_per_line = 32)
+{
+ return details::dump_info<It>(range_begin, range_end, size_per_line);
+}
+
+} // namespace spdlog
+
+namespace fmt {
+
+template<typename T>
+struct formatter<spdlog::details::dump_info<T>>
+{
+ const char delimiter = ' ';
+ bool put_newlines = true;
+ bool put_delimiters = true;
+ bool use_uppercase = false;
+ bool put_positions = true; // position on start of each line
+ bool show_ascii = false;
+
+ // parse the format string flags
+ template<typename ParseContext>
+ auto parse(ParseContext &ctx) -> decltype(ctx.begin())
+ {
+ auto it = ctx.begin();
+ while (it != ctx.end() && *it != '}')
+ {
+ switch (*it)
+ {
+ case 'X':
+ use_uppercase = true;
+ break;
+ case 's':
+ put_delimiters = false;
+ break;
+ case 'p':
+ put_positions = false;
+ break;
+ case 'n':
+ put_newlines = false;
+ show_ascii = false;
+ break;
+ case 'a':
+ if (put_newlines)
+ {
+ show_ascii = true;
+ }
+ break;
+ }
+
+ ++it;
+ }
+ return it;
+ }
+
+ // format the given bytes range as hex
+ template<typename FormatContext, typename Container>
+ auto format(const spdlog::details::dump_info<Container> &the_range, FormatContext &ctx) -> decltype(ctx.out())
+ {
+ SPDLOG_CONSTEXPR const char *hex_upper = "0123456789ABCDEF";
+ SPDLOG_CONSTEXPR const char *hex_lower = "0123456789abcdef";
+ const char *hex_chars = use_uppercase ? hex_upper : hex_lower;
+
+#if FMT_VERSION < 60000
+ auto inserter = ctx.begin();
+#else
+ auto inserter = ctx.out();
+#endif
+
+ int size_per_line = static_cast<int>(the_range.size_per_line());
+ auto start_of_line = the_range.begin();
+ for (auto i = the_range.begin(); i != the_range.end(); i++)
+ {
+ auto ch = static_cast<unsigned char>(*i);
+
+ if (put_newlines && (i == the_range.begin() || i - start_of_line >= size_per_line))
+ {
+ if (show_ascii && i != the_range.begin())
+ {
+ *inserter++ = delimiter;
+ *inserter++ = delimiter;
+ for (auto j = start_of_line; j < i; j++)
+ {
+ auto pc = static_cast<unsigned char>(*j);
+ *inserter++ = std::isprint(pc) ? static_cast<char>(*j) : '.';
+ }
+ }
+
+ put_newline(inserter, static_cast<size_t>(i - the_range.begin()));
+
+ // put first byte without delimiter in front of it
+ *inserter++ = hex_chars[(ch >> 4) & 0x0f];
+ *inserter++ = hex_chars[ch & 0x0f];
+ start_of_line = i;
+ continue;
+ }
+
+ if (put_delimiters)
+ {
+ *inserter++ = delimiter;
+ }
+
+ *inserter++ = hex_chars[(ch >> 4) & 0x0f];
+ *inserter++ = hex_chars[ch & 0x0f];
+ }
+ if (show_ascii) // add ascii to last line
+ {
+ if (the_range.end() - the_range.begin() > size_per_line)
+ {
+ auto blank_num = size_per_line - (the_range.end() - start_of_line);
+ while (blank_num-- > 0)
+ {
+ *inserter++ = delimiter;
+ *inserter++ = delimiter;
+ if (put_delimiters)
+ {
+ *inserter++ = delimiter;
+ }
+ }
+ }
+ *inserter++ = delimiter;
+ *inserter++ = delimiter;
+ for (auto j = start_of_line; j != the_range.end(); j++)
+ {
+ auto pc = static_cast<unsigned char>(*j);
+ *inserter++ = std::isprint(pc) ? static_cast<char>(*j) : '.';
+ }
+ }
+ return inserter;
+ }
+
+ // put newline(and position header)
+ template<typename It>
+ void put_newline(It inserter, std::size_t pos)
+ {
+#ifdef _WIN32
+ *inserter++ = '\r';
+#endif
+ *inserter++ = '\n';
+
+ if (put_positions)
+ {
+ fmt::format_to(inserter, "{:<04X}: ", pos);
+ }
+ }
+};
+} // namespace fmt
diff --git a/include/spdlog/fmt/bundled/LICENSE.rst b/include/spdlog/fmt/bundled/LICENSE.rst
new file mode 100644
index 00000000..f0ec3db4
--- /dev/null
+++ b/include/spdlog/fmt/bundled/LICENSE.rst
@@ -0,0 +1,27 @@
+Copyright (c) 2012 - present, Victor Zverovich
+
+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.
+
+--- Optional exception to the license ---
+
+As an exception, if, as a result of your compiling your source code, portions
+of this Software are embedded into a machine-executable object form of such
+source code, you may redistribute such embedded portions in such object form
+without including the above copyright and permission notices.
diff --git a/include/spdlog/fmt/bundled/chrono.h b/include/spdlog/fmt/bundled/chrono.h
new file mode 100644
index 00000000..bdfe2aa0
--- /dev/null
+++ b/include/spdlog/fmt/bundled/chrono.h
@@ -0,0 +1,1116 @@
+// Formatting library for C++ - chrono support
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_CHRONO_H_
+#define FMT_CHRONO_H_
+
+#include <chrono>
+#include <ctime>
+#include <locale>
+#include <sstream>
+
+#include "format.h"
+#include "locale.h"
+
+FMT_BEGIN_NAMESPACE
+
+// Enable safe chrono durations, unless explicitly disabled.
+#ifndef FMT_SAFE_DURATION_CAST
+# define FMT_SAFE_DURATION_CAST 1
+#endif
+#if FMT_SAFE_DURATION_CAST
+
+// For conversion between std::chrono::durations without undefined
+// behaviour or erroneous results.
+// This is a stripped down version of duration_cast, for inclusion in fmt.
+// See https://github.com/pauldreik/safe_duration_cast
+//
+// Copyright Paul Dreik 2019
+namespace safe_duration_cast {
+
+template <typename To, typename From,
+ FMT_ENABLE_IF(!std::is_same<From, To>::value &&
+ std::numeric_limits<From>::is_signed ==
+ std::numeric_limits<To>::is_signed)>
+FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
+ ec = 0;
+ using F = std::numeric_limits<From>;
+ using T = std::numeric_limits<To>;
+ static_assert(F::is_integer, "From must be integral");
+ static_assert(T::is_integer, "To must be integral");
+
+ // A and B are both signed, or both unsigned.
+ if (F::digits <= T::digits) {
+ // From fits in To without any problem.
+ } else {
+ // From does not always fit in To, resort to a dynamic check.
+ if (from < (T::min)() || from > (T::max)()) {
+ // outside range.
+ ec = 1;
+ return {};
+ }
+ }
+ return static_cast<To>(from);
+}
+
+/**
+ * converts From to To, without loss. If the dynamic value of from
+ * can't be converted to To without loss, ec is set.
+ */
+template <typename To, typename From,
+ FMT_ENABLE_IF(!std::is_same<From, To>::value &&
+ std::numeric_limits<From>::is_signed !=
+ std::numeric_limits<To>::is_signed)>
+FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
+ ec = 0;
+ using F = std::numeric_limits<From>;
+ using T = std::numeric_limits<To>;
+ static_assert(F::is_integer, "From must be integral");
+ static_assert(T::is_integer, "To must be integral");
+
+ if (detail::const_check(F::is_signed && !T::is_signed)) {
+ // From may be negative, not allowed!
+ if (fmt::detail::is_negative(from)) {
+ ec = 1;
+ return {};
+ }
+ // From is positive. Can it always fit in To?
+ if (F::digits > T::digits &&
+ from > static_cast<From>(detail::max_value<To>())) {
+ ec = 1;
+ return {};
+ }
+ }
+
+ if (!F::is_signed && T::is_signed && F::digits >= T::digits &&
+ from > static_cast<From>(detail::max_value<To>())) {
+ ec = 1;
+ return {};
+ }
+ return static_cast<To>(from); // Lossless conversion.
+}
+
+template <typename To, typename From,
+ FMT_ENABLE_IF(std::is_same<From, To>::value)>
+FMT_CONSTEXPR To lossless_integral_conversion(const From from, int& ec) {
+ ec = 0;
+ return from;
+} // function
+
+/**
+ * converts From to To if possible, otherwise ec is set.
+ *
+ * input | output
+ * ---------------------------------|---------------
+ * NaN | NaN
+ * Inf | Inf
+ * normal, fits in output | converted (possibly lossy)
+ * normal, does not fit in output | ec is set
+ * subnormal | best effort
+ * -Inf | -Inf
+ */
+template <typename To, typename From,
+ FMT_ENABLE_IF(!std::is_same<From, To>::value)>
+FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
+ ec = 0;
+ using T = std::numeric_limits<To>;
+ static_assert(std::is_floating_point<From>::value, "From must be floating");
+ static_assert(std::is_floating_point<To>::value, "To must be floating");
+
+ // catch the only happy case
+ if (std::isfinite(from)) {
+ if (from >= T::lowest() && from <= (T::max)()) {
+ return static_cast<To>(from);
+ }
+ // not within range.
+ ec = 1;
+ return {};
+ }
+
+ // nan and inf will be preserved
+ return static_cast<To>(from);
+} // function
+
+template <typename To, typename From,
+ FMT_ENABLE_IF(std::is_same<From, To>::value)>
+FMT_CONSTEXPR To safe_float_conversion(const From from, int& ec) {
+ ec = 0;
+ static_assert(std::is_floating_point<From>::value, "From must be floating");
+ return from;
+}
+
+/**
+ * safe duration cast between integral durations
+ */
+template <typename To, typename FromRep, typename FromPeriod,
+ FMT_ENABLE_IF(std::is_integral<FromRep>::value),
+ FMT_ENABLE_IF(std::is_integral<typename To::rep>::value)>
+To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
+ int& ec) {
+ using From = std::chrono::duration<FromRep, FromPeriod>;
+ ec = 0;
+ // the basic idea is that we need to convert from count() in the from type
+ // to count() in the To type, by multiplying it with this:
+ struct Factor
+ : std::ratio_divide<typename From::period, typename To::period> {};
+
+ static_assert(Factor::num > 0, "num must be positive");
+ static_assert(Factor::den > 0, "den must be positive");
+
+ // the conversion is like this: multiply from.count() with Factor::num
+ // /Factor::den and convert it to To::rep, all this without
+ // overflow/underflow. let's start by finding a suitable type that can hold
+ // both To, From and Factor::num
+ using IntermediateRep =
+ typename std::common_type<typename From::rep, typename To::rep,
+ decltype(Factor::num)>::type;
+
+ // safe conversion to IntermediateRep
+ IntermediateRep count =
+ lossless_integral_conversion<IntermediateRep>(from.count(), ec);
+ if (ec) return {};
+ // multiply with Factor::num without overflow or underflow
+ if (detail::const_check(Factor::num != 1)) {
+ const auto max1 = detail::max_value<IntermediateRep>() / Factor::num;
+ if (count > max1) {
+ ec = 1;
+ return {};
+ }
+ const auto min1 =
+ (std::numeric_limits<IntermediateRep>::min)() / Factor::num;
+ if (count < min1) {
+ ec = 1;
+ return {};
+ }
+ count *= Factor::num;
+ }
+
+ if (detail::const_check(Factor::den != 1)) count /= Factor::den;
+ auto tocount = lossless_integral_conversion<typename To::rep>(count, ec);
+ return ec ? To() : To(tocount);
+}
+
+/**
+ * safe duration_cast between floating point durations
+ */
+template <typename To, typename FromRep, typename FromPeriod,
+ FMT_ENABLE_IF(std::is_floating_point<FromRep>::value),
+ FMT_ENABLE_IF(std::is_floating_point<typename To::rep>::value)>
+To safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from,
+ int& ec) {
+ using From = std::chrono::duration<FromRep, FromPeriod>;
+ ec = 0;
+ if (std::isnan(from.count())) {
+ // nan in, gives nan out. easy.
+ return To{std::numeric_limits<typename To::rep>::quiet_NaN()};
+ }
+ // maybe we should also check if from is denormal, and decide what to do about
+ // it.
+
+ // +-inf should be preserved.
+ if (std::isinf(from.count())) {
+ return To{from.count()};
+ }
+
+ // the basic idea is that we need to convert from count() in the from type
+ // to count() in the To type, by multiplying it with this:
+ struct Factor
+ : std::ratio_divide<typename From::period, typename To::period> {};
+
+ static_assert(Factor::num > 0, "num must be positive");
+ static_assert(Factor::den > 0, "den must be positive");
+
+ // the conversion is like this: multiply from.count() with Factor::num
+ // /Factor::den and convert it to To::rep, all this without
+ // overflow/underflow. let's start by finding a suitable type that can hold
+ // both To, From and Factor::num
+ using IntermediateRep =
+ typename std::common_type<typename From::rep, typename To::rep,
+ decltype(Factor::num)>::type;
+
+ // force conversion of From::rep -> IntermediateRep to be safe,
+ // even if it will never happen be narrowing in this context.
+ IntermediateRep count =
+ safe_float_conversion<IntermediateRep>(from.count(), ec);
+ if (ec) {
+ return {};
+ }
+
+ // multiply with Factor::num without overflow or underflow
+ if (Factor::num != 1) {
+ constexpr auto max1 = detail::max_value<IntermediateRep>() /
+ static_cast<IntermediateRep>(Factor::num);
+ if (count > max1) {
+ ec = 1;
+ return {};
+ }
+ constexpr auto min1 = std::numeric_limits<IntermediateRep>::lowest() /
+ static_cast<IntermediateRep>(Factor::num);
+ if (count < min1) {
+ ec = 1;
+ return {};
+ }
+ count *= static_cast<IntermediateRep>(Factor::num);
+ }
+
+ // this can't go wrong, right? den>0 is checked earlier.
+ if (Factor::den != 1) {
+ using common_t = typename std::common_type<IntermediateRep, intmax_t>::type;
+ count /= static_cast<common_t>(Factor::den);
+ }
+
+ // convert to the to type, safely
+ using ToRep = typename To::rep;
+
+ const ToRep tocount = safe_float_conversion<ToRep>(count, ec);
+ if (ec) {
+ return {};
+ }
+ return To{tocount};
+}
+} // namespace safe_duration_cast
+#endif
+
+// Prevents expansion of a preceding token as a function-style macro.
+// Usage: f FMT_NOMACRO()
+#define FMT_NOMACRO
+
+namespace detail {
+inline null<> localtime_r FMT_NOMACRO(...) { return null<>(); }
+inline null<> localtime_s(...) { return null<>(); }
+inline null<> gmtime_r(...) { return null<>(); }
+inline null<> gmtime_s(...) { return null<>(); }
+} // namespace detail
+
+// Thread-safe replacement for std::localtime
+inline std::tm localtime(std::time_t time) {
+ struct dispatcher {
+ std::time_t time_;
+ std::tm tm_;
+
+ dispatcher(std::time_t t) : time_(t) {}
+
+ bool run() {
+ using namespace fmt::detail;
+ return handle(localtime_r(&time_, &tm_));
+ }
+
+ bool handle(std::tm* tm) { return tm != nullptr; }
+
+ bool handle(detail::null<>) {
+ using namespace fmt::detail;
+ return fallback(localtime_s(&tm_, &time_));
+ }
+
+ bool fallback(int res) { return res == 0; }
+
+#if !FMT_MSC_VER
+ bool fallback(detail::null<>) {
+ using namespace fmt::detail;
+ std::tm* tm = std::localtime(&time_);
+ if (tm) tm_ = *tm;
+ return tm != nullptr;
+ }
+#endif
+ };
+ dispatcher lt(time);
+ // Too big time values may be unsupported.
+ if (!lt.run()) FMT_THROW(format_error("time_t value out of range"));
+ return lt.tm_;
+}
+
+inline std::tm localtime(
+ std::chrono::time_point<std::chrono::system_clock> time_point) {
+ return localtime(std::chrono::system_clock::to_time_t(time_point));
+}
+
+// Thread-safe replacement for std::gmtime
+inline std::tm gmtime(std::time_t time) {
+ struct dispatcher {
+ std::time_t time_;
+ std::tm tm_;
+
+ dispatcher(std::time_t t) : time_(t) {}
+
+ bool run() {
+ using namespace fmt::detail;
+ return handle(gmtime_r(&time_, &tm_));
+ }
+
+ bool handle(std::tm* tm) { return tm != nullptr; }
+
+ bool handle(detail::null<>) {
+ using namespace fmt::detail;
+ return fallback(gmtime_s(&tm_, &time_));
+ }
+
+ bool fallback(int res) { return res == 0; }
+
+#if !FMT_MSC_VER
+ bool fallback(detail::null<>) {
+ std::tm* tm = std::gmtime(&time_);
+ if (tm) tm_ = *tm;
+ return tm != nullptr;
+ }
+#endif
+ };
+ dispatcher gt(time);
+ // Too big time values may be unsupported.
+ if (!gt.run()) FMT_THROW(format_error("time_t value out of range"));
+ return gt.tm_;
+}
+
+inline std::tm gmtime(
+ std::chrono::time_point<std::chrono::system_clock> time_point) {
+ return gmtime(std::chrono::system_clock::to_time_t(time_point));
+}
+
+namespace detail {
+inline size_t strftime(char* str, size_t count, const char* format,
+ const std::tm* time) {
+ return std::strftime(str, count, format, time);
+}
+
+inline size_t strftime(wchar_t* str, size_t count, const wchar_t* format,
+ const std::tm* time) {
+ return std::wcsftime(str, count, format, time);
+}
+} // namespace detail
+
+template <typename Char>
+struct formatter<std::chrono::time_point<std::chrono::system_clock>, Char>
+ : formatter<std::tm, Char> {
+ template <typename FormatContext>
+ auto format(std::chrono::time_point<std::chrono::system_clock> val,
+ FormatContext& ctx) -> decltype(ctx.out()) {
+ std::tm time = localtime(val);
+ return formatter<std::tm, Char>::format(time, ctx);
+ }
+};
+
+template <typename Char> struct formatter<std::tm, Char> {
+ template <typename ParseContext>
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ auto it = ctx.begin();
+ if (it != ctx.end() && *it == ':') ++it;
+ auto end = it;
+ while (end != ctx.end() && *end != '}') ++end;
+ tm_format.reserve(detail::to_unsigned(end - it + 1));
+ tm_format.append(it, end);
+ tm_format.push_back('\0');
+ return end;
+ }
+
+ template <typename FormatContext>
+ auto format(const std::tm& tm, FormatContext& ctx) -> decltype(ctx.out()) {
+ basic_memory_buffer<Char> buf;
+ size_t start = buf.size();
+ for (;;) {
+ size_t size = buf.capacity() - start;
+ size_t count = detail::strftime(&buf[start], size, &tm_format[0], &tm);
+ if (count != 0) {
+ buf.resize(start + count);
+ break;
+ }
+ if (size >= tm_format.size() * 256) {
+ // If the buffer is 256 times larger than the format string, assume
+ // that `strftime` gives an empty result. There doesn't seem to be a
+ // better way to distinguish the two cases:
+ // https://github.com/fmtlib/fmt/issues/367
+ break;
+ }
+ const size_t MIN_GROWTH = 10;
+ buf.reserve(buf.capacity() + (size > MIN_GROWTH ? size : MIN_GROWTH));
+ }
+ return std::copy(buf.begin(), buf.end(), ctx.out());
+ }
+
+ basic_memory_buffer<Char> tm_format;
+};
+
+namespace detail {
+template <typename Period> FMT_CONSTEXPR const char* get_units() {
+ return nullptr;
+}
+template <> FMT_CONSTEXPR const char* get_units<std::atto>() { return "as"; }
+template <> FMT_CONSTEXPR const char* get_units<std::femto>() { return "fs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::pico>() { return "ps"; }
+template <> FMT_CONSTEXPR const char* get_units<std::nano>() { return "ns"; }
+template <> FMT_CONSTEXPR const char* get_units<std::micro>() { return "µs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::milli>() { return "ms"; }
+template <> FMT_CONSTEXPR const char* get_units<std::centi>() { return "cs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::deci>() { return "ds"; }
+template <> FMT_CONSTEXPR const char* get_units<std::ratio<1>>() { return "s"; }
+template <> FMT_CONSTEXPR const char* get_units<std::deca>() { return "das"; }
+template <> FMT_CONSTEXPR const char* get_units<std::hecto>() { return "hs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::kilo>() { return "ks"; }
+template <> FMT_CONSTEXPR const char* get_units<std::mega>() { return "Ms"; }
+template <> FMT_CONSTEXPR const char* get_units<std::giga>() { return "Gs"; }
+template <> FMT_CONSTEXPR const char* get_units<std::tera>() { return "Ts"; }
+template <> FMT_CONSTEXPR const char* get_units<std::peta>() { return "Ps"; }
+template <> FMT_CONSTEXPR const char* get_units<std::exa>() { return "Es"; }
+template <> FMT_CONSTEXPR const char* get_units<std::ratio<60>>() {
+ return "m";
+}
+template <> FMT_CONSTEXPR const char* get_units<std::ratio<3600>>() {
+ return "h";
+}
+
+enum class numeric_system {
+ standard,
+ // Alternative numeric system, e.g. 十二 instead of 12 in ja_JP locale.
+ alternative
+};
+
+// Parses a put_time-like format string and invokes handler actions.
+template <typename Char, typename Handler>
+FMT_CONSTEXPR const Char* parse_chrono_format(const Char* begin,
+ const Char* end,
+ Handler&& handler) {
+ auto ptr = begin;
+ while (ptr != end) {
+ auto c = *ptr;
+ if (c == '}') break;
+ if (c != '%') {
+ ++ptr;
+ continue;
+ }
+ if (begin != ptr) handler.on_text(begin, ptr);
+ ++ptr; // consume '%'
+ if (ptr == end) FMT_THROW(format_error("invalid format"));
+ c = *ptr++;
+ switch (c) {
+ case '%':
+ handler.on_text(ptr - 1, ptr);
+ break;
+ case 'n': {
+ const Char newline[] = {'\n'};
+ handler.on_text(newline, newline + 1);
+ break;
+ }
+ case 't': {
+ const Char tab[] = {'\t'};
+ handler.on_text(tab, tab + 1);
+ break;
+ }
+ // Day of the week:
+ case 'a':
+ handler.on_abbr_weekday();
+ break;
+ case 'A':
+ handler.on_full_weekday();
+ break;
+ case 'w':
+ handler.on_dec0_weekday(numeric_system::standard);
+ break;
+ case 'u':
+ handler.on_dec1_weekday(numeric_system::standard);
+ break;
+ // Month:
+ case 'b':
+ handler.on_abbr_month();
+ break;
+ case 'B':
+ handler.on_full_month();
+ break;
+ // Hour, minute, second:
+ case 'H':
+ handler.on_24_hour(numeric_system::standard);
+ break;
+ case 'I':
+ handler.on_12_hour(numeric_system::standard);
+ break;
+ case 'M':
+ handler.on_minute(numeric_system::standard);
+ break;
+ case 'S':
+ handler.on_second(numeric_system::standard);
+ break;
+ // Other:
+ case 'c':
+ handler.on_datetime(numeric_system::standard);
+ break;
+ case 'x':
+ handler.on_loc_date(numeric_system::standard);
+ break;
+ case 'X':
+ handler.on_loc_time(numeric_system::standard);
+ break;
+ case 'D':
+ handler.on_us_date();
+ break;
+ case 'F':
+ handler.on_iso_date();
+ break;
+ case 'r':
+ handler.on_12_hour_time();
+ break;
+ case 'R':
+ handler.on_24_hour_time();
+ break;
+ case 'T':
+ handler.on_iso_time();
+ break;
+ case 'p':
+ handler.on_am_pm();
+ break;
+ case 'Q':
+ handler.on_duration_value();
+ break;
+ case 'q':
+ handler.on_duration_unit();
+ break;
+ case 'z':
+ handler.on_utc_offset();
+ break;
+ case 'Z':
+ handler.on_tz_name();
+ break;
+ // Alternative representation:
+ case 'E': {
+ if (ptr == end) FMT_THROW(format_error("invalid format"));
+ c = *ptr++;
+ switch (c) {
+ case 'c':
+ handler.on_datetime(numeric_system::alternative);
+ break;
+ case 'x':
+ handler.on_loc_date(numeric_system::alternative);
+ break;
+ case 'X':
+ handler.on_loc_time(numeric_system::alternative);
+ break;
+ default:
+ FMT_THROW(format_error("invalid format"));
+ }
+ break;
+ }
+ case 'O':
+ if (ptr == end) FMT_THROW(format_error("invalid format"));
+ c = *ptr++;
+ switch (c) {
+ case 'w':
+ handler.on_dec0_weekday(numeric_system::alternative);
+ break;
+ case 'u':
+ handler.on_dec1_weekday(numeric_system::alternative);
+ break;
+ case 'H':
+ handler.on_24_hour(numeric_system::alternative);
+ break;
+ case 'I':
+ handler.on_12_hour(numeric_system::alternative);
+ break;
+ case 'M':
+ handler.on_minute(numeric_system::alternative);
+ break;
+ case 'S':
+ handler.on_second(numeric_system::alternative);
+ break;
+ default:
+ FMT_THROW(format_error("invalid format"));
+ }
+ break;
+ default:
+ FMT_THROW(format_error("invalid format"));
+ }
+ begin = ptr;
+ }
+ if (begin != ptr) handler.on_text(begin, ptr);
+ return ptr;
+}
+
+struct chrono_format_checker {
+ FMT_NORETURN void report_no_date() { FMT_THROW(format_error("no date")); }
+
+ template <typename Char> void on_text(const Char*, const Char*) {}
+ FMT_NORETURN void on_abbr_weekday() { report_no_date(); }
+ FMT_NORETURN void on_full_weekday() { report_no_date(); }
+ FMT_NORETURN void on_dec0_weekday(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_dec1_weekday(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_abbr_month() { report_no_date(); }
+ FMT_NORETURN void on_full_month() { report_no_date(); }
+ void on_24_hour(numeric_system) {}
+ void on_12_hour(numeric_system) {}
+ void on_minute(numeric_system) {}
+ void on_second(numeric_system) {}
+ FMT_NORETURN void on_datetime(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_loc_date(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_loc_time(numeric_system) { report_no_date(); }
+ FMT_NORETURN void on_us_date() { report_no_date(); }
+ FMT_NORETURN void on_iso_date() { report_no_date(); }
+ void on_12_hour_time() {}
+ void on_24_hour_time() {}
+ void on_iso_time() {}
+ void on_am_pm() {}
+ void on_duration_value() {}
+ void on_duration_unit() {}
+ FMT_NORETURN void on_utc_offset() { report_no_date(); }
+ FMT_NORETURN void on_tz_name() { report_no_date(); }
+};
+
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline bool isnan(T) {
+ return false;
+}
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+inline bool isnan(T value) {
+ return std::isnan(value);
+}
+
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline bool isfinite(T) {
+ return true;
+}
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+inline bool isfinite(T value) {
+ return std::isfinite(value);
+}
+
+// Converts value to int and checks that it's in the range [0, upper).
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline int to_nonnegative_int(T value, int upper) {
+ FMT_ASSERT(value >= 0 && value <= upper, "invalid value");
+ (void)upper;
+ return static_cast<int>(value);
+}
+template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+inline int to_nonnegative_int(T value, int upper) {
+ FMT_ASSERT(
+ std::isnan(value) || (value >= 0 && value <= static_cast<T>(upper)),
+ "invalid value");
+ (void)upper;
+ return static_cast<int>(value);
+}
+
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline T mod(T x, int y) {
+ return x % static_cast<T>(y);
+}
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+inline T mod(T x, int y) {
+ return std::fmod(x, static_cast<T>(y));
+}
+
+// If T is an integral type, maps T to its unsigned counterpart, otherwise
+// leaves it unchanged (unlike std::make_unsigned).
+template <typename T, bool INTEGRAL = std::is_integral<T>::value>
+struct make_unsigned_or_unchanged {
+ using type = T;
+};
+
+template <typename T> struct make_unsigned_or_unchanged<T, true> {
+ using type = typename std::make_unsigned<T>::type;
+};
+
+#if FMT_SAFE_DURATION_CAST
+// throwing version of safe_duration_cast
+template <typename To, typename FromRep, typename FromPeriod>
+To fmt_safe_duration_cast(std::chrono::duration<FromRep, FromPeriod> from) {
+ int ec;
+ To to = safe_duration_cast::safe_duration_cast<To>(from, ec);
+ if (ec) FMT_THROW(format_error("cannot format duration"));
+ return to;
+}
+#endif
+
+template <typename Rep, typename Period,
+ FMT_ENABLE_IF(std::is_integral<Rep>::value)>
+inline std::chrono::duration<Rep, std::milli> get_milliseconds(
+ std::chrono::duration<Rep, Period> d) {
+ // this may overflow and/or the result may not fit in the
+ // target type.
+#if FMT_SAFE_DURATION_CAST
+ using CommonSecondsType =
+ typename std::common_type<decltype(d), std::chrono::seconds>::type;
+ const auto d_as_common = fmt_safe_duration_cast<CommonSecondsType>(d);
+ const auto d_as_whole_seconds =
+ fmt_safe_duration_cast<std::chrono::seconds>(d_as_common);
+ // this conversion should be nonproblematic
+ const auto diff = d_as_common - d_as_whole_seconds;
+ const auto ms =
+ fmt_safe_duration_cast<std::chrono::duration<Rep, std::milli>>(diff);
+ return ms;
+#else
+ auto s = std::chrono::duration_cast<std::chrono::seconds>(d);
+ return std::chrono::duration_cast<std::chrono::milliseconds>(d - s);
+#endif
+}
+
+template <typename Rep, typename Period,
+ FMT_ENABLE_IF(std::is_floating_point<Rep>::value)>
+inline std::chrono::duration<Rep, std::milli> get_milliseconds(
+ std::chrono::duration<Rep, Period> d) {
+ using common_type = typename std::common_type<Rep, std::intmax_t>::type;
+ auto ms = mod(d.count() * static_cast<common_type>(Period::num) /
+ static_cast<common_type>(Period::den) * 1000,
+ 1000);
+ return std::chrono::duration<Rep, std::milli>(static_cast<Rep>(ms));
+}
+
+template <typename Char, typename Rep, typename OutputIt>
+OutputIt format_duration_value(OutputIt out, Rep val, int precision) {
+ const Char pr_f[] = {'{', ':', '.', '{', '}', 'f', '}', 0};
+ if (precision >= 0) return format_to(out, pr_f, val, precision);
+ const Char fp_f[] = {'{', ':', 'g', '}', 0};
+ const Char format[] = {'{', '}', 0};
+ return format_to(out, std::is_floating_point<Rep>::value ? fp_f : format,
+ val);
+}
+template <typename Char, typename OutputIt>
+OutputIt copy_unit(string_view unit, OutputIt out, Char) {
+ return std::copy(unit.begin(), unit.end(), out);
+}
+
+template <typename OutputIt>
+OutputIt copy_unit(string_view unit, OutputIt out, wchar_t) {
+ // This works when wchar_t is UTF-32 because units only contain characters
+ // that have the same representation in UTF-16 and UTF-32.
+ utf8_to_utf16 u(unit);
+ return std::copy(u.c_str(), u.c_str() + u.size(), out);
+}
+
+template <typename Char, typename Period, typename OutputIt>
+OutputIt format_duration_unit(OutputIt out) {
+ if (const char* unit = get_units<Period>())
+ return copy_unit(string_view(unit), out, Char());
+ const Char num_f[] = {'[', '{', '}', ']', 's', 0};
+ if (const_check(Period::den == 1)) return format_to(out, num_f, Period::num);
+ const Char num_def_f[] = {'[', '{', '}', '/', '{', '}', ']', 's', 0};
+ return format_to(out, num_def_f, Period::num, Period::den);
+}
+
+template <typename FormatContext, typename OutputIt, typename Rep,
+ typename Period>
+struct chrono_formatter {
+ FormatContext& context;
+ OutputIt out;
+ int precision;
+ // rep is unsigned to avoid overflow.
+ using rep =
+ conditional_t<std::is_integral<Rep>::value && sizeof(Rep) < sizeof(int),
+ unsigned, typename make_unsigned_or_unchanged<Rep>::type>;
+ rep val;
+ using seconds = std::chrono::duration<rep>;
+ seconds s;
+ using milliseconds = std::chrono::duration<rep, std::milli>;
+ bool negative;
+
+ using char_type = typename FormatContext::char_type;
+
+ explicit chrono_formatter(FormatContext& ctx, OutputIt o,
+ std::chrono::duration<Rep, Period> d)
+ : context(ctx),
+ out(o),
+ val(static_cast<rep>(d.count())),
+ negative(false) {
+ if (d.count() < 0) {
+ val = 0 - val;
+ negative = true;
+ }
+
+ // this may overflow and/or the result may not fit in the
+ // target type.
+#if FMT_SAFE_DURATION_CAST
+ // might need checked conversion (rep!=Rep)
+ auto tmpval = std::chrono::duration<rep, Period>(val);
+ s = fmt_safe_duration_cast<seconds>(tmpval);
+#else
+ s = std::chrono::duration_cast<seconds>(
+ std::chrono::duration<rep, Period>(val));
+#endif
+ }
+
+ // returns true if nan or inf, writes to out.
+ bool handle_nan_inf() {
+ if (isfinite(val)) {
+ return false;
+ }
+ if (isnan(val)) {
+ write_nan();
+ return true;
+ }
+ // must be +-inf
+ if (val > 0) {
+ write_pinf();
+ } else {
+ write_ninf();
+ }
+ return true;
+ }
+
+ Rep hour() const { return static_cast<Rep>(mod((s.count() / 3600), 24)); }
+
+ Rep hour12() const {
+ Rep hour = static_cast<Rep>(mod((s.count() / 3600), 12));
+ return hour <= 0 ? 12 : hour;
+ }
+
+ Rep minute() const { return static_cast<Rep>(mod((s.count() / 60), 60)); }
+ Rep second() const { return static_cast<Rep>(mod(s.count(), 60)); }
+
+ std::tm time() const {
+ auto time = std::tm();
+ time.tm_hour = to_nonnegative_int(hour(), 24);
+ time.tm_min = to_nonnegative_int(minute(), 60);
+ time.tm_sec = to_nonnegative_int(second(), 60);
+ return time;
+ }
+
+ void write_sign() {
+ if (negative) {
+ *out++ = '-';
+ negative = false;
+ }
+ }
+
+ void write(Rep value, int width) {
+ write_sign();
+ if (isnan(value)) return write_nan();
+ uint32_or_64_or_128_t<int> n =
+ to_unsigned(to_nonnegative_int(value, max_value<int>()));
+ int num_digits = detail::count_digits(n);
+ if (width > num_digits) out = std::fill_n(out, width - num_digits, '0');
+ out = format_decimal<char_type>(out, n, num_digits).end;
+ }
+
+ void write_nan() { std::copy_n("nan", 3, out); }
+ void write_pinf() { std::copy_n("inf", 3, out); }
+ void write_ninf() { std::copy_n("-inf", 4, out); }
+
+ void format_localized(const tm& time, char format, char modifier = 0) {
+ if (isnan(val)) return write_nan();
+ auto locale = context.locale().template get<std::locale>();
+ auto& facet = std::use_facet<std::time_put<char_type>>(locale);
+ std::basic_ostringstream<char_type> os;
+ os.imbue(locale);
+ facet.put(os, os, ' ', &time, format, modifier);
+ auto str = os.str();
+ std::copy(str.begin(), str.end(), out);
+ }
+
+ void on_text(const char_type* begin, const char_type* end) {
+ std::copy(begin, end, out);
+ }
+
+ // These are not implemented because durations don't have date information.
+ void on_abbr_weekday() {}
+ void on_full_weekday() {}
+ void on_dec0_weekday(numeric_system) {}
+ void on_dec1_weekday(numeric_system) {}
+ void on_abbr_month() {}
+ void on_full_month() {}
+ void on_datetime(numeric_system) {}
+ void on_loc_date(numeric_system) {}
+ void on_loc_time(numeric_system) {}
+ void on_us_date() {}
+ void on_iso_date() {}
+ void on_utc_offset() {}
+ void on_tz_name() {}
+
+ void on_24_hour(numeric_system ns) {
+ if (handle_nan_inf()) return;
+
+ if (ns == numeric_system::standard) return write(hour(), 2);
+ auto time = tm();
+ time.tm_hour = to_nonnegative_int(hour(), 24);
+ format_localized(time, 'H', 'O');
+ }
+
+ void on_12_hour(numeric_system ns) {
+ if (handle_nan_inf()) return;
+
+ if (ns == numeric_system::standard) return write(hour12(), 2);
+ auto time = tm();
+ time.tm_hour = to_nonnegative_int(hour12(), 12);
+ format_localized(time, 'I', 'O');
+ }
+
+ void on_minute(numeric_system ns) {
+ if (handle_nan_inf()) return;
+
+ if (ns == numeric_system::standard) return write(minute(), 2);
+ auto time = tm();
+ time.tm_min = to_nonnegative_int(minute(), 60);
+ format_localized(time, 'M', 'O');
+ }
+
+ void on_second(numeric_system ns) {
+ if (handle_nan_inf()) return;
+
+ if (ns == numeric_system::standard) {
+ write(second(), 2);
+#if FMT_SAFE_DURATION_CAST
+ // convert rep->Rep
+ using duration_rep = std::chrono::duration<rep, Period>;
+ using duration_Rep = std::chrono::duration<Rep, Period>;
+ auto tmpval = fmt_safe_duration_cast<duration_Rep>(duration_rep{val});
+#else
+ auto tmpval = std::chrono::duration<Rep, Period>(val);
+#endif
+ auto ms = get_milliseconds(tmpval);
+ if (ms != std::chrono::milliseconds(0)) {
+ *out++ = '.';
+ write(ms.count(), 3);
+ }
+ return;
+ }
+ auto time = tm();
+ time.tm_sec = to_nonnegative_int(second(), 60);
+ format_localized(time, 'S', 'O');
+ }
+
+ void on_12_hour_time() {
+ if (handle_nan_inf()) return;
+ format_localized(time(), 'r');
+ }
+
+ void on_24_hour_time() {
+ if (handle_nan_inf()) {
+ *out++ = ':';
+ handle_nan_inf();
+ return;
+ }
+
+ write(hour(), 2);
+ *out++ = ':';
+ write(minute(), 2);
+ }
+
+ void on_iso_time() {
+ on_24_hour_time();
+ *out++ = ':';
+ if (handle_nan_inf()) return;
+ write(second(), 2);
+ }
+
+ void on_am_pm() {
+ if (handle_nan_inf()) return;
+ format_localized(time(), 'p');
+ }
+
+ void on_duration_value() {
+ if (handle_nan_inf()) return;
+ write_sign();
+ out = format_duration_value<char_type>(out, val, precision);
+ }
+
+ void on_duration_unit() {
+ out = format_duration_unit<char_type, Period>(out);
+ }
+};
+} // namespace detail
+
+template <typename Rep, typename Period, typename Char>
+struct formatter<std::chrono::duration<Rep, Period>, Char> {
+ private:
+ basic_format_specs<Char> specs;
+ int precision;
+ using arg_ref_type = detail::arg_ref<Char>;
+ arg_ref_type width_ref;
+ arg_ref_type precision_ref;
+ mutable basic_string_view<Char> format_str;
+ using duration = std::chrono::duration<Rep, Period>;
+
+ struct spec_handler {
+ formatter& f;
+ basic_format_parse_context<Char>& context;
+ basic_string_view<Char> format_str;
+
+ template <typename Id> FMT_CONSTEXPR arg_ref_type make_arg_ref(Id arg_id) {
+ context.check_arg_id(arg_id);
+ return arg_ref_type(arg_id);
+ }
+
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<Char> arg_id) {
+ context.check_arg_id(arg_id);
+ return arg_ref_type(arg_id);
+ }
+
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(detail::auto_id) {
+ return arg_ref_type(context.next_arg_id());
+ }
+
+ void on_error(const char* msg) { FMT_THROW(format_error(msg)); }
+ void on_fill(basic_string_view<Char> fill) { f.specs.fill = fill; }
+ void on_align(align_t align) { f.specs.align = align; }
+ void on_width(int width) { f.specs.width = width; }
+ void on_precision(int _precision) { f.precision = _precision; }
+ void end_precision() {}
+
+ template <typename Id> void on_dynamic_width(Id arg_id) {
+ f.width_ref = make_arg_ref(arg_id);
+ }
+
+ template <typename Id> void on_dynamic_precision(Id arg_id) {
+ f.precision_ref = make_arg_ref(arg_id);
+ }
+ };
+
+ using iterator = typename basic_format_parse_context<Char>::iterator;
+ struct parse_range {
+ iterator begin;
+ iterator end;
+ };
+
+ FMT_CONSTEXPR parse_range do_parse(basic_format_parse_context<Char>& ctx) {
+ auto begin = ctx.begin(), end = ctx.end();
+ if (begin == end || *begin == '}') return {begin, begin};
+ spec_handler handler{*this, ctx, format_str};
+ begin = detail::parse_align(begin, end, handler);
+ if (begin == end) return {begin, begin};
+ begin = detail::parse_width(begin, end, handler);
+ if (begin == end) return {begin, begin};
+ if (*begin == '.') {
+ if (std::is_floating_point<Rep>::value)
+ begin = detail::parse_precision(begin, end, handler);
+ else
+ handler.on_error("precision not allowed for this argument type");
+ }
+ end = parse_chrono_format(begin, end, detail::chrono_format_checker());
+ return {begin, end};
+ }
+
+ public:
+ formatter() : precision(-1) {}
+
+ FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
+ -> decltype(ctx.begin()) {
+ auto range = do_parse(ctx);
+ format_str = basic_string_view<Char>(
+ &*range.begin, detail::to_unsigned(range.end - range.begin));
+ return range.end;
+ }
+
+ template <typename FormatContext>
+ auto format(const duration& d, FormatContext& ctx) -> decltype(ctx.out()) {
+ auto begin = format_str.begin(), end = format_str.end();
+ // As a possible future optimization, we could avoid extra copying if width
+ // is not specified.
+ basic_memory_buffer<Char> buf;
+ auto out = std::back_inserter(buf);
+ detail::handle_dynamic_spec<detail::width_checker>(specs.width, width_ref,
+ ctx);
+ detail::handle_dynamic_spec<detail::precision_checker>(precision,
+ precision_ref, ctx);
+ if (begin == end || *begin == '}') {
+ out = detail::format_duration_value<Char>(out, d.count(), precision);
+ detail::format_duration_unit<Char, Period>(out);
+ } else {
+ detail::chrono_formatter<FormatContext, decltype(out), Rep, Period> f(
+ ctx, out, d);
+ f.precision = precision;
+ parse_chrono_format(begin, end, f);
+ }
+ return detail::write(
+ ctx.out(), basic_string_view<Char>(buf.data(), buf.size()), specs);
+ }
+};
+
+FMT_END_NAMESPACE
+
+#endif // FMT_CHRONO_H_
diff --git a/include/spdlog/fmt/bundled/color.h b/include/spdlog/fmt/bundled/color.h
new file mode 100644
index 00000000..94e3419d
--- /dev/null
+++ b/include/spdlog/fmt/bundled/color.h
@@ -0,0 +1,603 @@
+// Formatting library for C++ - color support
+//
+// Copyright (c) 2018 - present, Victor Zverovich and fmt contributors
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_COLOR_H_
+#define FMT_COLOR_H_
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+
+enum class color : uint32_t {
+ alice_blue = 0xF0F8FF, // rgb(240,248,255)
+ antique_white = 0xFAEBD7, // rgb(250,235,215)
+ aqua = 0x00FFFF, // rgb(0,255,255)
+ aquamarine = 0x7FFFD4, // rgb(127,255,212)
+ azure = 0xF0FFFF, // rgb(240,255,255)
+ beige = 0xF5F5DC, // rgb(245,245,220)
+ bisque = 0xFFE4C4, // rgb(255,228,196)
+ black = 0x000000, // rgb(0,0,0)
+ blanched_almond = 0xFFEBCD, // rgb(255,235,205)
+ blue = 0x0000FF, // rgb(0,0,255)
+ blue_violet = 0x8A2BE2, // rgb(138,43,226)
+ brown = 0xA52A2A, // rgb(165,42,42)
+ burly_wood = 0xDEB887, // rgb(222,184,135)
+ cadet_blue = 0x5F9EA0, // rgb(95,158,160)
+ chartreuse = 0x7FFF00, // rgb(127,255,0)
+ chocolate = 0xD2691E, // rgb(210,105,30)
+ coral = 0xFF7F50, // rgb(255,127,80)
+ cornflower_blue = 0x6495ED, // rgb(100,149,237)
+ cornsilk = 0xFFF8DC, // rgb(255,248,220)
+ crimson = 0xDC143C, // rgb(220,20,60)
+ cyan = 0x00FFFF, // rgb(0,255,255)
+ dark_blue = 0x00008B, // rgb(0,0,139)
+ dark_cyan = 0x008B8B, // rgb(0,139,139)
+ dark_golden_rod = 0xB8860B, // rgb(184,134,11)
+ dark_gray = 0xA9A9A9, // rgb(169,169,169)
+ dark_green = 0x006400, // rgb(0,100,0)
+ dark_khaki = 0xBDB76B, // rgb(189,183,107)
+ dark_magenta = 0x8B008B, // rgb(139,0,139)
+ dark_olive_green = 0x556B2F, // rgb(85,107,47)
+ dark_orange = 0xFF8C00, // rgb(255,140,0)
+ dark_orchid = 0x9932CC, // rgb(153,50,204)
+ dark_red = 0x8B0000, // rgb(139,0,0)
+ dark_salmon = 0xE9967A, // rgb(233,150,122)
+ dark_sea_green = 0x8FBC8F, // rgb(143,188,143)
+ dark_slate_blue = 0x483D8B, // rgb(72,61,139)
+ dark_slate_gray = 0x2F4F4F, // rgb(47,79,79)
+ dark_turquoise = 0x00CED1, // rgb(0,206,209)
+ dark_violet = 0x9400D3, // rgb(148,0,211)
+ deep_pink = 0xFF1493, // rgb(255,20,147)
+ deep_sky_blue = 0x00BFFF, // rgb(0,191,255)
+ dim_gray = 0x696969, // rgb(105,105,105)
+ dodger_blue = 0x1E90FF, // rgb(30,144,255)
+ fire_brick = 0xB22222, // rgb(178,34,34)
+ floral_white = 0xFFFAF0, // rgb(255,250,240)
+ forest_green = 0x228B22, // rgb(34,139,34)
+ fuchsia = 0xFF00FF, // rgb(255,0,255)
+ gainsboro = 0xDCDCDC, // rgb(220,220,220)
+ ghost_white = 0xF8F8FF, // rgb(248,248,255)
+ gold = 0xFFD700, // rgb(255,215,0)
+ golden_rod = 0xDAA520, // rgb(218,165,32)
+ gray = 0x808080, // rgb(128,128,128)
+ green = 0x008000, // rgb(0,128,0)
+ green_yellow = 0xADFF2F, // rgb(173,255,47)
+ honey_dew = 0xF0FFF0, // rgb(240,255,240)
+ hot_pink = 0xFF69B4, // rgb(255,105,180)
+ indian_red = 0xCD5C5C, // rgb(205,92,92)
+ indigo = 0x4B0082, // rgb(75,0,130)
+ ivory = 0xFFFFF0, // rgb(255,255,240)
+ khaki = 0xF0E68C, // rgb(240,230,140)
+ lavender = 0xE6E6FA, // rgb(230,230,250)
+ lavender_blush = 0xFFF0F5, // rgb(255,240,245)
+ lawn_green = 0x7CFC00, // rgb(124,252,0)
+ lemon_chiffon = 0xFFFACD, // rgb(255,250,205)
+ light_blue = 0xADD8E6, // rgb(173,216,230)
+ light_coral = 0xF08080, // rgb(240,128,128)
+ light_cyan = 0xE0FFFF, // rgb(224,255,255)
+ light_golden_rod_yellow = 0xFAFAD2, // rgb(250,250,210)
+ light_gray = 0xD3D3D3, // rgb(211,211,211)
+ light_green = 0x90EE90, // rgb(144,238,144)
+ light_pink = 0xFFB6C1, // rgb(255,182,193)
+ light_salmon = 0xFFA07A, // rgb(255,160,122)
+ light_sea_green = 0x20B2AA, // rgb(32,178,170)
+ light_sky_blue = 0x87CEFA, // rgb(135,206,250)
+ light_slate_gray = 0x778899, // rgb(119,136,153)
+ light_steel_blue = 0xB0C4DE, // rgb(176,196,222)
+ light_yellow = 0xFFFFE0, // rgb(255,255,224)
+ lime = 0x00FF00, // rgb(0,255,0)
+ lime_green = 0x32CD32, // rgb(50,205,50)
+ linen = 0xFAF0E6, // rgb(250,240,230)
+ magenta = 0xFF00FF, // rgb(255,0,255)
+ maroon = 0x800000, // rgb(128,0,0)
+ medium_aquamarine = 0x66CDAA, // rgb(102,205,170)
+ medium_blue = 0x0000CD, // rgb(0,0,205)
+ medium_orchid = 0xBA55D3, // rgb(186,85,211)
+ medium_purple = 0x9370DB, // rgb(147,112,219)
+ medium_sea_green = 0x3CB371, // rgb(60,179,113)
+ medium_slate_blue = 0x7B68EE, // rgb(123,104,238)
+ medium_spring_green = 0x00FA9A, // rgb(0,250,154)
+ medium_turquoise = 0x48D1CC, // rgb(72,209,204)
+ medium_violet_red = 0xC71585, // rgb(199,21,133)
+ midnight_blue = 0x191970, // rgb(25,25,112)
+ mint_cream = 0xF5FFFA, // rgb(245,255,250)
+ misty_rose = 0xFFE4E1, // rgb(255,228,225)
+ moccasin = 0xFFE4B5, // rgb(255,228,181)
+ navajo_white = 0xFFDEAD, // rgb(255,222,173)
+ navy = 0x000080, // rgb(0,0,128)
+ old_lace = 0xFDF5E6, // rgb(253,245,230)
+ olive = 0x808000, // rgb(128,128,0)
+ olive_drab = 0x6B8E23, // rgb(107,142,35)
+ orange = 0xFFA500, // rgb(255,165,0)
+ orange_red = 0xFF4500, // rgb(255,69,0)
+ orchid = 0xDA70D6, // rgb(218,112,214)
+ pale_golden_rod = 0xEEE8AA, // rgb(238,232,170)
+ pale_green = 0x98FB98, // rgb(152,251,152)
+ pale_turquoise = 0xAFEEEE, // rgb(175,238,238)
+ pale_violet_red = 0xDB7093, // rgb(219,112,147)
+ papaya_whip = 0xFFEFD5, // rgb(255,239,213)
+ peach_puff = 0xFFDAB9, // rgb(255,218,185)
+ peru = 0xCD853F, // rgb(205,133,63)
+ pink = 0xFFC0CB, // rgb(255,192,203)
+ plum = 0xDDA0DD, // rgb(221,160,221)
+ powder_blue = 0xB0E0E6, // rgb(176,224,230)
+ purple = 0x800080, // rgb(128,0,128)
+ rebecca_purple = 0x663399, // rgb(102,51,153)
+ red = 0xFF0000, // rgb(255,0,0)
+ rosy_brown = 0xBC8F8F, // rgb(188,143,143)
+ royal_blue = 0x4169E1, // rgb(65,105,225)
+ saddle_brown = 0x8B4513, // rgb(139,69,19)
+ salmon = 0xFA8072, // rgb(250,128,114)
+ sandy_brown = 0xF4A460, // rgb(244,164,96)
+ sea_green = 0x2E8B57, // rgb(46,139,87)
+ sea_shell = 0xFFF5EE, // rgb(255,245,238)
+ sienna = 0xA0522D, // rgb(160,82,45)
+ silver = 0xC0C0C0, // rgb(192,192,192)
+ sky_blue = 0x87CEEB, // rgb(135,206,235)
+ slate_blue = 0x6A5ACD, // rgb(106,90,205)
+ slate_gray = 0x708090, // rgb(112,128,144)
+ snow = 0xFFFAFA, // rgb(255,250,250)
+ spring_green = 0x00FF7F, // rgb(0,255,127)
+ steel_blue = 0x4682B4, // rgb(70,130,180)
+ tan = 0xD2B48C, // rgb(210,180,140)
+ teal = 0x008080, // rgb(0,128,128)
+ thistle = 0xD8BFD8, // rgb(216,191,216)
+ tomato = 0xFF6347, // rgb(255,99,71)
+ turquoise = 0x40E0D0, // rgb(64,224,208)
+ violet = 0xEE82EE, // rgb(238,130,238)
+ wheat = 0xF5DEB3, // rgb(245,222,179)
+ white = 0xFFFFFF, // rgb(255,255,255)
+ white_smoke = 0xF5F5F5, // rgb(245,245,245)
+ yellow = 0xFFFF00, // rgb(255,255,0)
+ yellow_green = 0x9ACD32 // rgb(154,205,50)
+}; // enum class color
+
+enum class terminal_color : uint8_t {
+ black = 30,
+ red,
+ green,
+ yellow,
+ blue,
+ magenta,
+ cyan,
+ white,
+ bright_black = 90,
+ bright_red,
+ bright_green,
+ bright_yellow,
+ bright_blue,
+ bright_magenta,
+ bright_cyan,
+ bright_white
+};
+
+enum class emphasis : uint8_t {
+ bold = 1,
+ italic = 1 << 1,
+ underline = 1 << 2,
+ strikethrough = 1 << 3
+};
+
+// rgb is a struct for red, green and blue colors.
+// Using the name "rgb" makes some editors show the color in a tooltip.
+struct rgb {
+ FMT_CONSTEXPR rgb() : r(0), g(0), b(0) {}
+ FMT_CONSTEXPR rgb(uint8_t r_, uint8_t g_, uint8_t b_) : r(r_), g(g_), b(b_) {}
+ FMT_CONSTEXPR rgb(uint32_t hex)
+ : r((hex >> 16) & 0xFF), g((hex >> 8) & 0xFF), b(hex & 0xFF) {}
+ FMT_CONSTEXPR rgb(color hex)
+ : r((uint32_t(hex) >> 16) & 0xFF),
+ g((uint32_t(hex) >> 8) & 0xFF),
+ b(uint32_t(hex) & 0xFF) {}
+ uint8_t r;
+ uint8_t g;
+ uint8_t b;
+};
+
+namespace detail {
+
+// color is a struct of either a rgb color or a terminal color.
+struct color_type {
+ FMT_CONSTEXPR color_type() FMT_NOEXCEPT : is_rgb(), value{} {}
+ FMT_CONSTEXPR color_type(color rgb_color) FMT_NOEXCEPT : is_rgb(true),
+ value{} {
+ value.rgb_color = static_cast<uint32_t>(rgb_color);
+ }
+ FMT_CONSTEXPR color_type(rgb rgb_color) FMT_NOEXCEPT : is_rgb(true), value{} {
+ value.rgb_color = (static_cast<uint32_t>(rgb_color.r) << 16) |
+ (static_cast<uint32_t>(rgb_color.g) << 8) | rgb_color.b;
+ }
+ FMT_CONSTEXPR color_type(terminal_color term_color) FMT_NOEXCEPT : is_rgb(),
+ value{} {
+ value.term_color = static_cast<uint8_t>(term_color);
+ }
+ bool is_rgb;
+ union color_union {
+ uint8_t term_color;
+ uint32_t rgb_color;
+ } value;
+};
+} // namespace detail
+
+// Experimental text formatting support.
+class text_style {
+ public:
+ FMT_CONSTEXPR text_style(emphasis em = emphasis()) FMT_NOEXCEPT
+ : set_foreground_color(),
+ set_background_color(),
+ ems(em) {}
+
+ FMT_CONSTEXPR text_style& operator|=(const text_style& rhs) {
+ if (!set_foreground_color) {
+ set_foreground_color = rhs.set_foreground_color;
+ foreground_color = rhs.foreground_color;
+ } else if (rhs.set_foreground_color) {
+ if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb)
+ FMT_THROW(format_error("can't OR a terminal color"));
+ foreground_color.value.rgb_color |= rhs.foreground_color.value.rgb_color;
+ }
+
+ if (!set_background_color) {
+ set_background_color = rhs.set_background_color;
+ background_color = rhs.background_color;
+ } else if (rhs.set_background_color) {
+ if (!background_color.is_rgb || !rhs.background_color.is_rgb)
+ FMT_THROW(format_error("can't OR a terminal color"));
+ background_color.value.rgb_color |= rhs.background_color.value.rgb_color;
+ }
+
+ ems = static_cast<emphasis>(static_cast<uint8_t>(ems) |
+ static_cast<uint8_t>(rhs.ems));
+ return *this;
+ }
+
+ friend FMT_CONSTEXPR text_style operator|(text_style lhs,
+ const text_style& rhs) {
+ return lhs |= rhs;
+ }
+
+ FMT_CONSTEXPR text_style& operator&=(const text_style& rhs) {
+ if (!set_foreground_color) {
+ set_foreground_color = rhs.set_foreground_color;
+ foreground_color = rhs.foreground_color;
+ } else if (rhs.set_foreground_color) {
+ if (!foreground_color.is_rgb || !rhs.foreground_color.is_rgb)
+ FMT_THROW(format_error("can't AND a terminal color"));
+ foreground_color.value.rgb_color &= rhs.foreground_color.value.rgb_color;
+ }
+
+ if (!set_background_color) {
+ set_background_color = rhs.set_background_color;
+ background_color = rhs.background_color;
+ } else if (rhs.set_background_color) {
+ if (!background_color.is_rgb || !rhs.background_color.is_rgb)
+ FMT_THROW(format_error("can't AND a terminal color"));
+ background_color.value.rgb_color &= rhs.background_color.value.rgb_color;
+ }
+
+ ems = static_cast<emphasis>(static_cast<uint8_t>(ems) &
+ static_cast<uint8_t>(rhs.ems));
+ return *this;
+ }
+
+ friend FMT_CONSTEXPR text_style operator&(text_style lhs,
+ const text_style& rhs) {
+ return lhs &= rhs;
+ }
+
+ FMT_CONSTEXPR bool has_foreground() const FMT_NOEXCEPT {
+ return set_foreground_color;
+ }
+ FMT_CONSTEXPR bool has_background() const FMT_NOEXCEPT {
+ return set_background_color;
+ }
+ FMT_CONSTEXPR bool has_emphasis() const FMT_NOEXCEPT {
+ return static_cast<uint8_t>(ems) != 0;
+ }
+ FMT_CONSTEXPR detail::color_type get_foreground() const FMT_NOEXCEPT {
+ FMT_ASSERT(has_foreground(), "no foreground specified for this style");
+ return foreground_color;
+ }
+ FMT_CONSTEXPR detail::color_type get_background() const FMT_NOEXCEPT {
+ FMT_ASSERT(has_background(), "no background specified for this style");
+ return background_color;
+ }
+ FMT_CONSTEXPR emphasis get_emphasis() const FMT_NOEXCEPT {
+ FMT_ASSERT(has_emphasis(), "no emphasis specified for this style");
+ return ems;
+ }
+
+ private:
+ FMT_CONSTEXPR text_style(bool is_foreground,
+ detail::color_type text_color) FMT_NOEXCEPT
+ : set_foreground_color(),
+ set_background_color(),
+ ems() {
+ if (is_foreground) {
+ foreground_color = text_color;
+ set_foreground_color = true;
+ } else {
+ background_color = text_color;
+ set_background_color = true;
+ }
+ }
+
+ friend FMT_CONSTEXPR_DECL text_style fg(detail::color_type foreground)
+ FMT_NOEXCEPT;
+ friend FMT_CONSTEXPR_DECL text_style bg(detail::color_type background)
+ FMT_NOEXCEPT;
+
+ detail::color_type foreground_color;
+ detail::color_type background_color;
+ bool set_foreground_color;
+ bool set_background_color;
+ emphasis ems;
+};
+
+FMT_CONSTEXPR text_style fg(detail::color_type foreground) FMT_NOEXCEPT {
+ return text_style(/*is_foreground=*/true, foreground);
+}
+
+FMT_CONSTEXPR text_style bg(detail::color_type background) FMT_NOEXCEPT {
+ return text_style(/*is_foreground=*/false, background);
+}
+
+FMT_CONSTEXPR text_style operator|(emphasis lhs, emphasis rhs) FMT_NOEXCEPT {
+ return text_style(lhs) | rhs;
+}
+
+namespace detail {
+
+template <typename Char> struct ansi_color_escape {
+ FMT_CONSTEXPR ansi_color_escape(detail::color_type text_color,
+ const char* esc) FMT_NOEXCEPT {
+ // If we have a terminal color, we need to output another escape code
+ // sequence.
+ if (!text_color.is_rgb) {
+ bool is_background = esc == detail::data::background_color;
+ uint32_t value = text_color.value.term_color;
+ // Background ASCII codes are the same as the foreground ones but with
+ // 10 more.
+ if (is_background) value += 10u;
+
+ size_t index = 0;
+ buffer[index++] = static_cast<Char>('\x1b');
+ buffer[index++] = static_cast<Char>('[');
+
+ if (value >= 100u) {
+ buffer[index++] = static_cast<Char>('1');
+ value %= 100u;
+ }
+ buffer[index++] = static_cast<Char>('0' + value / 10u);
+ buffer[index++] = static_cast<Char>('0' + value % 10u);
+
+ buffer[index++] = static_cast<Char>('m');
+ buffer[index++] = static_cast<Char>('\0');
+ return;
+ }
+
+ for (int i = 0; i < 7; i++) {
+ buffer[i] = static_cast<Char>(esc[i]);
+ }
+ rgb color(text_color.value.rgb_color);
+ to_esc(color.r, buffer + 7, ';');
+ to_esc(color.g, buffer + 11, ';');
+ to_esc(color.b, buffer + 15, 'm');
+ buffer[19] = static_cast<Char>(0);
+ }
+ FMT_CONSTEXPR ansi_color_escape(emphasis em) FMT_NOEXCEPT {
+ uint8_t em_codes[4] = {};
+ uint8_t em_bits = static_cast<uint8_t>(em);
+ if (em_bits & static_cast<uint8_t>(emphasis::bold)) em_codes[0] = 1;
+ if (em_bits & static_cast<uint8_t>(emphasis::italic)) em_codes[1] = 3;
+ if (em_bits & static_cast<uint8_t>(emphasis::underline)) em_codes[2] = 4;
+ if (em_bits & static_cast<uint8_t>(emphasis::strikethrough))
+ em_codes[3] = 9;
+
+ size_t index = 0;
+ for (int i = 0; i < 4; ++i) {
+ if (!em_codes[i]) continue;
+ buffer[index++] = static_cast<Char>('\x1b');
+ buffer[index++] = static_cast<Char>('[');
+ buffer[index++] = static_cast<Char>('0' + em_codes[i]);
+ buffer[index++] = static_cast<Char>('m');
+ }
+ buffer[index++] = static_cast<Char>(0);
+ }
+ FMT_CONSTEXPR operator const Char*() const FMT_NOEXCEPT { return buffer; }
+
+ FMT_CONSTEXPR const Char* begin() const FMT_NOEXCEPT { return buffer; }
+ FMT_CONSTEXPR const Char* end() const FMT_NOEXCEPT {
+ return buffer + std::char_traits<Char>::length(buffer);
+ }
+
+ private:
+ Char buffer[7u + 3u * 4u + 1u];
+
+ static FMT_CONSTEXPR void to_esc(uint8_t c, Char* out,
+ char delimiter) FMT_NOEXCEPT {
+ out[0] = static_cast<Char>('0' + c / 100);
+ out[1] = static_cast<Char>('0' + c / 10 % 10);
+ out[2] = static_cast<Char>('0' + c % 10);
+ out[3] = static_cast<Char>(delimiter);
+ }
+};
+
+template <typename Char>
+FMT_CONSTEXPR ansi_color_escape<Char> make_foreground_color(
+ detail::color_type foreground) FMT_NOEXCEPT {
+ return ansi_color_escape<Char>(foreground, detail::data::foreground_color);
+}
+
+template <typename Char>
+FMT_CONSTEXPR ansi_color_escape<Char> make_background_color(
+ detail::color_type background) FMT_NOEXCEPT {
+ return ansi_color_escape<Char>(background, detail::data::background_color);
+}
+
+template <typename Char>
+FMT_CONSTEXPR ansi_color_escape<Char> make_emphasis(emphasis em) FMT_NOEXCEPT {
+ return ansi_color_escape<Char>(em);
+}
+
+template <typename Char>
+inline void fputs(const Char* chars, FILE* stream) FMT_NOEXCEPT {
+ std::fputs(chars, stream);
+}
+
+template <>
+inline void fputs<wchar_t>(const wchar_t* chars, FILE* stream) FMT_NOEXCEPT {
+ std::fputws(chars, stream);
+}
+
+template <typename Char> inline void reset_color(FILE* stream) FMT_NOEXCEPT {
+ fputs(detail::data::reset_color, stream);
+}
+
+template <> inline void reset_color<wchar_t>(FILE* stream) FMT_NOEXCEPT {
+ fputs(detail::data::wreset_color, stream);
+}
+
+template <typename Char>
+inline void reset_color(buffer<Char>& buffer) FMT_NOEXCEPT {
+ const char* begin = data::reset_color;
+ const char* end = begin + sizeof(data::reset_color) - 1;
+ buffer.append(begin, end);
+}
+
+template <typename Char>
+void vformat_to(buffer<Char>& buf, const text_style& ts,
+ basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ bool has_style = false;
+ if (ts.has_emphasis()) {
+ has_style = true;
+ auto emphasis = detail::make_emphasis<Char>(ts.get_emphasis());
+ buf.append(emphasis.begin(), emphasis.end());
+ }
+ if (ts.has_foreground()) {
+ has_style = true;
+ auto foreground = detail::make_foreground_color<Char>(ts.get_foreground());
+ buf.append(foreground.begin(), foreground.end());
+ }
+ if (ts.has_background()) {
+ has_style = true;
+ auto background = detail::make_background_color<Char>(ts.get_background());
+ buf.append(background.begin(), background.end());
+ }
+ detail::vformat_to(buf, format_str, args);
+ if (has_style) detail::reset_color<Char>(buf);
+}
+} // namespace detail
+
+template <typename S, typename Char = char_t<S>>
+void vprint(std::FILE* f, const text_style& ts, const S& format,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buf;
+ detail::vformat_to(buf, ts, to_string_view(format), args);
+ buf.push_back(Char(0));
+ detail::fputs(buf.data(), f);
+}
+
+/**
+ \rst
+ Formats a string and prints it to the specified file stream using ANSI
+ escape sequences to specify text formatting.
+
+ **Example**::
+
+ fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
+ "Elapsed time: {0:.2f} seconds", 1.23);
+ \endrst
+ */
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(detail::is_string<S>::value)>
+void print(std::FILE* f, const text_style& ts, const S& format_str,
+ const Args&... args) {
+ vprint(f, ts, format_str,
+ fmt::make_args_checked<Args...>(format_str, args...));
+}
+
+/**
+ Formats a string and prints it to stdout using ANSI escape sequences to
+ specify text formatting.
+ Example:
+ fmt::print(fmt::emphasis::bold | fg(fmt::color::red),
+ "Elapsed time: {0:.2f} seconds", 1.23);
+ */
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(detail::is_string<S>::value)>
+void print(const text_style& ts, const S& format_str, const Args&... args) {
+ return print(stdout, ts, format_str, args...);
+}
+
+template <typename S, typename Char = char_t<S>>
+inline std::basic_string<Char> vformat(
+ const text_style& ts, const S& format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buf;
+ detail::vformat_to(buf, ts, to_string_view(format_str), args);
+ return fmt::to_string(buf);
+}
+
+/**
+ \rst
+ Formats arguments and returns the result as a string using ANSI
+ escape sequences to specify text formatting.
+
+ **Example**::
+
+ #include <fmt/color.h>
+ std::string message = fmt::format(fmt::emphasis::bold | fg(fmt::color::red),
+ "The answer is {}", 42);
+ \endrst
+*/
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline std::basic_string<Char> format(const text_style& ts, const S& format_str,
+ const Args&... args) {
+ return vformat(ts, to_string_view(format_str),
+ fmt::make_args_checked<Args...>(format_str, args...));
+}
+
+/**
+ Formats a string with the given text_style and writes the output to ``out``.
+ */
+template <typename OutputIt, typename Char,
+ FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)>
+OutputIt vformat_to(
+ OutputIt out, const text_style& ts, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ decltype(detail::get_buffer<Char>(out)) buf(detail::get_buffer_init(out));
+ detail::vformat_to(buf, ts, format_str, args);
+ return detail::get_iterator(buf);
+}
+
+/**
+ \rst
+ Formats arguments with the given text_style, writes the result to the output
+ iterator ``out`` and returns the iterator past the end of the output range.
+
+ **Example**::
+
+ std::vector<char> out;
+ fmt::format_to(std::back_inserter(out),
+ fmt::emphasis::bold | fg(fmt::color::red), "{}", 42);
+ \endrst
+*/
+template <typename OutputIt, typename S, typename... Args,
+ bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value&&
+ detail::is_string<S>::value>
+inline auto format_to(OutputIt out, const text_style& ts, const S& format_str,
+ Args&&... args) ->
+ typename std::enable_if<enable, OutputIt>::type {
+ return vformat_to(out, ts, to_string_view(format_str),
+ fmt::make_args_checked<Args...>(format_str, args...));
+}
+
+FMT_END_NAMESPACE
+
+#endif // FMT_COLOR_H_
diff --git a/include/spdlog/fmt/bundled/compile.h b/include/spdlog/fmt/bundled/compile.h
new file mode 100644
index 00000000..3a33b020
--- /dev/null
+++ b/include/spdlog/fmt/bundled/compile.h
@@ -0,0 +1,701 @@
+// Formatting library for C++ - experimental format string compilation
+//
+// Copyright (c) 2012 - present, Victor Zverovich and fmt contributors
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_COMPILE_H_
+#define FMT_COMPILE_H_
+
+#include <vector>
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+// A compile-time string which is compiled into fast formatting code.
+class compiled_string {};
+
+template <typename S>
+struct is_compiled_string : std::is_base_of<compiled_string, S> {};
+
+/**
+ \rst
+ Converts a string literal *s* into a format string that will be parsed at
+ compile time and converted into efficient formatting code. Requires C++17
+ ``constexpr if`` compiler support.
+
+ **Example**::
+
+ // Converts 42 into std::string using the most efficient method and no
+ // runtime format string processing.
+ std::string s = fmt::format(FMT_COMPILE("{}"), 42);
+ \endrst
+ */
+#define FMT_COMPILE(s) FMT_STRING_IMPL(s, fmt::detail::compiled_string)
+
+template <typename T, typename... Tail>
+const T& first(const T& value, const Tail&...) {
+ return value;
+}
+
+// Part of a compiled format string. It can be either literal text or a
+// replacement field.
+template <typename Char> struct format_part {
+ enum class kind { arg_index, arg_name, text, replacement };
+
+ struct replacement {
+ arg_ref<Char> arg_id;
+ dynamic_format_specs<Char> specs;
+ };
+
+ kind part_kind;
+ union value {
+ int arg_index;
+ basic_string_view<Char> str;
+ replacement repl;
+
+ FMT_CONSTEXPR value(int index = 0) : arg_index(index) {}
+ FMT_CONSTEXPR value(basic_string_view<Char> s) : str(s) {}
+ FMT_CONSTEXPR value(replacement r) : repl(r) {}
+ } val;
+ // Position past the end of the argument id.
+ const Char* arg_id_end = nullptr;
+
+ FMT_CONSTEXPR format_part(kind k = kind::arg_index, value v = {})
+ : part_kind(k), val(v) {}
+
+ static FMT_CONSTEXPR format_part make_arg_index(int index) {
+ return format_part(kind::arg_index, index);
+ }
+ static FMT_CONSTEXPR format_part make_arg_name(basic_string_view<Char> name) {
+ return format_part(kind::arg_name, name);
+ }
+ static FMT_CONSTEXPR format_part make_text(basic_string_view<Char> text) {
+ return format_part(kind::text, text);
+ }
+ static FMT_CONSTEXPR format_part make_replacement(replacement repl) {
+ return format_part(kind::replacement, repl);
+ }
+};
+
+template <typename Char> struct part_counter {
+ unsigned num_parts = 0;
+
+ FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
+ if (begin != end) ++num_parts;
+ }
+
+ FMT_CONSTEXPR int on_arg_id() { return ++num_parts, 0; }
+ FMT_CONSTEXPR int on_arg_id(int) { return ++num_parts, 0; }
+ FMT_CONSTEXPR int on_arg_id(basic_string_view<Char>) {
+ return ++num_parts, 0;
+ }
+
+ FMT_CONSTEXPR void on_replacement_field(int, const Char*) {}
+
+ FMT_CONSTEXPR const Char* on_format_specs(int, const Char* begin,
+ const Char* end) {
+ // Find the matching brace.
+ unsigned brace_counter = 0;
+ for (; begin != end; ++begin) {
+ if (*begin == '{') {
+ ++brace_counter;
+ } else if (*begin == '}') {
+ if (brace_counter == 0u) break;
+ --brace_counter;
+ }
+ }
+ return begin;
+ }
+
+ FMT_CONSTEXPR void on_error(const char*) {}
+};
+
+// Counts the number of parts in a format string.
+template <typename Char>
+FMT_CONSTEXPR unsigned count_parts(basic_string_view<Char> format_str) {
+ part_counter<Char> counter;
+ parse_format_string<true>(format_str, counter);
+ return counter.num_parts;
+}
+
+template <typename Char, typename PartHandler>
+class format_string_compiler : public error_handler {
+ private:
+ using part = format_part<Char>;
+
+ PartHandler handler_;
+ part part_;
+ basic_string_view<Char> format_str_;
+ basic_format_parse_context<Char> parse_context_;
+
+ public:
+ FMT_CONSTEXPR format_string_compiler(basic_string_view<Char> format_str,
+ PartHandler handler)
+ : handler_(handler),
+ format_str_(format_str),
+ parse_context_(format_str) {}
+
+ FMT_CONSTEXPR void on_text(const Char* begin, const Char* end) {
+ if (begin != end)
+ handler_(part::make_text({begin, to_unsigned(end - begin)}));
+ }
+
+ FMT_CONSTEXPR int on_arg_id() {
+ part_ = part::make_arg_index(parse_context_.next_arg_id());
+ return 0;
+ }
+
+ FMT_CONSTEXPR int on_arg_id(int id) {
+ parse_context_.check_arg_id(id);
+ part_ = part::make_arg_index(id);
+ return 0;
+ }
+
+ FMT_CONSTEXPR int on_arg_id(basic_string_view<Char> id) {
+ part_ = part::make_arg_name(id);
+ return 0;
+ }
+
+ FMT_CONSTEXPR void on_replacement_field(int, const Char* ptr) {
+ part_.arg_id_end = ptr;
+ handler_(part_);
+ }
+
+ FMT_CONSTEXPR const Char* on_format_specs(int, const Char* begin,
+ const Char* end) {
+ auto repl = typename part::replacement();
+ dynamic_specs_handler<basic_format_parse_context<Char>> handler(
+ repl.specs, parse_context_);
+ auto it = parse_format_specs(begin, end, handler);
+ if (*it != '}') on_error("missing '}' in format string");
+ repl.arg_id = part_.part_kind == part::kind::arg_index
+ ? arg_ref<Char>(part_.val.arg_index)
+ : arg_ref<Char>(part_.val.str);
+ auto part = part::make_replacement(repl);
+ part.arg_id_end = begin;
+ handler_(part);
+ return it;
+ }
+};
+
+// Compiles a format string and invokes handler(part) for each parsed part.
+template <bool IS_CONSTEXPR, typename Char, typename PartHandler>
+FMT_CONSTEXPR void compile_format_string(basic_string_view<Char> format_str,
+ PartHandler handler) {
+ parse_format_string<IS_CONSTEXPR>(
+ format_str,
+ format_string_compiler<Char, PartHandler>(format_str, handler));
+}
+
+template <typename OutputIt, typename Context, typename Id>
+void format_arg(
+ basic_format_parse_context<typename Context::char_type>& parse_ctx,
+ Context& ctx, Id arg_id) {
+ ctx.advance_to(visit_format_arg(
+ arg_formatter<OutputIt, typename Context::char_type>(ctx, &parse_ctx),
+ ctx.arg(arg_id)));
+}
+
+// vformat_to is defined in a subnamespace to prevent ADL.
+namespace cf {
+template <typename Context, typename OutputIt, typename CompiledFormat>
+auto vformat_to(OutputIt out, CompiledFormat& cf,
+ basic_format_args<Context> args) -> typename Context::iterator {
+ using char_type = typename Context::char_type;
+ basic_format_parse_context<char_type> parse_ctx(
+ to_string_view(cf.format_str_));
+ Context ctx(out, args);
+
+ const auto& parts = cf.parts();
+ for (auto part_it = std::begin(parts); part_it != std::end(parts);
+ ++part_it) {
+ const auto& part = *part_it;
+ const auto& value = part.val;
+
+ using format_part_t = format_part<char_type>;
+ switch (part.part_kind) {
+ case format_part_t::kind::text: {
+ const auto text = value.str;
+ auto output = ctx.out();
+ auto&& it = reserve(output, text.size());
+ it = std::copy_n(text.begin(), text.size(), it);
+ ctx.advance_to(output);
+ break;
+ }
+
+ case format_part_t::kind::arg_index:
+ advance_to(parse_ctx, part.arg_id_end);
+ detail::format_arg<OutputIt>(parse_ctx, ctx, value.arg_index);
+ break;
+
+ case format_part_t::kind::arg_name:
+ advance_to(parse_ctx, part.arg_id_end);
+ detail::format_arg<OutputIt>(parse_ctx, ctx, value.str);
+ break;
+
+ case format_part_t::kind::replacement: {
+ const auto& arg_id_value = value.repl.arg_id.val;
+ const auto arg = value.repl.arg_id.kind == arg_id_kind::index
+ ? ctx.arg(arg_id_value.index)
+ : ctx.arg(arg_id_value.name);
+
+ auto specs = value.repl.specs;
+
+ handle_dynamic_spec<width_checker>(specs.width, specs.width_ref, ctx);
+ handle_dynamic_spec<precision_checker>(specs.precision,
+ specs.precision_ref, ctx);
+
+ error_handler h;
+ numeric_specs_checker<error_handler> checker(h, arg.type());
+ if (specs.align == align::numeric) checker.require_numeric_argument();
+ if (specs.sign != sign::none) checker.check_sign();
+ if (specs.alt) checker.require_numeric_argument();
+ if (specs.precision >= 0) checker.check_precision();
+
+ advance_to(parse_ctx, part.arg_id_end);
+ ctx.advance_to(
+ visit_format_arg(arg_formatter<OutputIt, typename Context::char_type>(
+ ctx, nullptr, &specs),
+ arg));
+ break;
+ }
+ }
+ }
+ return ctx.out();
+}
+} // namespace cf
+
+struct basic_compiled_format {};
+
+template <typename S, typename = void>
+struct compiled_format_base : basic_compiled_format {
+ using char_type = char_t<S>;
+ using parts_container = std::vector<detail::format_part<char_type>>;
+
+ parts_container compiled_parts;
+
+ explicit compiled_format_base(basic_string_view<char_type> format_str) {
+ compile_format_string<false>(format_str,
+ [this](const format_part<char_type>& part) {
+ compiled_parts.push_back(part);
+ });
+ }
+
+ const parts_container& parts() const { return compiled_parts; }
+};
+
+template <typename Char, unsigned N> struct format_part_array {
+ format_part<Char> data[N] = {};
+ FMT_CONSTEXPR format_part_array() = default;
+};
+
+template <typename Char, unsigned N>
+FMT_CONSTEXPR format_part_array<Char, N> compile_to_parts(
+ basic_string_view<Char> format_str) {
+ format_part_array<Char, N> parts;
+ unsigned counter = 0;
+ // This is not a lambda for compatibility with older compilers.
+ struct {
+ format_part<Char>* parts;
+ unsigned* counter;
+ FMT_CONSTEXPR void operator()(const format_part<Char>& part) {
+ parts[(*counter)++] = part;
+ }
+ } collector{parts.data, &counter};
+ compile_format_string<true>(format_str, collector);
+ if (counter < N) {
+ parts.data[counter] =
+ format_part<Char>::make_text(basic_string_view<Char>());
+ }
+ return parts;
+}
+
+template <typename T> constexpr const T& constexpr_max(const T& a, const T& b) {
+ return (a < b) ? b : a;
+}
+
+template <typename S>
+struct compiled_format_base<S, enable_if_t<is_compile_string<S>::value>>
+ : basic_compiled_format {
+ using char_type = char_t<S>;
+
+ FMT_CONSTEXPR explicit compiled_format_base(basic_string_view<char_type>) {}
+
+// Workaround for old compilers. Format string compilation will not be
+// performed there anyway.
+#if FMT_USE_CONSTEXPR
+ static FMT_CONSTEXPR_DECL const unsigned num_format_parts =
+ constexpr_max(count_parts(to_string_view(S())), 1u);
+#else
+ static const unsigned num_format_parts = 1;
+#endif
+
+ using parts_container = format_part<char_type>[num_format_parts];
+
+ const parts_container& parts() const {
+ static FMT_CONSTEXPR_DECL const auto compiled_parts =
+ compile_to_parts<char_type, num_format_parts>(
+ detail::to_string_view(S()));
+ return compiled_parts.data;
+ }
+};
+
+template <typename S, typename... Args>
+class compiled_format : private compiled_format_base<S> {
+ public:
+ using typename compiled_format_base<S>::char_type;
+
+ private:
+ basic_string_view<char_type> format_str_;
+
+ template <typename Context, typename OutputIt, typename CompiledFormat>
+ friend auto cf::vformat_to(OutputIt out, CompiledFormat& cf,
+ basic_format_args<Context> args) ->
+ typename Context::iterator;
+
+ public:
+ compiled_format() = delete;
+ explicit constexpr compiled_format(basic_string_view<char_type> format_str)
+ : compiled_format_base<S>(format_str), format_str_(format_str) {}
+};
+
+#ifdef __cpp_if_constexpr
+template <typename... Args> struct type_list {};
+
+// Returns a reference to the argument at index N from [first, rest...].
+template <int N, typename T, typename... Args>
+constexpr const auto& get([[maybe_unused]] const T& first,
+ [[maybe_unused]] const Args&... rest) {
+ static_assert(N < 1 + sizeof...(Args), "index is out of bounds");
+ if constexpr (N == 0)
+ return first;
+ else
+ return get<N - 1>(rest...);
+}
+
+template <int N, typename> struct get_type_impl;
+
+template <int N, typename... Args> struct get_type_impl<N, type_list<Args...>> {
+ using type = remove_cvref_t<decltype(get<N>(std::declval<Args>()...))>;
+};
+
+template <int N, typename T>
+using get_type = typename get_type_impl<N, T>::type;
+
+template <typename T> struct is_compiled_format : std::false_type {};
+
+template <typename Char> struct text {
+ basic_string_view<Char> data;
+ using char_type = Char;
+
+ template <typename OutputIt, typename... Args>
+ OutputIt format(OutputIt out, const Args&...) const {
+ return write<Char>(out, data);
+ }
+};
+
+template <typename Char>
+struct is_compiled_format<text<Char>> : std::true_type {};
+
+template <typename Char>
+constexpr text<Char> make_text(basic_string_view<Char> s, size_t pos,
+ size_t size) {
+ return {{&s[pos], size}};
+}
+
+template <typename Char> struct code_unit {
+ Char value;
+ using char_type = Char;
+
+ template <typename OutputIt, typename... Args>
+ OutputIt format(OutputIt out, const Args&...) const {
+ return write<Char>(out, value);
+ }
+};
+
+template <typename Char>
+struct is_compiled_format<code_unit<Char>> : std::true_type {};
+
+// A replacement field that refers to argument N.
+template <typename Char, typename T, int N> struct field {
+ using char_type = Char;
+
+ template <typename OutputIt, typename... Args>
+ OutputIt format(OutputIt out, const Args&... args) const {
+ // This ensures that the argument type is convertile to `const T&`.
+ const T& arg = get<N>(args...);
+ return write<Char>(out, arg);
+ }
+};
+
+template <typename Char, typename T, int N>
+struct is_compiled_format<field<Char, T, N>> : std::true_type {};
+
+// A replacement field that refers to argument N and has format specifiers.
+template <typename Char, typename T, int N> struct spec_field {
+ using char_type = Char;
+ mutable formatter<T, Char> fmt;
+
+ template <typename OutputIt, typename... Args>
+ OutputIt format(OutputIt out, const Args&... args) const {
+ // This ensures that the argument type is convertile to `const T&`.
+ const T& arg = get<N>(args...);
+ const auto& vargs =
+ make_format_args<basic_format_context<OutputIt, Char>>(args...);
+ basic_format_context<OutputIt, Char> ctx(out, vargs);
+ return fmt.format(arg, ctx);
+ }
+};
+
+template <typename Char, typename T, int N>
+struct is_compiled_format<spec_field<Char, T, N>> : std::true_type {};
+
+template <typename L, typename R> struct concat {
+ L lhs;
+ R rhs;
+ using char_type = typename L::char_type;
+
+ template <typename OutputIt, typename... Args>
+ OutputIt format(OutputIt out, const Args&... args) const {
+ out = lhs.format(out, args...);
+ return rhs.format(out, args...);
+ }
+};
+
+template <typename L, typename R>
+struct is_compiled_format<concat<L, R>> : std::true_type {};
+
+template <typename L, typename R>
+constexpr concat<L, R> make_concat(L lhs, R rhs) {
+ return {lhs, rhs};
+}
+
+struct unknown_format {};
+
+template <typename Char>
+constexpr size_t parse_text(basic_string_view<Char> str, size_t pos) {
+ for (size_t size = str.size(); pos != size; ++pos) {
+ if (str[pos] == '{' || str[pos] == '}') break;
+ }
+ return pos;
+}
+
+template <typename Args, size_t POS, int ID, typename S>
+constexpr auto compile_format_string(S format_str);
+
+template <typename Args, size_t POS, int ID, typename T, typename S>
+constexpr auto parse_tail(T head, S format_str) {
+ if constexpr (POS !=
+ basic_string_view<typename S::char_type>(format_str).size()) {
+ constexpr auto tail = compile_format_string<Args, POS, ID>(format_str);
+ if constexpr (std::is_same<remove_cvref_t<decltype(tail)>,
+ unknown_format>())
+ return tail;
+ else
+ return make_concat(head, tail);
+ } else {
+ return head;
+ }
+}
+
+template <typename T, typename Char> struct parse_specs_result {
+ formatter<T, Char> fmt;
+ size_t end;
+ int next_arg_id;
+};
+
+template <typename T, typename Char>
+constexpr parse_specs_result<T, Char> parse_specs(basic_string_view<Char> str,
+ size_t pos, int arg_id) {
+ str.remove_prefix(pos);
+ auto ctx = basic_format_parse_context<Char>(str, {}, arg_id + 1);
+ auto f = formatter<T, Char>();
+ auto end = f.parse(ctx);
+ return {f, pos + (end - str.data()) + 1, ctx.next_arg_id()};
+}
+
+// Compiles a non-empty format string and returns the compiled representation
+// or unknown_format() on unrecognized input.
+template <typename Args, size_t POS, int ID, typename S>
+constexpr auto compile_format_string(S format_str) {
+ using char_type = typename S::char_type;
+ constexpr basic_string_view<char_type> str = format_str;
+ if constexpr (str[POS] == '{') {
+ if (POS + 1 == str.size())
+ throw format_error("unmatched '{' in format string");
+ if constexpr (str[POS + 1] == '{') {
+ return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
+ } else if constexpr (str[POS + 1] == '}') {
+ using type = get_type<ID, Args>;
+ return parse_tail<Args, POS + 2, ID + 1>(field<char_type, type, ID>(),
+ format_str);
+ } else if constexpr (str[POS + 1] == ':') {
+ using type = get_type<ID, Args>;
+ constexpr auto result = parse_specs<type>(str, POS + 2, ID);
+ return parse_tail<Args, result.end, result.next_arg_id>(
+ spec_field<char_type, type, ID>{result.fmt}, format_str);
+ } else {
+ return unknown_format();
+ }
+ } else if constexpr (str[POS] == '}') {
+ if (POS + 1 == str.size())
+ throw format_error("unmatched '}' in format string");
+ return parse_tail<Args, POS + 2, ID>(make_text(str, POS, 1), format_str);
+ } else {
+ constexpr auto end = parse_text(str, POS + 1);
+ if constexpr (end - POS > 1) {
+ return parse_tail<Args, end, ID>(make_text(str, POS, end - POS),
+ format_str);
+ } else {
+ return parse_tail<Args, end, ID>(code_unit<char_type>{str[POS]},
+ format_str);
+ }
+ }
+}
+
+template <typename... Args, typename S,
+ FMT_ENABLE_IF(is_compile_string<S>::value ||
+ detail::is_compiled_string<S>::value)>
+constexpr auto compile(S format_str) {
+ constexpr basic_string_view<typename S::char_type> str = format_str;
+ if constexpr (str.size() == 0) {
+ return detail::make_text(str, 0, 0);
+ } else {
+ constexpr auto result =
+ detail::compile_format_string<detail::type_list<Args...>, 0, 0>(
+ format_str);
+ if constexpr (std::is_same<remove_cvref_t<decltype(result)>,
+ detail::unknown_format>()) {
+ return detail::compiled_format<S, Args...>(to_string_view(format_str));
+ } else {
+ return result;
+ }
+ }
+}
+#else
+template <typename... Args, typename S,
+ FMT_ENABLE_IF(is_compile_string<S>::value)>
+constexpr auto compile(S format_str) -> detail::compiled_format<S, Args...> {
+ return detail::compiled_format<S, Args...>(to_string_view(format_str));
+}
+#endif // __cpp_if_constexpr
+
+// Compiles the format string which must be a string literal.
+template <typename... Args, typename Char, size_t N>
+auto compile(const Char (&format_str)[N])
+ -> detail::compiled_format<const Char*, Args...> {
+ return detail::compiled_format<const Char*, Args...>(
+ basic_string_view<Char>(format_str, N - 1));
+}
+} // namespace detail
+
+// DEPRECATED! use FMT_COMPILE instead.
+template <typename... Args>
+FMT_DEPRECATED auto compile(const Args&... args)
+ -> decltype(detail::compile(args...)) {
+ return detail::compile(args...);
+}
+
+#if FMT_USE_CONSTEXPR
+# ifdef __cpp_if_constexpr
+
+template <typename CompiledFormat, typename... Args,
+ typename Char = typename CompiledFormat::char_type,
+ FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
+FMT_INLINE std::basic_string<Char> format(const CompiledFormat& cf,
+ const Args&... args) {
+ basic_memory_buffer<Char> buffer;
+ cf.format(detail::buffer_appender<Char>(buffer), args...);
+ return to_string(buffer);
+}
+
+template <typename OutputIt, typename CompiledFormat, typename... Args,
+ FMT_ENABLE_IF(detail::is_compiled_format<CompiledFormat>::value)>
+OutputIt format_to(OutputIt out, const CompiledFormat& cf,
+ const Args&... args) {
+ return cf.format(out, args...);
+}
+# endif // __cpp_if_constexpr
+#endif // FMT_USE_CONSTEXPR
+
+template <typename CompiledFormat, typename... Args,
+ typename Char = typename CompiledFormat::char_type,
+ FMT_ENABLE_IF(std::is_base_of<detail::basic_compiled_format,
+ CompiledFormat>::value)>
+std::basic_string<Char> format(const CompiledFormat& cf, const Args&... args) {
+ basic_memory_buffer<Char> buffer;
+ using context = buffer_context<Char>;
+ detail::cf::vformat_to<context>(detail::buffer_appender<Char>(buffer), cf,
+ make_format_args<context>(args...));
+ return to_string(buffer);
+}
+
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
+FMT_INLINE std::basic_string<typename S::char_type> format(const S&,
+ Args&&... args) {
+#ifdef __cpp_if_constexpr
+ if constexpr (std::is_same<typename S::char_type, char>::value) {
+ constexpr basic_string_view<typename S::char_type> str = S();
+ if (str.size() == 2 && str[0] == '{' && str[1] == '}')
+ return fmt::to_string(detail::first(args...));
+ }
+#endif
+ constexpr auto compiled = detail::compile<Args...>(S());
+ return format(compiled, std::forward<Args>(args)...);
+}
+
+template <typename OutputIt, typename CompiledFormat, typename... Args,
+ FMT_ENABLE_IF(std::is_base_of<detail::basic_compiled_format,
+ CompiledFormat>::value)>
+OutputIt format_to(OutputIt out, const CompiledFormat& cf,
+ const Args&... args) {
+ using char_type = typename CompiledFormat::char_type;
+ using context = format_context_t<OutputIt, char_type>;
+ return detail::cf::vformat_to<context>(out, cf,
+ make_format_args<context>(args...));
+}
+
+template <typename OutputIt, typename S, typename... Args,
+ FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
+OutputIt format_to(OutputIt out, const S&, const Args&... args) {
+ constexpr auto compiled = detail::compile<Args...>(S());
+ return format_to(out, compiled, args...);
+}
+
+template <typename OutputIt, typename CompiledFormat, typename... Args>
+auto format_to_n(OutputIt out, size_t n, const CompiledFormat& cf,
+ const Args&... args) ->
+ typename std::enable_if<
+ detail::is_output_iterator<OutputIt,
+ typename CompiledFormat::char_type>::value &&
+ std::is_base_of<detail::basic_compiled_format,
+ CompiledFormat>::value,
+ format_to_n_result<OutputIt>>::type {
+ auto it =
+ format_to(detail::truncating_iterator<OutputIt>(out, n), cf, args...);
+ return {it.base(), it.count()};
+}
+
+template <typename OutputIt, typename S, typename... Args,
+ FMT_ENABLE_IF(detail::is_compiled_string<S>::value)>
+format_to_n_result<OutputIt> format_to_n(OutputIt out, size_t n, const S&,
+ const Args&... args) {
+ constexpr auto compiled = detail::compile<Args...>(S());
+ auto it = format_to(detail::truncating_iterator<OutputIt>(out, n), compiled,
+ args...);
+ return {it.base(), it.count()};
+}
+
+template <typename CompiledFormat, typename... Args>
+size_t formatted_size(const CompiledFormat& cf, const Args&... args) {
+ return format_to(detail::counting_iterator(), cf, args...).count();
+}
+
+FMT_END_NAMESPACE
+
+#endif // FMT_COMPILE_H_
diff --git a/include/spdlog/fmt/bundled/core.h b/include/spdlog/fmt/bundled/core.h
new file mode 100644
index 00000000..0a81e0cc
--- /dev/null
+++ b/include/spdlog/fmt/bundled/core.h
@@ -0,0 +1,2122 @@
+// Formatting library for C++ - the core API
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_CORE_H_
+#define FMT_CORE_H_
+
+#include <cstdio> // std::FILE
+#include <cstring>
+#include <functional>
+#include <iterator>
+#include <memory>
+#include <string>
+#include <type_traits>
+#include <vector>
+
+// The fmt library version in the form major * 10000 + minor * 100 + patch.
+#define FMT_VERSION 70103
+
+#ifdef __clang__
+# define FMT_CLANG_VERSION (__clang_major__ * 100 + __clang_minor__)
+#else
+# define FMT_CLANG_VERSION 0
+#endif
+
+#if defined(__GNUC__) && !defined(__clang__)
+# define FMT_GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__)
+#else
+# define FMT_GCC_VERSION 0
+#endif
+
+#if defined(__INTEL_COMPILER)
+# define FMT_ICC_VERSION __INTEL_COMPILER
+#else
+# define FMT_ICC_VERSION 0
+#endif
+
+#if __cplusplus >= 201103L || defined(__GXX_EXPERIMENTAL_CXX0X__)
+# define FMT_HAS_GXX_CXX11 FMT_GCC_VERSION
+#else
+# define FMT_HAS_GXX_CXX11 0
+#endif
+
+#ifdef __NVCC__
+# define FMT_NVCC __NVCC__
+#else
+# define FMT_NVCC 0
+#endif
+
+#ifdef _MSC_VER
+# define FMT_MSC_VER _MSC_VER
+# define FMT_SUPPRESS_MSC_WARNING(n) __pragma(warning(suppress : n))
+#else
+# define FMT_MSC_VER 0
+# define FMT_SUPPRESS_MSC_WARNING(n)
+#endif
+
+#ifdef __has_feature
+# define FMT_HAS_FEATURE(x) __has_feature(x)
+#else
+# define FMT_HAS_FEATURE(x) 0
+#endif
+
+#if defined(__has_include) && !defined(__INTELLISENSE__) && \
+ (!FMT_ICC_VERSION || FMT_ICC_VERSION >= 1600)
+# define FMT_HAS_INCLUDE(x) __has_include(x)
+#else
+# define FMT_HAS_INCLUDE(x) 0
+#endif
+
+#ifdef __has_cpp_attribute
+# define FMT_HAS_CPP_ATTRIBUTE(x) __has_cpp_attribute(x)
+#else
+# define FMT_HAS_CPP_ATTRIBUTE(x) 0
+#endif
+
+#define FMT_HAS_CPP14_ATTRIBUTE(attribute) \
+ (__cplusplus >= 201402L && FMT_HAS_CPP_ATTRIBUTE(attribute))
+
+#define FMT_HAS_CPP17_ATTRIBUTE(attribute) \
+ (__cplusplus >= 201703L && FMT_HAS_CPP_ATTRIBUTE(attribute))
+
+// Check if relaxed C++14 constexpr is supported.
+// GCC doesn't allow throw in constexpr until version 6 (bug 67371).
+#ifndef FMT_USE_CONSTEXPR
+# define FMT_USE_CONSTEXPR \
+ (FMT_HAS_FEATURE(cxx_relaxed_constexpr) || FMT_MSC_VER >= 1910 || \
+ (FMT_GCC_VERSION >= 600 && __cplusplus >= 201402L)) && \
+ !FMT_NVCC && !FMT_ICC_VERSION
+#endif
+#if FMT_USE_CONSTEXPR
+# define FMT_CONSTEXPR constexpr
+# define FMT_CONSTEXPR_DECL constexpr
+#else
+# define FMT_CONSTEXPR inline
+# define FMT_CONSTEXPR_DECL
+#endif
+
+#ifndef FMT_OVERRIDE
+# if FMT_HAS_FEATURE(cxx_override_control) || \
+ (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
+# define FMT_OVERRIDE override
+# else
+# define FMT_OVERRIDE
+# endif
+#endif
+
+// Check if exceptions are disabled.
+#ifndef FMT_EXCEPTIONS
+# if (defined(__GNUC__) && !defined(__EXCEPTIONS)) || \
+ FMT_MSC_VER && !_HAS_EXCEPTIONS
+# define FMT_EXCEPTIONS 0
+# else
+# define FMT_EXCEPTIONS 1
+# endif
+#endif
+
+// Define FMT_USE_NOEXCEPT to make fmt use noexcept (C++11 feature).
+#ifndef FMT_USE_NOEXCEPT
+# define FMT_USE_NOEXCEPT 0
+#endif
+
+#if FMT_USE_NOEXCEPT || FMT_HAS_FEATURE(cxx_noexcept) || \
+ (FMT_GCC_VERSION >= 408 && FMT_HAS_GXX_CXX11) || FMT_MSC_VER >= 1900
+# define FMT_DETECTED_NOEXCEPT noexcept
+# define FMT_HAS_CXX11_NOEXCEPT 1
+#else
+# define FMT_DETECTED_NOEXCEPT throw()
+# define FMT_HAS_CXX11_NOEXCEPT 0
+#endif
+
+#ifndef FMT_NOEXCEPT
+# if FMT_EXCEPTIONS || FMT_HAS_CXX11_NOEXCEPT
+# define FMT_NOEXCEPT FMT_DETECTED_NOEXCEPT
+# else
+# define FMT_NOEXCEPT
+# endif
+#endif
+
+// [[noreturn]] is disabled on MSVC and NVCC because of bogus unreachable code
+// warnings.
+#if FMT_EXCEPTIONS && FMT_HAS_CPP_ATTRIBUTE(noreturn) && !FMT_MSC_VER && \
+ !FMT_NVCC
+# define FMT_NORETURN [[noreturn]]
+#else
+# define FMT_NORETURN
+#endif
+
+#ifndef FMT_DEPRECATED
+# if FMT_HAS_CPP14_ATTRIBUTE(deprecated) || FMT_MSC_VER >= 1900
+# define FMT_DEPRECATED [[deprecated]]
+# else
+# if (defined(__GNUC__) && !defined(__LCC__)) || defined(__clang__)
+# define FMT_DEPRECATED __attribute__((deprecated))
+# elif FMT_MSC_VER
+# define FMT_DEPRECATED __declspec(deprecated)
+# else
+# define FMT_DEPRECATED /* deprecated */
+# endif
+# endif
+#endif
+
+// Workaround broken [[deprecated]] in the Intel, PGI and NVCC compilers.
+#if FMT_ICC_VERSION || defined(__PGI) || FMT_NVCC
+# define FMT_DEPRECATED_ALIAS
+#else
+# define FMT_DEPRECATED_ALIAS FMT_DEPRECATED
+#endif
+
+#ifndef FMT_INLINE
+# if FMT_GCC_VERSION || FMT_CLANG_VERSION
+# define FMT_INLINE inline __attribute__((always_inline))
+# else
+# define FMT_INLINE inline
+# endif
+#endif
+
+#ifndef FMT_USE_INLINE_NAMESPACES
+# if FMT_HAS_FEATURE(cxx_inline_namespaces) || FMT_GCC_VERSION >= 404 || \
+ (FMT_MSC_VER >= 1900 && !_MANAGED)
+# define FMT_USE_INLINE_NAMESPACES 1
+# else
+# define FMT_USE_INLINE_NAMESPACES 0
+# endif
+#endif
+
+#ifndef FMT_BEGIN_NAMESPACE
+# if FMT_USE_INLINE_NAMESPACES
+# define FMT_INLINE_NAMESPACE inline namespace
+# define FMT_END_NAMESPACE \
+ } \
+ }
+# else
+# define FMT_INLINE_NAMESPACE namespace
+# define FMT_END_NAMESPACE \
+ } \
+ using namespace v7; \
+ }
+# endif
+# define FMT_BEGIN_NAMESPACE \
+ namespace fmt { \
+ FMT_INLINE_NAMESPACE v7 {
+#endif
+
+#if !defined(FMT_HEADER_ONLY) && defined(_WIN32)
+# define FMT_CLASS_API FMT_SUPPRESS_MSC_WARNING(4275)
+# ifdef FMT_EXPORT
+# define FMT_API __declspec(dllexport)
+# define FMT_EXTERN_TEMPLATE_API FMT_API
+# define FMT_EXPORTED
+# elif defined(FMT_SHARED)
+# define FMT_API __declspec(dllimport)
+# define FMT_EXTERN_TEMPLATE_API FMT_API
+# endif
+#else
+# define FMT_CLASS_API
+#endif
+#ifndef FMT_API
+# define FMT_API
+#endif
+#ifndef FMT_EXTERN_TEMPLATE_API
+# define FMT_EXTERN_TEMPLATE_API
+#endif
+#ifndef FMT_INSTANTIATION_DEF_API
+# define FMT_INSTANTIATION_DEF_API FMT_API
+#endif
+
+#ifndef FMT_HEADER_ONLY
+# define FMT_EXTERN extern
+#else
+# define FMT_EXTERN
+#endif
+
+// libc++ supports string_view in pre-c++17.
+#if (FMT_HAS_INCLUDE(<string_view>) && \
+ (__cplusplus > 201402L || defined(_LIBCPP_VERSION))) || \
+ (defined(_MSVC_LANG) && _MSVC_LANG > 201402L && _MSC_VER >= 1910)
+# include <string_view>
+# define FMT_USE_STRING_VIEW
+#elif FMT_HAS_INCLUDE("experimental/string_view") && __cplusplus >= 201402L
+# include <experimental/string_view>
+# define FMT_USE_EXPERIMENTAL_STRING_VIEW
+#endif
+
+#ifndef FMT_UNICODE
+# define FMT_UNICODE !FMT_MSC_VER
+#endif
+#if FMT_UNICODE && FMT_MSC_VER
+# pragma execution_character_set("utf-8")
+#endif
+
+FMT_BEGIN_NAMESPACE
+
+// Implementations of enable_if_t and other metafunctions for older systems.
+template <bool B, class T = void>
+using enable_if_t = typename std::enable_if<B, T>::type;
+template <bool B, class T, class F>
+using conditional_t = typename std::conditional<B, T, F>::type;
+template <bool B> using bool_constant = std::integral_constant<bool, B>;
+template <typename T>
+using remove_reference_t = typename std::remove_reference<T>::type;
+template <typename T>
+using remove_const_t = typename std::remove_const<T>::type;
+template <typename T>
+using remove_cvref_t = typename std::remove_cv<remove_reference_t<T>>::type;
+template <typename T> struct type_identity { using type = T; };
+template <typename T> using type_identity_t = typename type_identity<T>::type;
+
+struct monostate {};
+
+// An enable_if helper to be used in template parameters which results in much
+// shorter symbols: https://godbolt.org/z/sWw4vP. Extra parentheses are needed
+// to workaround a bug in MSVC 2019 (see #1140 and #1186).
+#define FMT_ENABLE_IF(...) enable_if_t<(__VA_ARGS__), int> = 0
+
+namespace detail {
+
+// A helper function to suppress "conditional expression is constant" warnings.
+template <typename T> constexpr T const_check(T value) { return value; }
+
+FMT_NORETURN FMT_API void assert_fail(const char* file, int line,
+ const char* message);
+
+#ifndef FMT_ASSERT
+# ifdef NDEBUG
+// FMT_ASSERT is not empty to avoid -Werror=empty-body.
+# define FMT_ASSERT(condition, message) ((void)0)
+# else
+# define FMT_ASSERT(condition, message) \
+ ((condition) /* void() fails with -Winvalid-constexpr on clang 4.0.1 */ \
+ ? (void)0 \
+ : ::fmt::detail::assert_fail(__FILE__, __LINE__, (message)))
+# endif
+#endif
+
+#if defined(FMT_USE_STRING_VIEW)
+template <typename Char> using std_string_view = std::basic_string_view<Char>;
+#elif defined(FMT_USE_EXPERIMENTAL_STRING_VIEW)
+template <typename Char>
+using std_string_view = std::experimental::basic_string_view<Char>;
+#else
+template <typename T> struct std_string_view {};
+#endif
+
+#ifdef FMT_USE_INT128
+// Do nothing.
+#elif defined(__SIZEOF_INT128__) && !FMT_NVCC && \
+ !(FMT_CLANG_VERSION && FMT_MSC_VER)
+# define FMT_USE_INT128 1
+using int128_t = __int128_t;
+using uint128_t = __uint128_t;
+#else
+# define FMT_USE_INT128 0
+#endif
+#if !FMT_USE_INT128
+struct int128_t {};
+struct uint128_t {};
+#endif
+
+// Casts a nonnegative integer to unsigned.
+template <typename Int>
+FMT_CONSTEXPR typename std::make_unsigned<Int>::type to_unsigned(Int value) {
+ FMT_ASSERT(value >= 0, "negative value");
+ return static_cast<typename std::make_unsigned<Int>::type>(value);
+}
+
+FMT_SUPPRESS_MSC_WARNING(4566) constexpr unsigned char micro[] = "\u00B5";
+
+template <typename Char> constexpr bool is_unicode() {
+ return FMT_UNICODE || sizeof(Char) != 1 ||
+ (sizeof(micro) == 3 && micro[0] == 0xC2 && micro[1] == 0xB5);
+}
+
+#ifdef __cpp_char8_t
+using char8_type = char8_t;
+#else
+enum char8_type : unsigned char {};
+#endif
+} // namespace detail
+
+#ifdef FMT_USE_INTERNAL
+namespace internal = detail; // DEPRECATED
+#endif
+
+/**
+ An implementation of ``std::basic_string_view`` for pre-C++17. It provides a
+ subset of the API. ``fmt::basic_string_view`` is used for format strings even
+ if ``std::string_view`` is available to prevent issues when a library is
+ compiled with a different ``-std`` option than the client code (which is not
+ recommended).
+ */
+template <typename Char> class basic_string_view {
+ private:
+ const Char* data_;
+ size_t size_;
+
+ public:
+ using value_type = Char;
+ using iterator = const Char*;
+
+ constexpr basic_string_view() FMT_NOEXCEPT : data_(nullptr), size_(0) {}
+
+ /** Constructs a string reference object from a C string and a size. */
+ constexpr basic_string_view(const Char* s, size_t count) FMT_NOEXCEPT
+ : data_(s),
+ size_(count) {}
+
+ /**
+ \rst
+ Constructs a string reference object from a C string computing
+ the size with ``std::char_traits<Char>::length``.
+ \endrst
+ */
+#if __cplusplus >= 201703L // C++17's char_traits::length() is constexpr.
+ FMT_CONSTEXPR
+#endif
+ basic_string_view(const Char* s)
+ : data_(s), size_(std::char_traits<Char>::length(s)) {}
+
+ /** Constructs a string reference from a ``std::basic_string`` object. */
+ template <typename Traits, typename Alloc>
+ FMT_CONSTEXPR basic_string_view(
+ const std::basic_string<Char, Traits, Alloc>& s) FMT_NOEXCEPT
+ : data_(s.data()),
+ size_(s.size()) {}
+
+ template <typename S, FMT_ENABLE_IF(std::is_same<
+ S, detail::std_string_view<Char>>::value)>
+ FMT_CONSTEXPR basic_string_view(S s) FMT_NOEXCEPT : data_(s.data()),
+ size_(s.size()) {}
+
+ /** Returns a pointer to the string data. */
+ constexpr const Char* data() const { return data_; }
+
+ /** Returns the string size. */
+ constexpr size_t size() const { return size_; }
+
+ constexpr iterator begin() const { return data_; }
+ constexpr iterator end() const { return data_ + size_; }
+
+ constexpr const Char& operator[](size_t pos) const { return data_[pos]; }
+
+ FMT_CONSTEXPR void remove_prefix(size_t n) {
+ data_ += n;
+ size_ -= n;
+ }
+
+ // Lexicographically compare this string reference to other.
+ int compare(basic_string_view other) const {
+ size_t str_size = size_ < other.size_ ? size_ : other.size_;
+ int result = std::char_traits<Char>::compare(data_, other.data_, str_size);
+ if (result == 0)
+ result = size_ == other.size_ ? 0 : (size_ < other.size_ ? -1 : 1);
+ return result;
+ }
+
+ friend bool operator==(basic_string_view lhs, basic_string_view rhs) {
+ return lhs.compare(rhs) == 0;
+ }
+ friend bool operator!=(basic_string_view lhs, basic_string_view rhs) {
+ return lhs.compare(rhs) != 0;
+ }
+ friend bool operator<(basic_string_view lhs, basic_string_view rhs) {
+ return lhs.compare(rhs) < 0;
+ }
+ friend bool operator<=(basic_string_view lhs, basic_string_view rhs) {
+ return lhs.compare(rhs) <= 0;
+ }
+ friend bool operator>(basic_string_view lhs, basic_string_view rhs) {
+ return lhs.compare(rhs) > 0;
+ }
+ friend bool operator>=(basic_string_view lhs, basic_string_view rhs) {
+ return lhs.compare(rhs) >= 0;
+ }
+};
+
+using string_view = basic_string_view<char>;
+using wstring_view = basic_string_view<wchar_t>;
+
+/** Specifies if ``T`` is a character type. Can be specialized by users. */
+template <typename T> struct is_char : std::false_type {};
+template <> struct is_char<char> : std::true_type {};
+template <> struct is_char<wchar_t> : std::true_type {};
+template <> struct is_char<detail::char8_type> : std::true_type {};
+template <> struct is_char<char16_t> : std::true_type {};
+template <> struct is_char<char32_t> : std::true_type {};
+
+/**
+ \rst
+ Returns a string view of `s`. In order to add custom string type support to
+ {fmt} provide an overload of `to_string_view` for it in the same namespace as
+ the type for the argument-dependent lookup to work.
+
+ **Example**::
+
+ namespace my_ns {
+ inline string_view to_string_view(const my_string& s) {
+ return {s.data(), s.length()};
+ }
+ }
+ std::string message = fmt::format(my_string("The answer is {}"), 42);
+ \endrst
+ */
+template <typename Char, FMT_ENABLE_IF(is_char<Char>::value)>
+inline basic_string_view<Char> to_string_view(const Char* s) {
+ return s;
+}
+
+template <typename Char, typename Traits, typename Alloc>
+inline basic_string_view<Char> to_string_view(
+ const std::basic_string<Char, Traits, Alloc>& s) {
+ return s;
+}
+
+template <typename Char>
+inline basic_string_view<Char> to_string_view(basic_string_view<Char> s) {
+ return s;
+}
+
+template <typename Char,
+ FMT_ENABLE_IF(!std::is_empty<detail::std_string_view<Char>>::value)>
+inline basic_string_view<Char> to_string_view(detail::std_string_view<Char> s) {
+ return s;
+}
+
+// A base class for compile-time strings. It is defined in the fmt namespace to
+// make formatting functions visible via ADL, e.g. format(FMT_STRING("{}"), 42).
+struct compile_string {};
+
+template <typename S>
+struct is_compile_string : std::is_base_of<compile_string, S> {};
+
+template <typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
+constexpr basic_string_view<typename S::char_type> to_string_view(const S& s) {
+ return s;
+}
+
+namespace detail {
+void to_string_view(...);
+using fmt::v7::to_string_view;
+
+// Specifies whether S is a string type convertible to fmt::basic_string_view.
+// It should be a constexpr function but MSVC 2017 fails to compile it in
+// enable_if and MSVC 2015 fails to compile it as an alias template.
+template <typename S>
+struct is_string : std::is_class<decltype(to_string_view(std::declval<S>()))> {
+};
+
+template <typename S, typename = void> struct char_t_impl {};
+template <typename S> struct char_t_impl<S, enable_if_t<is_string<S>::value>> {
+ using result = decltype(to_string_view(std::declval<S>()));
+ using type = typename result::value_type;
+};
+
+// Reports a compile-time error if S is not a valid format string.
+template <typename..., typename S, FMT_ENABLE_IF(!is_compile_string<S>::value)>
+FMT_INLINE void check_format_string(const S&) {
+#ifdef FMT_ENFORCE_COMPILE_STRING
+ static_assert(is_compile_string<S>::value,
+ "FMT_ENFORCE_COMPILE_STRING requires all format strings to use "
+ "FMT_STRING.");
+#endif
+}
+template <typename..., typename S, FMT_ENABLE_IF(is_compile_string<S>::value)>
+void check_format_string(S);
+
+struct error_handler {
+ constexpr error_handler() = default;
+ constexpr error_handler(const error_handler&) = default;
+
+ // This function is intentionally not constexpr to give a compile-time error.
+ FMT_NORETURN FMT_API void on_error(const char* message);
+};
+} // namespace detail
+
+/** String's character type. */
+template <typename S> using char_t = typename detail::char_t_impl<S>::type;
+
+/**
+ \rst
+ Parsing context consisting of a format string range being parsed and an
+ argument counter for automatic indexing.
+
+ You can use one of the following type aliases for common character types:
+
+ +-----------------------+-------------------------------------+
+ | Type | Definition |
+ +=======================+=====================================+
+ | format_parse_context | basic_format_parse_context<char> |
+ +-----------------------+-------------------------------------+
+ | wformat_parse_context | basic_format_parse_context<wchar_t> |
+ +-----------------------+-------------------------------------+
+ \endrst
+ */
+template <typename Char, typename ErrorHandler = detail::error_handler>
+class basic_format_parse_context : private ErrorHandler {
+ private:
+ basic_string_view<Char> format_str_;
+ int next_arg_id_;
+
+ public:
+ using char_type = Char;
+ using iterator = typename basic_string_view<Char>::iterator;
+
+ explicit constexpr basic_format_parse_context(
+ basic_string_view<Char> format_str, ErrorHandler eh = {},
+ int next_arg_id = 0)
+ : ErrorHandler(eh), format_str_(format_str), next_arg_id_(next_arg_id) {}
+
+ /**
+ Returns an iterator to the beginning of the format string range being
+ parsed.
+ */
+ constexpr iterator begin() const FMT_NOEXCEPT { return format_str_.begin(); }
+
+ /**
+ Returns an iterator past the end of the format string range being parsed.
+ */
+ constexpr iterator end() const FMT_NOEXCEPT { return format_str_.end(); }
+
+ /** Advances the begin iterator to ``it``. */
+ FMT_CONSTEXPR void advance_to(iterator it) {
+ format_str_.remove_prefix(detail::to_unsigned(it - begin()));
+ }
+
+ /**
+ Reports an error if using the manual argument indexing; otherwise returns
+ the next argument index and switches to the automatic indexing.
+ */
+ FMT_CONSTEXPR int next_arg_id() {
+ // Don't check if the argument id is valid to avoid overhead and because it
+ // will be checked during formatting anyway.
+ if (next_arg_id_ >= 0) return next_arg_id_++;
+ on_error("cannot switch from manual to automatic argument indexing");
+ return 0;
+ }
+
+ /**
+ Reports an error if using the automatic argument indexing; otherwise
+ switches to the manual indexing.
+ */
+ FMT_CONSTEXPR void check_arg_id(int) {
+ if (next_arg_id_ > 0)
+ on_error("cannot switch from automatic to manual argument indexing");
+ else
+ next_arg_id_ = -1;
+ }
+
+ FMT_CONSTEXPR void check_arg_id(basic_string_view<Char>) {}
+
+ FMT_CONSTEXPR void on_error(const char* message) {
+ ErrorHandler::on_error(message);
+ }
+
+ constexpr ErrorHandler error_handler() const { return *this; }
+};
+
+using format_parse_context = basic_format_parse_context<char>;
+using wformat_parse_context = basic_format_parse_context<wchar_t>;
+
+template <typename Context> class basic_format_arg;
+template <typename Context> class basic_format_args;
+template <typename Context> class dynamic_format_arg_store;
+
+// A formatter for objects of type T.
+template <typename T, typename Char = char, typename Enable = void>
+struct formatter {
+ // A deleted default constructor indicates a disabled formatter.
+ formatter() = delete;
+};
+
+// Specifies if T has an enabled formatter specialization. A type can be
+// formattable even if it doesn't have a formatter e.g. via a conversion.
+template <typename T, typename Context>
+using has_formatter =
+ std::is_constructible<typename Context::template formatter_type<T>>;
+
+// Checks whether T is a container with contiguous storage.
+template <typename T> struct is_contiguous : std::false_type {};
+template <typename Char>
+struct is_contiguous<std::basic_string<Char>> : std::true_type {};
+
+namespace detail {
+
+// Extracts a reference to the container from back_insert_iterator.
+template <typename Container>
+inline Container& get_container(std::back_insert_iterator<Container> it) {
+ using bi_iterator = std::back_insert_iterator<Container>;
+ struct accessor : bi_iterator {
+ accessor(bi_iterator iter) : bi_iterator(iter) {}
+ using bi_iterator::container;
+ };
+ return *accessor(it).container;
+}
+
+/**
+ \rst
+ A contiguous memory buffer with an optional growing ability. It is an internal
+ class and shouldn't be used directly, only via `~fmt::basic_memory_buffer`.
+ \endrst
+ */
+template <typename T> class buffer {
+ private:
+ T* ptr_;
+ size_t size_;
+ size_t capacity_;
+
+ protected:
+ // Don't initialize ptr_ since it is not accessed to save a few cycles.
+ FMT_SUPPRESS_MSC_WARNING(26495)
+ buffer(size_t sz) FMT_NOEXCEPT : size_(sz), capacity_(sz) {}
+
+ buffer(T* p = nullptr, size_t sz = 0, size_t cap = 0) FMT_NOEXCEPT
+ : ptr_(p),
+ size_(sz),
+ capacity_(cap) {}
+
+ ~buffer() = default;
+
+ /** Sets the buffer data and capacity. */
+ void set(T* buf_data, size_t buf_capacity) FMT_NOEXCEPT {
+ ptr_ = buf_data;
+ capacity_ = buf_capacity;
+ }
+
+ /** Increases the buffer capacity to hold at least *capacity* elements. */
+ virtual void grow(size_t capacity) = 0;
+
+ public:
+ using value_type = T;
+ using const_reference = const T&;
+
+ buffer(const buffer&) = delete;
+ void operator=(const buffer&) = delete;
+
+ T* begin() FMT_NOEXCEPT { return ptr_; }
+ T* end() FMT_NOEXCEPT { return ptr_ + size_; }
+
+ const T* begin() const FMT_NOEXCEPT { return ptr_; }
+ const T* end() const FMT_NOEXCEPT { return ptr_ + size_; }
+
+ /** Returns the size of this buffer. */
+ size_t size() const FMT_NOEXCEPT { return size_; }
+
+ /** Returns the capacity of this buffer. */
+ size_t capacity() const FMT_NOEXCEPT { return capacity_; }
+
+ /** Returns a pointer to the buffer data. */
+ T* data() FMT_NOEXCEPT { return ptr_; }
+
+ /** Returns a pointer to the buffer data. */
+ const T* data() const FMT_NOEXCEPT { return ptr_; }
+
+ /** Clears this buffer. */
+ void clear() { size_ = 0; }
+
+ // Tries resizing the buffer to contain *count* elements. If T is a POD type
+ // the new elements may not be initialized.
+ void try_resize(size_t count) {
+ try_reserve(count);
+ size_ = count <= capacity_ ? count : capacity_;
+ }
+
+ // Tries increasing the buffer capacity to *new_capacity*. It can increase the
+ // capacity by a smaller amount than requested but guarantees there is space
+ // for at least one additional element either by increasing the capacity or by
+ // flushing the buffer if it is full.
+ void try_reserve(size_t new_capacity) {
+ if (new_capacity > capacity_) grow(new_capacity);
+ }
+
+ void push_back(const T& value) {
+ try_reserve(size_ + 1);
+ ptr_[size_++] = value;
+ }
+
+ /** Appends data to the end of the buffer. */
+ template <typename U> void append(const U* begin, const U* end);
+
+ template <typename I> T& operator[](I index) { return ptr_[index]; }
+ template <typename I> const T& operator[](I index) const {
+ return ptr_[index];
+ }
+};
+
+struct buffer_traits {
+ explicit buffer_traits(size_t) {}
+ size_t count() const { return 0; }
+ size_t limit(size_t size) { return size; }
+};
+
+class fixed_buffer_traits {
+ private:
+ size_t count_ = 0;
+ size_t limit_;
+
+ public:
+ explicit fixed_buffer_traits(size_t limit) : limit_(limit) {}
+ size_t count() const { return count_; }
+ size_t limit(size_t size) {
+ size_t n = limit_ > count_ ? limit_ - count_ : 0;
+ count_ += size;
+ return size < n ? size : n;
+ }
+};
+
+// A buffer that writes to an output iterator when flushed.
+template <typename OutputIt, typename T, typename Traits = buffer_traits>
+class iterator_buffer final : public Traits, public buffer<T> {
+ private:
+ OutputIt out_;
+ enum { buffer_size = 256 };
+ T data_[buffer_size];
+
+ protected:
+ void grow(size_t) final FMT_OVERRIDE {
+ if (this->size() == buffer_size) flush();
+ }
+ void flush();
+
+ public:
+ explicit iterator_buffer(OutputIt out, size_t n = buffer_size)
+ : Traits(n),
+ buffer<T>(data_, 0, buffer_size),
+ out_(out) {}
+ ~iterator_buffer() { flush(); }
+
+ OutputIt out() {
+ flush();
+ return out_;
+ }
+ size_t count() const { return Traits::count() + this->size(); }
+};
+
+template <typename T> class iterator_buffer<T*, T> final : public buffer<T> {
+ protected:
+ void grow(size_t) final FMT_OVERRIDE {}
+
+ public:
+ explicit iterator_buffer(T* out, size_t = 0) : buffer<T>(out, 0, ~size_t()) {}
+
+ T* out() { return &*this->end(); }
+};
+
+// A buffer that writes to a container with the contiguous storage.
+template <typename Container>
+class iterator_buffer<std::back_insert_iterator<Container>,
+ enable_if_t<is_contiguous<Container>::value,
+ typename Container::value_type>>
+ final : public buffer<typename Container::value_type> {
+ private:
+ Container& container_;
+
+ protected:
+ void grow(size_t capacity) final FMT_OVERRIDE {
+ container_.resize(capacity);
+ this->set(&container_[0], capacity);
+ }
+
+ public:
+ explicit iterator_buffer(Container& c)
+ : buffer<typename Container::value_type>(c.size()), container_(c) {}
+ explicit iterator_buffer(std::back_insert_iterator<Container> out, size_t = 0)
+ : iterator_buffer(get_container(out)) {}
+ std::back_insert_iterator<Container> out() {
+ return std::back_inserter(container_);
+ }
+};
+
+// A buffer that counts the number of code units written discarding the output.
+template <typename T = char> class counting_buffer final : public buffer<T> {
+ private:
+ enum { buffer_size = 256 };
+ T data_[buffer_size];
+ size_t count_ = 0;
+
+ protected:
+ void grow(size_t) final FMT_OVERRIDE {
+ if (this->size() != buffer_size) return;
+ count_ += this->size();
+ this->clear();
+ }
+
+ public:
+ counting_buffer() : buffer<T>(data_, 0, buffer_size) {}
+
+ size_t count() { return count_ + this->size(); }
+};
+
+// An output iterator that appends to the buffer.
+// It is used to reduce symbol sizes for the common case.
+template <typename T>
+class buffer_appender : public std::back_insert_iterator<buffer<T>> {
+ using base = std::back_insert_iterator<buffer<T>>;
+
+ public:
+ explicit buffer_appender(buffer<T>& buf) : base(buf) {}
+ buffer_appender(base it) : base(it) {}
+
+ buffer_appender& operator++() {
+ base::operator++();
+ return *this;
+ }
+
+ buffer_appender operator++(int) {
+ buffer_appender tmp = *this;
+ ++*this;
+ return tmp;
+ }
+};
+
+// Maps an output iterator into a buffer.
+template <typename T, typename OutputIt>
+iterator_buffer<OutputIt, T> get_buffer(OutputIt);
+template <typename T> buffer<T>& get_buffer(buffer_appender<T>);
+
+template <typename OutputIt> OutputIt get_buffer_init(OutputIt out) {
+ return out;
+}
+template <typename T> buffer<T>& get_buffer_init(buffer_appender<T> out) {
+ return get_container(out);
+}
+
+template <typename Buffer>
+auto get_iterator(Buffer& buf) -> decltype(buf.out()) {
+ return buf.out();
+}
+template <typename T> buffer_appender<T> get_iterator(buffer<T>& buf) {
+ return buffer_appender<T>(buf);
+}
+
+template <typename T, typename Char = char, typename Enable = void>
+struct fallback_formatter {
+ fallback_formatter() = delete;
+};
+
+// Specifies if T has an enabled fallback_formatter specialization.
+template <typename T, typename Context>
+using has_fallback_formatter =
+ std::is_constructible<fallback_formatter<T, typename Context::char_type>>;
+
+struct view {};
+
+template <typename Char, typename T> struct named_arg : view {
+ const Char* name;
+ const T& value;
+ named_arg(const Char* n, const T& v) : name(n), value(v) {}
+};
+
+template <typename Char> struct named_arg_info {
+ const Char* name;
+ int id;
+};
+
+template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
+struct arg_data {
+ // args_[0].named_args points to named_args_ to avoid bloating format_args.
+ // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
+ T args_[1 + (NUM_ARGS != 0 ? NUM_ARGS : +1)];
+ named_arg_info<Char> named_args_[NUM_NAMED_ARGS];
+
+ template <typename... U>
+ arg_data(const U&... init) : args_{T(named_args_, NUM_NAMED_ARGS), init...} {}
+ arg_data(const arg_data& other) = delete;
+ const T* args() const { return args_ + 1; }
+ named_arg_info<Char>* named_args() { return named_args_; }
+};
+
+template <typename T, typename Char, size_t NUM_ARGS>
+struct arg_data<T, Char, NUM_ARGS, 0> {
+ // +1 to workaround a bug in gcc 7.5 that causes duplicated-branches warning.
+ T args_[NUM_ARGS != 0 ? NUM_ARGS : +1];
+
+ template <typename... U>
+ FMT_INLINE arg_data(const U&... init) : args_{init...} {}
+ FMT_INLINE const T* args() const { return args_; }
+ FMT_INLINE std::nullptr_t named_args() { return nullptr; }
+};
+
+template <typename Char>
+inline void init_named_args(named_arg_info<Char>*, int, int) {}
+
+template <typename Char, typename T, typename... Tail>
+void init_named_args(named_arg_info<Char>* named_args, int arg_count,
+ int named_arg_count, const T&, const Tail&... args) {
+ init_named_args(named_args, arg_count + 1, named_arg_count, args...);
+}
+
+template <typename Char, typename T, typename... Tail>
+void init_named_args(named_arg_info<Char>* named_args, int arg_count,
+ int named_arg_count, const named_arg<Char, T>& arg,
+ const Tail&... args) {
+ named_args[named_arg_count++] = {arg.name, arg_count};
+ init_named_args(named_args, arg_count + 1, named_arg_count, args...);
+}
+
+template <typename... Args>
+FMT_INLINE void init_named_args(std::nullptr_t, int, int, const Args&...) {}
+
+template <typename T> struct is_named_arg : std::false_type {};
+
+template <typename T, typename Char>
+struct is_named_arg<named_arg<Char, T>> : std::true_type {};
+
+template <bool B = false> constexpr size_t count() { return B ? 1 : 0; }
+template <bool B1, bool B2, bool... Tail> constexpr size_t count() {
+ return (B1 ? 1 : 0) + count<B2, Tail...>();
+}
+
+template <typename... Args> constexpr size_t count_named_args() {
+ return count<is_named_arg<Args>::value...>();
+}
+
+enum class type {
+ none_type,
+ // Integer types should go first,
+ int_type,
+ uint_type,
+ long_long_type,
+ ulong_long_type,
+ int128_type,
+ uint128_type,
+ bool_type,
+ char_type,
+ last_integer_type = char_type,
+ // followed by floating-point types.
+ float_type,
+ double_type,
+ long_double_type,
+ last_numeric_type = long_double_type,
+ cstring_type,
+ string_type,
+ pointer_type,
+ custom_type
+};
+
+// Maps core type T to the corresponding type enum constant.
+template <typename T, typename Char>
+struct type_constant : std::integral_constant<type, type::custom_type> {};
+
+#define FMT_TYPE_CONSTANT(Type, constant) \
+ template <typename Char> \
+ struct type_constant<Type, Char> \
+ : std::integral_constant<type, type::constant> {}
+
+FMT_TYPE_CONSTANT(int, int_type);
+FMT_TYPE_CONSTANT(unsigned, uint_type);
+FMT_TYPE_CONSTANT(long long, long_long_type);
+FMT_TYPE_CONSTANT(unsigned long long, ulong_long_type);
+FMT_TYPE_CONSTANT(int128_t, int128_type);
+FMT_TYPE_CONSTANT(uint128_t, uint128_type);
+FMT_TYPE_CONSTANT(bool, bool_type);
+FMT_TYPE_CONSTANT(Char, char_type);
+FMT_TYPE_CONSTANT(float, float_type);
+FMT_TYPE_CONSTANT(double, double_type);
+FMT_TYPE_CONSTANT(long double, long_double_type);
+FMT_TYPE_CONSTANT(const Char*, cstring_type);
+FMT_TYPE_CONSTANT(basic_string_view<Char>, string_type);
+FMT_TYPE_CONSTANT(const void*, pointer_type);
+
+constexpr bool is_integral_type(type t) {
+ return t > type::none_type && t <= type::last_integer_type;
+}
+
+constexpr bool is_arithmetic_type(type t) {
+ return t > type::none_type && t <= type::last_numeric_type;
+}
+
+template <typename Char> struct string_value {
+ const Char* data;
+ size_t size;
+};
+
+template <typename Char> struct named_arg_value {
+ const named_arg_info<Char>* data;
+ size_t size;
+};
+
+template <typename Context> struct custom_value {
+ using parse_context = typename Context::parse_context_type;
+ const void* value;
+ void (*format)(const void* arg, parse_context& parse_ctx, Context& ctx);
+};
+
+// A formatting argument value.
+template <typename Context> class value {
+ public:
+ using char_type = typename Context::char_type;
+
+ union {
+ int int_value;
+ unsigned uint_value;
+ long long long_long_value;
+ unsigned long long ulong_long_value;
+ int128_t int128_value;
+ uint128_t uint128_value;
+ bool bool_value;
+ char_type char_value;
+ float float_value;
+ double double_value;
+ long double long_double_value;
+ const void* pointer;
+ string_value<char_type> string;
+ custom_value<Context> custom;
+ named_arg_value<char_type> named_args;
+ };
+
+ constexpr FMT_INLINE value(int val = 0) : int_value(val) {}
+ constexpr FMT_INLINE value(unsigned val) : uint_value(val) {}
+ FMT_INLINE value(long long val) : long_long_value(val) {}
+ FMT_INLINE value(unsigned long long val) : ulong_long_value(val) {}
+ FMT_INLINE value(int128_t val) : int128_value(val) {}
+ FMT_INLINE value(uint128_t val) : uint128_value(val) {}
+ FMT_INLINE value(float val) : float_value(val) {}
+ FMT_INLINE value(double val) : double_value(val) {}
+ FMT_INLINE value(long double val) : long_double_value(val) {}
+ FMT_INLINE value(bool val) : bool_value(val) {}
+ FMT_INLINE value(char_type val) : char_value(val) {}
+ FMT_INLINE value(const char_type* val) { string.data = val; }
+ FMT_INLINE value(basic_string_view<char_type> val) {
+ string.data = val.data();
+ string.size = val.size();
+ }
+ FMT_INLINE value(const void* val) : pointer(val) {}
+ FMT_INLINE value(const named_arg_info<char_type>* args, size_t size)
+ : named_args{args, size} {}
+
+ template <typename T> FMT_INLINE value(const T& val) {
+ custom.value = &val;
+ // Get the formatter type through the context to allow different contexts
+ // have different extension points, e.g. `formatter<T>` for `format` and
+ // `printf_formatter<T>` for `printf`.
+ custom.format = format_custom_arg<
+ T, conditional_t<has_formatter<T, Context>::value,
+ typename Context::template formatter_type<T>,
+ fallback_formatter<T, char_type>>>;
+ }
+
+ private:
+ // Formats an argument of a custom type, such as a user-defined class.
+ template <typename T, typename Formatter>
+ static void format_custom_arg(const void* arg,
+ typename Context::parse_context_type& parse_ctx,
+ Context& ctx) {
+ Formatter f;
+ parse_ctx.advance_to(f.parse(parse_ctx));
+ ctx.advance_to(f.format(*static_cast<const T*>(arg), ctx));
+ }
+};
+
+template <typename Context, typename T>
+FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value);
+
+// To minimize the number of types we need to deal with, long is translated
+// either to int or to long long depending on its size.
+enum { long_short = sizeof(long) == sizeof(int) };
+using long_type = conditional_t<long_short, int, long long>;
+using ulong_type = conditional_t<long_short, unsigned, unsigned long long>;
+
+struct unformattable {};
+
+// Maps formatting arguments to core types.
+template <typename Context> struct arg_mapper {
+ using char_type = typename Context::char_type;
+
+ FMT_CONSTEXPR int map(signed char val) { return val; }
+ FMT_CONSTEXPR unsigned map(unsigned char val) { return val; }
+ FMT_CONSTEXPR int map(short val) { return val; }
+ FMT_CONSTEXPR unsigned map(unsigned short val) { return val; }
+ FMT_CONSTEXPR int map(int val) { return val; }
+ FMT_CONSTEXPR unsigned map(unsigned val) { return val; }
+ FMT_CONSTEXPR long_type map(long val) { return val; }
+ FMT_CONSTEXPR ulong_type map(unsigned long val) { return val; }
+ FMT_CONSTEXPR long long map(long long val) { return val; }
+ FMT_CONSTEXPR unsigned long long map(unsigned long long val) { return val; }
+ FMT_CONSTEXPR int128_t map(int128_t val) { return val; }
+ FMT_CONSTEXPR uint128_t map(uint128_t val) { return val; }
+ FMT_CONSTEXPR bool map(bool val) { return val; }
+
+ template <typename T, FMT_ENABLE_IF(is_char<T>::value)>
+ FMT_CONSTEXPR char_type map(T val) {
+ static_assert(
+ std::is_same<T, char>::value || std::is_same<T, char_type>::value,
+ "mixing character types is disallowed");
+ return val;
+ }
+
+ FMT_CONSTEXPR float map(float val) { return val; }
+ FMT_CONSTEXPR double map(double val) { return val; }
+ FMT_CONSTEXPR long double map(long double val) { return val; }
+
+ FMT_CONSTEXPR const char_type* map(char_type* val) { return val; }
+ FMT_CONSTEXPR const char_type* map(const char_type* val) { return val; }
+ template <typename T, FMT_ENABLE_IF(is_string<T>::value)>
+ FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
+ static_assert(std::is_same<char_type, char_t<T>>::value,
+ "mixing character types is disallowed");
+ return to_string_view(val);
+ }
+ template <typename T,
+ FMT_ENABLE_IF(
+ std::is_constructible<basic_string_view<char_type>, T>::value &&
+ !is_string<T>::value && !has_formatter<T, Context>::value &&
+ !has_fallback_formatter<T, Context>::value)>
+ FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
+ return basic_string_view<char_type>(val);
+ }
+ template <
+ typename T,
+ FMT_ENABLE_IF(
+ std::is_constructible<std_string_view<char_type>, T>::value &&
+ !std::is_constructible<basic_string_view<char_type>, T>::value &&
+ !is_string<T>::value && !has_formatter<T, Context>::value &&
+ !has_fallback_formatter<T, Context>::value)>
+ FMT_CONSTEXPR basic_string_view<char_type> map(const T& val) {
+ return std_string_view<char_type>(val);
+ }
+ FMT_CONSTEXPR const char* map(const signed char* val) {
+ static_assert(std::is_same<char_type, char>::value, "invalid string type");
+ return reinterpret_cast<const char*>(val);
+ }
+ FMT_CONSTEXPR const char* map(const unsigned char* val) {
+ static_assert(std::is_same<char_type, char>::value, "invalid string type");
+ return reinterpret_cast<const char*>(val);
+ }
+ FMT_CONSTEXPR const char* map(signed char* val) {
+ const auto* const_val = val;
+ return map(const_val);
+ }
+ FMT_CONSTEXPR const char* map(unsigned char* val) {
+ const auto* const_val = val;
+ return map(const_val);
+ }
+
+ FMT_CONSTEXPR const void* map(void* val) { return val; }
+ FMT_CONSTEXPR const void* map(const void* val) { return val; }
+ FMT_CONSTEXPR const void* map(std::nullptr_t val) { return val; }
+ template <typename T> FMT_CONSTEXPR int map(const T*) {
+ // Formatting of arbitrary pointers is disallowed. If you want to output
+ // a pointer cast it to "void *" or "const void *". In particular, this
+ // forbids formatting of "[const] volatile char *" which is printed as bool
+ // by iostreams.
+ static_assert(!sizeof(T), "formatting of non-void pointers is disallowed");
+ return 0;
+ }
+
+ template <typename T,
+ FMT_ENABLE_IF(std::is_enum<T>::value &&
+ !has_formatter<T, Context>::value &&
+ !has_fallback_formatter<T, Context>::value)>
+ FMT_CONSTEXPR auto map(const T& val)
+ -> decltype(std::declval<arg_mapper>().map(
+ static_cast<typename std::underlying_type<T>::type>(val))) {
+ return map(static_cast<typename std::underlying_type<T>::type>(val));
+ }
+ template <typename T,
+ FMT_ENABLE_IF(!is_string<T>::value && !is_char<T>::value &&
+ (has_formatter<T, Context>::value ||
+ has_fallback_formatter<T, Context>::value))>
+ FMT_CONSTEXPR const T& map(const T& val) {
+ return val;
+ }
+
+ template <typename T>
+ FMT_CONSTEXPR auto map(const named_arg<char_type, T>& val)
+ -> decltype(std::declval<arg_mapper>().map(val.value)) {
+ return map(val.value);
+ }
+
+ unformattable map(...) { return {}; }
+};
+
+// A type constant after applying arg_mapper<Context>.
+template <typename T, typename Context>
+using mapped_type_constant =
+ type_constant<decltype(arg_mapper<Context>().map(std::declval<const T&>())),
+ typename Context::char_type>;
+
+enum { packed_arg_bits = 4 };
+// Maximum number of arguments with packed types.
+enum { max_packed_args = 62 / packed_arg_bits };
+enum : unsigned long long { is_unpacked_bit = 1ULL << 63 };
+enum : unsigned long long { has_named_args_bit = 1ULL << 62 };
+} // namespace detail
+
+// A formatting argument. It is a trivially copyable/constructible type to
+// allow storage in basic_memory_buffer.
+template <typename Context> class basic_format_arg {
+ private:
+ detail::value<Context> value_;
+ detail::type type_;
+
+ template <typename ContextType, typename T>
+ friend FMT_CONSTEXPR basic_format_arg<ContextType> detail::make_arg(
+ const T& value);
+
+ template <typename Visitor, typename Ctx>
+ friend FMT_CONSTEXPR auto visit_format_arg(Visitor&& vis,
+ const basic_format_arg<Ctx>& arg)
+ -> decltype(vis(0));
+
+ friend class basic_format_args<Context>;
+ friend class dynamic_format_arg_store<Context>;
+
+ using char_type = typename Context::char_type;
+
+ template <typename T, typename Char, size_t NUM_ARGS, size_t NUM_NAMED_ARGS>
+ friend struct detail::arg_data;
+
+ basic_format_arg(const detail::named_arg_info<char_type>* args, size_t size)
+ : value_(args, size) {}
+
+ public:
+ class handle {
+ public:
+ explicit handle(detail::custom_value<Context> custom) : custom_(custom) {}
+
+ void format(typename Context::parse_context_type& parse_ctx,
+ Context& ctx) const {
+ custom_.format(custom_.value, parse_ctx, ctx);
+ }
+
+ private:
+ detail::custom_value<Context> custom_;
+ };
+
+ constexpr basic_format_arg() : type_(detail::type::none_type) {}
+
+ constexpr explicit operator bool() const FMT_NOEXCEPT {
+ return type_ != detail::type::none_type;
+ }
+
+ detail::type type() const { return type_; }
+
+ bool is_integral() const { return detail::is_integral_type(type_); }
+ bool is_arithmetic() const { return detail::is_arithmetic_type(type_); }
+};
+
+/**
+ \rst
+ Visits an argument dispatching to the appropriate visit method based on
+ the argument type. For example, if the argument type is ``double`` then
+ ``vis(value)`` will be called with the value of type ``double``.
+ \endrst
+ */
+template <typename Visitor, typename Context>
+FMT_CONSTEXPR_DECL FMT_INLINE auto visit_format_arg(
+ Visitor&& vis, const basic_format_arg<Context>& arg) -> decltype(vis(0)) {
+ using char_type = typename Context::char_type;
+ switch (arg.type_) {
+ case detail::type::none_type:
+ break;
+ case detail::type::int_type:
+ return vis(arg.value_.int_value);
+ case detail::type::uint_type:
+ return vis(arg.value_.uint_value);
+ case detail::type::long_long_type:
+ return vis(arg.value_.long_long_value);
+ case detail::type::ulong_long_type:
+ return vis(arg.value_.ulong_long_value);
+#if FMT_USE_INT128
+ case detail::type::int128_type:
+ return vis(arg.value_.int128_value);
+ case detail::type::uint128_type:
+ return vis(arg.value_.uint128_value);
+#else
+ case detail::type::int128_type:
+ case detail::type::uint128_type:
+ break;
+#endif
+ case detail::type::bool_type:
+ return vis(arg.value_.bool_value);
+ case detail::type::char_type:
+ return vis(arg.value_.char_value);
+ case detail::type::float_type:
+ return vis(arg.value_.float_value);
+ case detail::type::double_type:
+ return vis(arg.value_.double_value);
+ case detail::type::long_double_type:
+ return vis(arg.value_.long_double_value);
+ case detail::type::cstring_type:
+ return vis(arg.value_.string.data);
+ case detail::type::string_type:
+ return vis(basic_string_view<char_type>(arg.value_.string.data,
+ arg.value_.string.size));
+ case detail::type::pointer_type:
+ return vis(arg.value_.pointer);
+ case detail::type::custom_type:
+ return vis(typename basic_format_arg<Context>::handle(arg.value_.custom));
+ }
+ return vis(monostate());
+}
+
+template <typename T> struct formattable : std::false_type {};
+
+namespace detail {
+
+// A workaround for gcc 4.8 to make void_t work in a SFINAE context.
+template <typename... Ts> struct void_t_impl { using type = void; };
+template <typename... Ts>
+using void_t = typename detail::void_t_impl<Ts...>::type;
+
+template <typename It, typename T, typename Enable = void>
+struct is_output_iterator : std::false_type {};
+
+template <typename It, typename T>
+struct is_output_iterator<
+ It, T,
+ void_t<typename std::iterator_traits<It>::iterator_category,
+ decltype(*std::declval<It>() = std::declval<T>())>>
+ : std::true_type {};
+
+template <typename OutputIt>
+struct is_back_insert_iterator : std::false_type {};
+template <typename Container>
+struct is_back_insert_iterator<std::back_insert_iterator<Container>>
+ : std::true_type {};
+
+template <typename OutputIt>
+struct is_contiguous_back_insert_iterator : std::false_type {};
+template <typename Container>
+struct is_contiguous_back_insert_iterator<std::back_insert_iterator<Container>>
+ : is_contiguous<Container> {};
+template <typename Char>
+struct is_contiguous_back_insert_iterator<buffer_appender<Char>>
+ : std::true_type {};
+
+// A type-erased reference to an std::locale to avoid heavy <locale> include.
+class locale_ref {
+ private:
+ const void* locale_; // A type-erased pointer to std::locale.
+
+ public:
+ locale_ref() : locale_(nullptr) {}
+ template <typename Locale> explicit locale_ref(const Locale& loc);
+
+ explicit operator bool() const FMT_NOEXCEPT { return locale_ != nullptr; }
+
+ template <typename Locale> Locale get() const;
+};
+
+template <typename> constexpr unsigned long long encode_types() { return 0; }
+
+template <typename Context, typename Arg, typename... Args>
+constexpr unsigned long long encode_types() {
+ return static_cast<unsigned>(mapped_type_constant<Arg, Context>::value) |
+ (encode_types<Context, Args...>() << packed_arg_bits);
+}
+
+template <typename Context, typename T>
+FMT_CONSTEXPR basic_format_arg<Context> make_arg(const T& value) {
+ basic_format_arg<Context> arg;
+ arg.type_ = mapped_type_constant<T, Context>::value;
+ arg.value_ = arg_mapper<Context>().map(value);
+ return arg;
+}
+
+template <typename T> int check(unformattable) {
+ static_assert(
+ formattable<T>(),
+ "Cannot format an argument. To make type T formattable provide a "
+ "formatter<T> specialization: https://fmt.dev/latest/api.html#udt");
+ return 0;
+}
+template <typename T, typename U> inline const U& check(const U& val) {
+ return val;
+}
+
+// The type template parameter is there to avoid an ODR violation when using
+// a fallback formatter in one translation unit and an implicit conversion in
+// another (not recommended).
+template <bool IS_PACKED, typename Context, type, typename T,
+ FMT_ENABLE_IF(IS_PACKED)>
+inline value<Context> make_arg(const T& val) {
+ return check<T>(arg_mapper<Context>().map(val));
+}
+
+template <bool IS_PACKED, typename Context, type, typename T,
+ FMT_ENABLE_IF(!IS_PACKED)>
+inline basic_format_arg<Context> make_arg(const T& value) {
+ return make_arg<Context>(value);
+}
+
+template <typename T> struct is_reference_wrapper : std::false_type {};
+template <typename T>
+struct is_reference_wrapper<std::reference_wrapper<T>> : std::true_type {};
+
+template <typename T> const T& unwrap(const T& v) { return v; }
+template <typename T> const T& unwrap(const std::reference_wrapper<T>& v) {
+ return static_cast<const T&>(v);
+}
+
+class dynamic_arg_list {
+ // Workaround for clang's -Wweak-vtables. Unlike for regular classes, for
+ // templates it doesn't complain about inability to deduce single translation
+ // unit for placing vtable. So storage_node_base is made a fake template.
+ template <typename = void> struct node {
+ virtual ~node() = default;
+ std::unique_ptr<node<>> next;
+ };
+
+ template <typename T> struct typed_node : node<> {
+ T value;
+
+ template <typename Arg>
+ FMT_CONSTEXPR typed_node(const Arg& arg) : value(arg) {}
+
+ template <typename Char>
+ FMT_CONSTEXPR typed_node(const basic_string_view<Char>& arg)
+ : value(arg.data(), arg.size()) {}
+ };
+
+ std::unique_ptr<node<>> head_;
+
+ public:
+ template <typename T, typename Arg> const T& push(const Arg& arg) {
+ auto new_node = std::unique_ptr<typed_node<T>>(new typed_node<T>(arg));
+ auto& value = new_node->value;
+ new_node->next = std::move(head_);
+ head_ = std::move(new_node);
+ return value;
+ }
+};
+} // namespace detail
+
+// Formatting context.
+template <typename OutputIt, typename Char> class basic_format_context {
+ public:
+ /** The character type for the output. */
+ using char_type = Char;
+
+ private:
+ OutputIt out_;
+ basic_format_args<basic_format_context> args_;
+ detail::locale_ref loc_;
+
+ public:
+ using iterator = OutputIt;
+ using format_arg = basic_format_arg<basic_format_context>;
+ using parse_context_type = basic_format_parse_context<Char>;
+ template <typename T> using formatter_type = formatter<T, char_type>;
+
+ basic_format_context(const basic_format_context&) = delete;
+ void operator=(const basic_format_context&) = delete;
+ /**
+ Constructs a ``basic_format_context`` object. References to the arguments are
+ stored in the object so make sure they have appropriate lifetimes.
+ */
+ basic_format_context(OutputIt out,
+ basic_format_args<basic_format_context> ctx_args,
+ detail::locale_ref loc = detail::locale_ref())
+ : out_(out), args_(ctx_args), loc_(loc) {}
+
+ format_arg arg(int id) const { return args_.get(id); }
+ format_arg arg(basic_string_view<char_type> name) { return args_.get(name); }
+ int arg_id(basic_string_view<char_type> name) { return args_.get_id(name); }
+ const basic_format_args<basic_format_context>& args() const { return args_; }
+
+ detail::error_handler error_handler() { return {}; }
+ void on_error(const char* message) { error_handler().on_error(message); }
+
+ // Returns an iterator to the beginning of the output range.
+ iterator out() { return out_; }
+
+ // Advances the begin iterator to ``it``.
+ void advance_to(iterator it) {
+ if (!detail::is_back_insert_iterator<iterator>()) out_ = it;
+ }
+
+ detail::locale_ref locale() { return loc_; }
+};
+
+template <typename Char>
+using buffer_context =
+ basic_format_context<detail::buffer_appender<Char>, Char>;
+using format_context = buffer_context<char>;
+using wformat_context = buffer_context<wchar_t>;
+
+// Workaround an alias issue: https://stackoverflow.com/q/62767544/471164.
+#define FMT_BUFFER_CONTEXT(Char) \
+ basic_format_context<detail::buffer_appender<Char>, Char>
+
+/**
+ \rst
+ An array of references to arguments. It can be implicitly converted into
+ `~fmt::basic_format_args` for passing into type-erased formatting functions
+ such as `~fmt::vformat`.
+ \endrst
+ */
+template <typename Context, typename... Args>
+class format_arg_store
+#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
+ // Workaround a GCC template argument substitution bug.
+ : public basic_format_args<Context>
+#endif
+{
+ private:
+ static const size_t num_args = sizeof...(Args);
+ static const size_t num_named_args = detail::count_named_args<Args...>();
+ static const bool is_packed = num_args <= detail::max_packed_args;
+
+ using value_type = conditional_t<is_packed, detail::value<Context>,
+ basic_format_arg<Context>>;
+
+ detail::arg_data<value_type, typename Context::char_type, num_args,
+ num_named_args>
+ data_;
+
+ friend class basic_format_args<Context>;
+
+ static constexpr unsigned long long desc =
+ (is_packed ? detail::encode_types<Context, Args...>()
+ : detail::is_unpacked_bit | num_args) |
+ (num_named_args != 0
+ ? static_cast<unsigned long long>(detail::has_named_args_bit)
+ : 0);
+
+ public:
+ format_arg_store(const Args&... args)
+ :
+#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
+ basic_format_args<Context>(*this),
+#endif
+ data_{detail::make_arg<
+ is_packed, Context,
+ detail::mapped_type_constant<Args, Context>::value>(args)...} {
+ detail::init_named_args(data_.named_args(), 0, 0, args...);
+ }
+};
+
+/**
+ \rst
+ Constructs a `~fmt::format_arg_store` object that contains references to
+ arguments and can be implicitly converted to `~fmt::format_args`. `Context`
+ can be omitted in which case it defaults to `~fmt::context`.
+ See `~fmt::arg` for lifetime considerations.
+ \endrst
+ */
+template <typename Context = format_context, typename... Args>
+inline format_arg_store<Context, Args...> make_format_args(
+ const Args&... args) {
+ return {args...};
+}
+
+/**
+ \rst
+ Constructs a `~fmt::format_arg_store` object that contains references
+ to arguments and can be implicitly converted to `~fmt::format_args`.
+ If ``format_str`` is a compile-time string then `make_args_checked` checks
+ its validity at compile time.
+ \endrst
+ */
+template <typename... Args, typename S, typename Char = char_t<S>>
+inline auto make_args_checked(const S& format_str,
+ const remove_reference_t<Args>&... args)
+ -> format_arg_store<buffer_context<Char>, remove_reference_t<Args>...> {
+ static_assert(
+ detail::count<(
+ std::is_base_of<detail::view, remove_reference_t<Args>>::value &&
+ std::is_reference<Args>::value)...>() == 0,
+ "passing views as lvalues is disallowed");
+ detail::check_format_string<Args...>(format_str);
+ return {args...};
+}
+
+/**
+ \rst
+ Returns a named argument to be used in a formatting function. It should only
+ be used in a call to a formatting function.
+
+ **Example**::
+
+ fmt::print("Elapsed time: {s:.2f} seconds", fmt::arg("s", 1.23));
+ \endrst
+ */
+template <typename Char, typename T>
+inline detail::named_arg<Char, T> arg(const Char* name, const T& arg) {
+ static_assert(!detail::is_named_arg<T>(), "nested named arguments");
+ return {name, arg};
+}
+
+/**
+ \rst
+ A dynamic version of `fmt::format_arg_store`.
+ It's equipped with a storage to potentially temporary objects which lifetimes
+ could be shorter than the format arguments object.
+
+ It can be implicitly converted into `~fmt::basic_format_args` for passing
+ into type-erased formatting functions such as `~fmt::vformat`.
+ \endrst
+ */
+template <typename Context>
+class dynamic_format_arg_store
+#if FMT_GCC_VERSION && FMT_GCC_VERSION < 409
+ // Workaround a GCC template argument substitution bug.
+ : public basic_format_args<Context>
+#endif
+{
+ private:
+ using char_type = typename Context::char_type;
+
+ template <typename T> struct need_copy {
+ static constexpr detail::type mapped_type =
+ detail::mapped_type_constant<T, Context>::value;
+
+ enum {
+ value = !(detail::is_reference_wrapper<T>::value ||
+ std::is_same<T, basic_string_view<char_type>>::value ||
+ std::is_same<T, detail::std_string_view<char_type>>::value ||
+ (mapped_type != detail::type::cstring_type &&
+ mapped_type != detail::type::string_type &&
+ mapped_type != detail::type::custom_type))
+ };
+ };
+
+ template <typename T>
+ using stored_type = conditional_t<detail::is_string<T>::value,
+ std::basic_string<char_type>, T>;
+
+ // Storage of basic_format_arg must be contiguous.
+ std::vector<basic_format_arg<Context>> data_;
+ std::vector<detail::named_arg_info<char_type>> named_info_;
+
+ // Storage of arguments not fitting into basic_format_arg must grow
+ // without relocation because items in data_ refer to it.
+ detail::dynamic_arg_list dynamic_args_;
+
+ friend class basic_format_args<Context>;
+
+ unsigned long long get_types() const {
+ return detail::is_unpacked_bit | data_.size() |
+ (named_info_.empty()
+ ? 0ULL
+ : static_cast<unsigned long long>(detail::has_named_args_bit));
+ }
+
+ const basic_format_arg<Context>* data() const {
+ return named_info_.empty() ? data_.data() : data_.data() + 1;
+ }
+
+ template <typename T> void emplace_arg(const T& arg) {
+ data_.emplace_back(detail::make_arg<Context>(arg));
+ }
+
+ template <typename T>
+ void emplace_arg(const detail::named_arg<char_type, T>& arg) {
+ if (named_info_.empty()) {
+ constexpr const detail::named_arg_info<char_type>* zero_ptr{nullptr};
+ data_.insert(data_.begin(), {zero_ptr, 0});
+ }
+ data_.emplace_back(detail::make_arg<Context>(detail::unwrap(arg.value)));
+ auto pop_one = [](std::vector<basic_format_arg<Context>>* data) {
+ data->pop_back();
+ };
+ std::unique_ptr<std::vector<basic_format_arg<Context>>, decltype(pop_one)>
+ guard{&data_, pop_one};
+ named_info_.push_back({arg.name, static_cast<int>(data_.size() - 2u)});
+ data_[0].value_.named_args = {named_info_.data(), named_info_.size()};
+ guard.release();
+ }
+
+ public:
+ /**
+ \rst
+ Adds an argument into the dynamic store for later passing to a formatting
+ function.
+
+ Note that custom types and string types (but not string views) are copied
+ into the store dynamically allocating memory if necessary.
+
+ **Example**::
+
+ fmt::dynamic_format_arg_store<fmt::format_context> store;
+ store.push_back(42);
+ store.push_back("abc");
+ store.push_back(1.5f);
+ std::string result = fmt::vformat("{} and {} and {}", store);
+ \endrst
+ */
+ template <typename T> void push_back(const T& arg) {
+ if (detail::const_check(need_copy<T>::value))
+ emplace_arg(dynamic_args_.push<stored_type<T>>(arg));
+ else
+ emplace_arg(detail::unwrap(arg));
+ }
+
+ /**
+ \rst
+ Adds a reference to the argument into the dynamic store for later passing to
+ a formatting function. Supports named arguments wrapped in
+ ``std::reference_wrapper`` via ``std::ref()``/``std::cref()``.
+
+ **Example**::
+
+ fmt::dynamic_format_arg_store<fmt::format_context> store;
+ char str[] = "1234567890";
+ store.push_back(std::cref(str));
+ int a1_val{42};
+ auto a1 = fmt::arg("a1_", a1_val);
+ store.push_back(std::cref(a1));
+
+ // Changing str affects the output but only for string and custom types.
+ str[0] = 'X';
+
+ std::string result = fmt::vformat("{} and {a1_}");
+ assert(result == "X234567890 and 42");
+ \endrst
+ */
+ template <typename T> void push_back(std::reference_wrapper<T> arg) {
+ static_assert(
+ detail::is_named_arg<typename std::remove_cv<T>::type>::value ||
+ need_copy<T>::value,
+ "objects of built-in types and string views are always copied");
+ emplace_arg(arg.get());
+ }
+
+ /**
+ Adds named argument into the dynamic store for later passing to a formatting
+ function. ``std::reference_wrapper`` is supported to avoid copying of the
+ argument.
+ */
+ template <typename T>
+ void push_back(const detail::named_arg<char_type, T>& arg) {
+ const char_type* arg_name =
+ dynamic_args_.push<std::basic_string<char_type>>(arg.name).c_str();
+ if (detail::const_check(need_copy<T>::value)) {
+ emplace_arg(
+ fmt::arg(arg_name, dynamic_args_.push<stored_type<T>>(arg.value)));
+ } else {
+ emplace_arg(fmt::arg(arg_name, arg.value));
+ }
+ }
+
+ /** Erase all elements from the store */
+ void clear() {
+ data_.clear();
+ named_info_.clear();
+ dynamic_args_ = detail::dynamic_arg_list();
+ }
+
+ /**
+ \rst
+ Reserves space to store at least *new_cap* arguments including
+ *new_cap_named* named arguments.
+ \endrst
+ */
+ void reserve(size_t new_cap, size_t new_cap_named) {
+ FMT_ASSERT(new_cap >= new_cap_named,
+ "Set of arguments includes set of named arguments");
+ data_.reserve(new_cap);
+ named_info_.reserve(new_cap_named);
+ }
+};
+
+/**
+ \rst
+ A view of a collection of formatting arguments. To avoid lifetime issues it
+ should only be used as a parameter type in type-erased functions such as
+ ``vformat``::
+
+ void vlog(string_view format_str, format_args args); // OK
+ format_args args = make_format_args(42); // Error: dangling reference
+ \endrst
+ */
+template <typename Context> class basic_format_args {
+ public:
+ using size_type = int;
+ using format_arg = basic_format_arg<Context>;
+
+ private:
+ // A descriptor that contains information about formatting arguments.
+ // If the number of arguments is less or equal to max_packed_args then
+ // argument types are passed in the descriptor. This reduces binary code size
+ // per formatting function call.
+ unsigned long long desc_;
+ union {
+ // If is_packed() returns true then argument values are stored in values_;
+ // otherwise they are stored in args_. This is done to improve cache
+ // locality and reduce compiled code size since storing larger objects
+ // may require more code (at least on x86-64) even if the same amount of
+ // data is actually copied to stack. It saves ~10% on the bloat test.
+ const detail::value<Context>* values_;
+ const format_arg* args_;
+ };
+
+ bool is_packed() const { return (desc_ & detail::is_unpacked_bit) == 0; }
+ bool has_named_args() const {
+ return (desc_ & detail::has_named_args_bit) != 0;
+ }
+
+ detail::type type(int index) const {
+ int shift = index * detail::packed_arg_bits;
+ unsigned int mask = (1 << detail::packed_arg_bits) - 1;
+ return static_cast<detail::type>((desc_ >> shift) & mask);
+ }
+
+ basic_format_args(unsigned long long desc,
+ const detail::value<Context>* values)
+ : desc_(desc), values_(values) {}
+ basic_format_args(unsigned long long desc, const format_arg* args)
+ : desc_(desc), args_(args) {}
+
+ public:
+ basic_format_args() : desc_(0) {}
+
+ /**
+ \rst
+ Constructs a `basic_format_args` object from `~fmt::format_arg_store`.
+ \endrst
+ */
+ template <typename... Args>
+ FMT_INLINE basic_format_args(const format_arg_store<Context, Args...>& store)
+ : basic_format_args(store.desc, store.data_.args()) {}
+
+ /**
+ \rst
+ Constructs a `basic_format_args` object from
+ `~fmt::dynamic_format_arg_store`.
+ \endrst
+ */
+ FMT_INLINE basic_format_args(const dynamic_format_arg_store<Context>& store)
+ : basic_format_args(store.get_types(), store.data()) {}
+
+ /**
+ \rst
+ Constructs a `basic_format_args` object from a dynamic set of arguments.
+ \endrst
+ */
+ basic_format_args(const format_arg* args, int count)
+ : basic_format_args(detail::is_unpacked_bit | detail::to_unsigned(count),
+ args) {}
+
+ /** Returns the argument with the specified id. */
+ format_arg get(int id) const {
+ format_arg arg;
+ if (!is_packed()) {
+ if (id < max_size()) arg = args_[id];
+ return arg;
+ }
+ if (id >= detail::max_packed_args) return arg;
+ arg.type_ = type(id);
+ if (arg.type_ == detail::type::none_type) return arg;
+ arg.value_ = values_[id];
+ return arg;
+ }
+
+ template <typename Char> format_arg get(basic_string_view<Char> name) const {
+ int id = get_id(name);
+ return id >= 0 ? get(id) : format_arg();
+ }
+
+ template <typename Char> int get_id(basic_string_view<Char> name) const {
+ if (!has_named_args()) return -1;
+ const auto& named_args =
+ (is_packed() ? values_[-1] : args_[-1].value_).named_args;
+ for (size_t i = 0; i < named_args.size; ++i) {
+ if (named_args.data[i].name == name) return named_args.data[i].id;
+ }
+ return -1;
+ }
+
+ int max_size() const {
+ unsigned long long max_packed = detail::max_packed_args;
+ return static_cast<int>(is_packed() ? max_packed
+ : desc_ & ~detail::is_unpacked_bit);
+ }
+};
+
+#ifdef FMT_ARM_ABI_COMPATIBILITY
+/** An alias to ``basic_format_args<format_context>``. */
+// Separate types would result in shorter symbols but break ABI compatibility
+// between clang and gcc on ARM (#1919).
+using format_args = basic_format_args<format_context>;
+using wformat_args = basic_format_args<wformat_context>;
+#else
+// DEPRECATED! These are kept for ABI compatibility.
+// It is a separate type rather than an alias to make symbols readable.
+struct format_args : basic_format_args<format_context> {
+ template <typename... Args>
+ FMT_INLINE format_args(const Args&... args) : basic_format_args(args...) {}
+};
+struct wformat_args : basic_format_args<wformat_context> {
+ using basic_format_args::basic_format_args;
+};
+#endif
+
+namespace detail {
+
+template <typename Char, FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+std::basic_string<Char> vformat(
+ basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args);
+
+FMT_API std::string vformat(string_view format_str, format_args args);
+
+template <typename Char>
+void vformat_to(
+ buffer<Char>& buf, basic_string_view<Char> format_str,
+ basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args,
+ detail::locale_ref loc = {});
+
+template <typename Char, typename Args,
+ FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+inline void vprint_mojibake(std::FILE*, basic_string_view<Char>, const Args&) {}
+
+FMT_API void vprint_mojibake(std::FILE*, string_view, format_args);
+#ifndef _WIN32
+inline void vprint_mojibake(std::FILE*, string_view, format_args) {}
+#endif
+} // namespace detail
+
+/** Formats a string and writes the output to ``out``. */
+// GCC 8 and earlier cannot handle std::back_insert_iterator<Container> with
+// vformat_to<ArgFormatter>(...) overload, so SFINAE on iterator type instead.
+template <typename OutputIt, typename S, typename Char = char_t<S>,
+ bool enable = detail::is_output_iterator<OutputIt, Char>::value>
+auto vformat_to(OutputIt out, const S& format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args)
+ -> typename std::enable_if<enable, OutputIt>::type {
+ decltype(detail::get_buffer<Char>(out)) buf(detail::get_buffer_init(out));
+ detail::vformat_to(buf, to_string_view(format_str), args);
+ return detail::get_iterator(buf);
+}
+
+/**
+ \rst
+ Formats arguments, writes the result to the output iterator ``out`` and returns
+ the iterator past the end of the output range.
+
+ **Example**::
+
+ std::vector<char> out;
+ fmt::format_to(std::back_inserter(out), "{}", 42);
+ \endrst
+ */
+// We cannot use FMT_ENABLE_IF because of a bug in gcc 8.3.
+template <typename OutputIt, typename S, typename... Args,
+ bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value>
+inline auto format_to(OutputIt out, const S& format_str, Args&&... args) ->
+ typename std::enable_if<enable, OutputIt>::type {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ return vformat_to(out, to_string_view(format_str), vargs);
+}
+
+template <typename OutputIt> struct format_to_n_result {
+ /** Iterator past the end of the output range. */
+ OutputIt out;
+ /** Total (not truncated) output size. */
+ size_t size;
+};
+
+template <typename OutputIt, typename Char, typename... Args,
+ FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)>
+inline format_to_n_result<OutputIt> vformat_to_n(
+ OutputIt out, size_t n, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ detail::iterator_buffer<OutputIt, Char, detail::fixed_buffer_traits> buf(out,
+ n);
+ detail::vformat_to(buf, format_str, args);
+ return {buf.out(), buf.count()};
+}
+
+/**
+ \rst
+ Formats arguments, writes up to ``n`` characters of the result to the output
+ iterator ``out`` and returns the total output size and the iterator past the
+ end of the output range.
+ \endrst
+ */
+template <typename OutputIt, typename S, typename... Args,
+ bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value>
+inline auto format_to_n(OutputIt out, size_t n, const S& format_str,
+ const Args&... args) ->
+ typename std::enable_if<enable, format_to_n_result<OutputIt>>::type {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ return vformat_to_n(out, n, to_string_view(format_str), vargs);
+}
+
+/**
+ Returns the number of characters in the output of
+ ``format(format_str, args...)``.
+ */
+template <typename... Args>
+inline size_t formatted_size(string_view format_str, Args&&... args) {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ detail::counting_buffer<> buf;
+ detail::vformat_to(buf, format_str, vargs);
+ return buf.count();
+}
+
+template <typename S, typename Char = char_t<S>>
+FMT_INLINE std::basic_string<Char> vformat(
+ const S& format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ return detail::vformat(to_string_view(format_str), args);
+}
+
+/**
+ \rst
+ Formats arguments and returns the result as a string.
+
+ **Example**::
+
+ #include <fmt/core.h>
+ std::string message = fmt::format("The answer is {}", 42);
+ \endrst
+*/
+// Pass char_t as a default template parameter instead of using
+// std::basic_string<char_t<S>> to reduce the symbol size.
+template <typename S, typename... Args, typename Char = char_t<S>>
+FMT_INLINE std::basic_string<Char> format(const S& format_str, Args&&... args) {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ return detail::vformat(to_string_view(format_str), vargs);
+}
+
+FMT_API void vprint(string_view, format_args);
+FMT_API void vprint(std::FILE*, string_view, format_args);
+
+/**
+ \rst
+ Formats ``args`` according to specifications in ``format_str`` and writes the
+ output to the file ``f``. Strings are assumed to be Unicode-encoded unless the
+ ``FMT_UNICODE`` macro is set to 0.
+
+ **Example**::
+
+ fmt::print(stderr, "Don't {}!", "panic");
+ \endrst
+ */
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline void print(std::FILE* f, const S& format_str, Args&&... args) {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ return detail::is_unicode<Char>()
+ ? vprint(f, to_string_view(format_str), vargs)
+ : detail::vprint_mojibake(f, to_string_view(format_str), vargs);
+}
+
+/**
+ \rst
+ Formats ``args`` according to specifications in ``format_str`` and writes
+ the output to ``stdout``. Strings are assumed to be Unicode-encoded unless
+ the ``FMT_UNICODE`` macro is set to 0.
+
+ **Example**::
+
+ fmt::print("Elapsed time: {0:.2f} seconds", 1.23);
+ \endrst
+ */
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline void print(const S& format_str, Args&&... args) {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ return detail::is_unicode<Char>()
+ ? vprint(to_string_view(format_str), vargs)
+ : detail::vprint_mojibake(stdout, to_string_view(format_str),
+ vargs);
+}
+FMT_END_NAMESPACE
+
+#endif // FMT_CORE_H_
diff --git a/include/spdlog/fmt/bundled/format-inl.h b/include/spdlog/fmt/bundled/format-inl.h
new file mode 100644
index 00000000..8f2fe735
--- /dev/null
+++ b/include/spdlog/fmt/bundled/format-inl.h
@@ -0,0 +1,2801 @@
+// Formatting library for C++ - implementation
+//
+// Copyright (c) 2012 - 2016, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_FORMAT_INL_H_
+#define FMT_FORMAT_INL_H_
+
+#include <cassert>
+#include <cctype>
+#include <climits>
+#include <cmath>
+#include <cstdarg>
+#include <cstring> // std::memmove
+#include <cwchar>
+#include <exception>
+
+#ifndef FMT_STATIC_THOUSANDS_SEPARATOR
+# include <locale>
+#endif
+
+#ifdef _WIN32
+# include <io.h> // _isatty
+#endif
+
+#include "format.h"
+
+// Dummy implementations of strerror_r and strerror_s called if corresponding
+// system functions are not available.
+inline fmt::detail::null<> strerror_r(int, char*, ...) { return {}; }
+inline fmt::detail::null<> strerror_s(char*, size_t, ...) { return {}; }
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+FMT_FUNC void assert_fail(const char* file, int line, const char* message) {
+ // Use unchecked std::fprintf to avoid triggering another assertion when
+ // writing to stderr fails
+ std::fprintf(stderr, "%s:%d: assertion failed: %s", file, line, message);
+ // Chosen instead of std::abort to satisfy Clang in CUDA mode during device
+ // code pass.
+ std::terminate();
+}
+
+#ifndef _MSC_VER
+# define FMT_SNPRINTF snprintf
+#else // _MSC_VER
+inline int fmt_snprintf(char* buffer, size_t size, const char* format, ...) {
+ va_list args;
+ va_start(args, format);
+ int result = vsnprintf_s(buffer, size, _TRUNCATE, format, args);
+ va_end(args);
+ return result;
+}
+# define FMT_SNPRINTF fmt_snprintf
+#endif // _MSC_VER
+
+// A portable thread-safe version of strerror.
+// Sets buffer to point to a string describing the error code.
+// This can be either a pointer to a string stored in buffer,
+// or a pointer to some static immutable string.
+// Returns one of the following values:
+// 0 - success
+// ERANGE - buffer is not large enough to store the error message
+// other - failure
+// Buffer should be at least of size 1.
+inline int safe_strerror(int error_code, char*& buffer,
+ size_t buffer_size) FMT_NOEXCEPT {
+ FMT_ASSERT(buffer != nullptr && buffer_size != 0, "invalid buffer");
+
+ class dispatcher {
+ private:
+ int error_code_;
+ char*& buffer_;
+ size_t buffer_size_;
+
+ // A noop assignment operator to avoid bogus warnings.
+ void operator=(const dispatcher&) {}
+
+ // Handle the result of XSI-compliant version of strerror_r.
+ int handle(int result) {
+ // glibc versions before 2.13 return result in errno.
+ return result == -1 ? errno : result;
+ }
+
+ // Handle the result of GNU-specific version of strerror_r.
+ FMT_MAYBE_UNUSED
+ int handle(char* message) {
+ // If the buffer is full then the message is probably truncated.
+ if (message == buffer_ && strlen(buffer_) == buffer_size_ - 1)
+ return ERANGE;
+ buffer_ = message;
+ return 0;
+ }
+
+ // Handle the case when strerror_r is not available.
+ FMT_MAYBE_UNUSED
+ int handle(detail::null<>) {
+ return fallback(strerror_s(buffer_, buffer_size_, error_code_));
+ }
+
+ // Fallback to strerror_s when strerror_r is not available.
+ FMT_MAYBE_UNUSED
+ int fallback(int result) {
+ // If the buffer is full then the message is probably truncated.
+ return result == 0 && strlen(buffer_) == buffer_size_ - 1 ? ERANGE
+ : result;
+ }
+
+#if !FMT_MSC_VER
+ // Fallback to strerror if strerror_r and strerror_s are not available.
+ int fallback(detail::null<>) {
+ errno = 0;
+ buffer_ = strerror(error_code_);
+ return errno;
+ }
+#endif
+
+ public:
+ dispatcher(int err_code, char*& buf, size_t buf_size)
+ : error_code_(err_code), buffer_(buf), buffer_size_(buf_size) {}
+
+ int run() { return handle(strerror_r(error_code_, buffer_, buffer_size_)); }
+ };
+ return dispatcher(error_code, buffer, buffer_size).run();
+}
+
+FMT_FUNC void format_error_code(detail::buffer<char>& out, int error_code,
+ string_view message) FMT_NOEXCEPT {
+ // Report error code making sure that the output fits into
+ // inline_buffer_size to avoid dynamic memory allocation and potential
+ // bad_alloc.
+ out.try_resize(0);
+ static const char SEP[] = ": ";
+ static const char ERROR_STR[] = "error ";
+ // Subtract 2 to account for terminating null characters in SEP and ERROR_STR.
+ size_t error_code_size = sizeof(SEP) + sizeof(ERROR_STR) - 2;
+ auto abs_value = static_cast<uint32_or_64_or_128_t<int>>(error_code);
+ if (detail::is_negative(error_code)) {
+ abs_value = 0 - abs_value;
+ ++error_code_size;
+ }
+ error_code_size += detail::to_unsigned(detail::count_digits(abs_value));
+ auto it = buffer_appender<char>(out);
+ if (message.size() <= inline_buffer_size - error_code_size)
+ format_to(it, "{}{}", message, SEP);
+ format_to(it, "{}{}", ERROR_STR, error_code);
+ assert(out.size() <= inline_buffer_size);
+}
+
+FMT_FUNC void report_error(format_func func, int error_code,
+ string_view message) FMT_NOEXCEPT {
+ memory_buffer full_message;
+ func(full_message, error_code, message);
+ // Don't use fwrite_fully because the latter may throw.
+ (void)std::fwrite(full_message.data(), full_message.size(), 1, stderr);
+ std::fputc('\n', stderr);
+}
+
+// A wrapper around fwrite that throws on error.
+inline void fwrite_fully(const void* ptr, size_t size, size_t count,
+ FILE* stream) {
+ size_t written = std::fwrite(ptr, size, count, stream);
+ if (written < count) FMT_THROW(system_error(errno, "cannot write to file"));
+}
+} // namespace detail
+
+#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
+namespace detail {
+
+template <typename Locale>
+locale_ref::locale_ref(const Locale& loc) : locale_(&loc) {
+ static_assert(std::is_same<Locale, std::locale>::value, "");
+}
+
+template <typename Locale> Locale locale_ref::get() const {
+ static_assert(std::is_same<Locale, std::locale>::value, "");
+ return locale_ ? *static_cast<const std::locale*>(locale_) : std::locale();
+}
+
+template <typename Char> FMT_FUNC std::string grouping_impl(locale_ref loc) {
+ return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>()).grouping();
+}
+template <typename Char> FMT_FUNC Char thousands_sep_impl(locale_ref loc) {
+ return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>())
+ .thousands_sep();
+}
+template <typename Char> FMT_FUNC Char decimal_point_impl(locale_ref loc) {
+ return std::use_facet<std::numpunct<Char>>(loc.get<std::locale>())
+ .decimal_point();
+}
+} // namespace detail
+#else
+template <typename Char>
+FMT_FUNC std::string detail::grouping_impl(locale_ref) {
+ return "\03";
+}
+template <typename Char> FMT_FUNC Char detail::thousands_sep_impl(locale_ref) {
+ return FMT_STATIC_THOUSANDS_SEPARATOR;
+}
+template <typename Char> FMT_FUNC Char detail::decimal_point_impl(locale_ref) {
+ return '.';
+}
+#endif
+
+FMT_API FMT_FUNC format_error::~format_error() FMT_NOEXCEPT = default;
+FMT_API FMT_FUNC system_error::~system_error() FMT_NOEXCEPT = default;
+
+FMT_FUNC void system_error::init(int err_code, string_view format_str,
+ format_args args) {
+ error_code_ = err_code;
+ memory_buffer buffer;
+ format_system_error(buffer, err_code, vformat(format_str, args));
+ std::runtime_error& base = *this;
+ base = std::runtime_error(to_string(buffer));
+}
+
+namespace detail {
+
+template <> FMT_FUNC int count_digits<4>(detail::fallback_uintptr n) {
+ // fallback_uintptr is always stored in little endian.
+ int i = static_cast<int>(sizeof(void*)) - 1;
+ while (i > 0 && n.value[i] == 0) --i;
+ auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
+ return i >= 0 ? i * char_digits + count_digits<4, unsigned>(n.value[i]) : 1;
+}
+
+template <typename T>
+const typename basic_data<T>::digit_pair basic_data<T>::digits[] = {
+ {'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'}, {'0', '5'},
+ {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'}, {'1', '0'}, {'1', '1'},
+ {'1', '2'}, {'1', '3'}, {'1', '4'}, {'1', '5'}, {'1', '6'}, {'1', '7'},
+ {'1', '8'}, {'1', '9'}, {'2', '0'}, {'2', '1'}, {'2', '2'}, {'2', '3'},
+ {'2', '4'}, {'2', '5'}, {'2', '6'}, {'2', '7'}, {'2', '8'}, {'2', '9'},
+ {'3', '0'}, {'3', '1'}, {'3', '2'}, {'3', '3'}, {'3', '4'}, {'3', '5'},
+ {'3', '6'}, {'3', '7'}, {'3', '8'}, {'3', '9'}, {'4', '0'}, {'4', '1'},
+ {'4', '2'}, {'4', '3'}, {'4', '4'}, {'4', '5'}, {'4', '6'}, {'4', '7'},
+ {'4', '8'}, {'4', '9'}, {'5', '0'}, {'5', '1'}, {'5', '2'}, {'5', '3'},
+ {'5', '4'}, {'5', '5'}, {'5', '6'}, {'5', '7'}, {'5', '8'}, {'5', '9'},
+ {'6', '0'}, {'6', '1'}, {'6', '2'}, {'6', '3'}, {'6', '4'}, {'6', '5'},
+ {'6', '6'}, {'6', '7'}, {'6', '8'}, {'6', '9'}, {'7', '0'}, {'7', '1'},
+ {'7', '2'}, {'7', '3'}, {'7', '4'}, {'7', '5'}, {'7', '6'}, {'7', '7'},
+ {'7', '8'}, {'7', '9'}, {'8', '0'}, {'8', '1'}, {'8', '2'}, {'8', '3'},
+ {'8', '4'}, {'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'},
+ {'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'}, {'9', '5'},
+ {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'}};
+
+template <typename T>
+const char basic_data<T>::hex_digits[] = "0123456789abcdef";
+
+#define FMT_POWERS_OF_10(factor) \
+ factor * 10, (factor)*100, (factor)*1000, (factor)*10000, (factor)*100000, \
+ (factor)*1000000, (factor)*10000000, (factor)*100000000, \
+ (factor)*1000000000
+
+template <typename T>
+const uint64_t basic_data<T>::powers_of_10_64[] = {
+ 1, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL),
+ 10000000000000000000ULL};
+
+template <typename T>
+const uint32_t basic_data<T>::zero_or_powers_of_10_32[] = {0,
+ FMT_POWERS_OF_10(1)};
+template <typename T>
+const uint64_t basic_data<T>::zero_or_powers_of_10_64[] = {
+ 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL),
+ 10000000000000000000ULL};
+
+template <typename T>
+const uint32_t basic_data<T>::zero_or_powers_of_10_32_new[] = {
+ 0, 0, FMT_POWERS_OF_10(1)};
+
+template <typename T>
+const uint64_t basic_data<T>::zero_or_powers_of_10_64_new[] = {
+ 0, 0, FMT_POWERS_OF_10(1), FMT_POWERS_OF_10(1000000000ULL),
+ 10000000000000000000ULL};
+
+// Normalized 64-bit significands of pow(10, k), for k = -348, -340, ..., 340.
+// These are generated by support/compute-powers.py.
+template <typename T>
+const uint64_t basic_data<T>::grisu_pow10_significands[] = {
+ 0xfa8fd5a0081c0288, 0xbaaee17fa23ebf76, 0x8b16fb203055ac76,
+ 0xcf42894a5dce35ea, 0x9a6bb0aa55653b2d, 0xe61acf033d1a45df,
+ 0xab70fe17c79ac6ca, 0xff77b1fcbebcdc4f, 0xbe5691ef416bd60c,
+ 0x8dd01fad907ffc3c, 0xd3515c2831559a83, 0x9d71ac8fada6c9b5,
+ 0xea9c227723ee8bcb, 0xaecc49914078536d, 0x823c12795db6ce57,
+ 0xc21094364dfb5637, 0x9096ea6f3848984f, 0xd77485cb25823ac7,
+ 0xa086cfcd97bf97f4, 0xef340a98172aace5, 0xb23867fb2a35b28e,
+ 0x84c8d4dfd2c63f3b, 0xc5dd44271ad3cdba, 0x936b9fcebb25c996,
+ 0xdbac6c247d62a584, 0xa3ab66580d5fdaf6, 0xf3e2f893dec3f126,
+ 0xb5b5ada8aaff80b8, 0x87625f056c7c4a8b, 0xc9bcff6034c13053,
+ 0x964e858c91ba2655, 0xdff9772470297ebd, 0xa6dfbd9fb8e5b88f,
+ 0xf8a95fcf88747d94, 0xb94470938fa89bcf, 0x8a08f0f8bf0f156b,
+ 0xcdb02555653131b6, 0x993fe2c6d07b7fac, 0xe45c10c42a2b3b06,
+ 0xaa242499697392d3, 0xfd87b5f28300ca0e, 0xbce5086492111aeb,
+ 0x8cbccc096f5088cc, 0xd1b71758e219652c, 0x9c40000000000000,
+ 0xe8d4a51000000000, 0xad78ebc5ac620000, 0x813f3978f8940984,
+ 0xc097ce7bc90715b3, 0x8f7e32ce7bea5c70, 0xd5d238a4abe98068,
+ 0x9f4f2726179a2245, 0xed63a231d4c4fb27, 0xb0de65388cc8ada8,
+ 0x83c7088e1aab65db, 0xc45d1df942711d9a, 0x924d692ca61be758,
+ 0xda01ee641a708dea, 0xa26da3999aef774a, 0xf209787bb47d6b85,
+ 0xb454e4a179dd1877, 0x865b86925b9bc5c2, 0xc83553c5c8965d3d,
+ 0x952ab45cfa97a0b3, 0xde469fbd99a05fe3, 0xa59bc234db398c25,
+ 0xf6c69a72a3989f5c, 0xb7dcbf5354e9bece, 0x88fcf317f22241e2,
+ 0xcc20ce9bd35c78a5, 0x98165af37b2153df, 0xe2a0b5dc971f303a,
+ 0xa8d9d1535ce3b396, 0xfb9b7cd9a4a7443c, 0xbb764c4ca7a44410,
+ 0x8bab8eefb6409c1a, 0xd01fef10a657842c, 0x9b10a4e5e9913129,
+ 0xe7109bfba19c0c9d, 0xac2820d9623bf429, 0x80444b5e7aa7cf85,
+ 0xbf21e44003acdd2d, 0x8e679c2f5e44ff8f, 0xd433179d9c8cb841,
+ 0x9e19db92b4e31ba9, 0xeb96bf6ebadf77d9, 0xaf87023b9bf0ee6b,
+};
+
+// Binary exponents of pow(10, k), for k = -348, -340, ..., 340, corresponding
+// to significands above.
+template <typename T>
+const int16_t basic_data<T>::grisu_pow10_exponents[] = {
+ -1220, -1193, -1166, -1140, -1113, -1087, -1060, -1034, -1007, -980, -954,
+ -927, -901, -874, -847, -821, -794, -768, -741, -715, -688, -661,
+ -635, -608, -582, -555, -529, -502, -475, -449, -422, -396, -369,
+ -343, -316, -289, -263, -236, -210, -183, -157, -130, -103, -77,
+ -50, -24, 3, 30, 56, 83, 109, 136, 162, 189, 216,
+ 242, 269, 295, 322, 348, 375, 402, 428, 455, 481, 508,
+ 534, 561, 588, 614, 641, 667, 694, 720, 747, 774, 800,
+ 827, 853, 880, 907, 933, 960, 986, 1013, 1039, 1066};
+
+template <typename T>
+const divtest_table_entry<uint32_t> basic_data<T>::divtest_table_for_pow5_32[] =
+ {{0x00000001, 0xffffffff}, {0xcccccccd, 0x33333333},
+ {0xc28f5c29, 0x0a3d70a3}, {0x26e978d5, 0x020c49ba},
+ {0x3afb7e91, 0x0068db8b}, {0x0bcbe61d, 0x0014f8b5},
+ {0x68c26139, 0x000431bd}, {0xae8d46a5, 0x0000d6bf},
+ {0x22e90e21, 0x00002af3}, {0x3a2e9c6d, 0x00000897},
+ {0x3ed61f49, 0x000001b7}};
+
+template <typename T>
+const divtest_table_entry<uint64_t> basic_data<T>::divtest_table_for_pow5_64[] =
+ {{0x0000000000000001, 0xffffffffffffffff},
+ {0xcccccccccccccccd, 0x3333333333333333},
+ {0x8f5c28f5c28f5c29, 0x0a3d70a3d70a3d70},
+ {0x1cac083126e978d5, 0x020c49ba5e353f7c},
+ {0xd288ce703afb7e91, 0x0068db8bac710cb2},
+ {0x5d4e8fb00bcbe61d, 0x0014f8b588e368f0},
+ {0x790fb65668c26139, 0x000431bde82d7b63},
+ {0xe5032477ae8d46a5, 0x0000d6bf94d5e57a},
+ {0xc767074b22e90e21, 0x00002af31dc46118},
+ {0x8e47ce423a2e9c6d, 0x0000089705f4136b},
+ {0x4fa7f60d3ed61f49, 0x000001b7cdfd9d7b},
+ {0x0fee64690c913975, 0x00000057f5ff85e5},
+ {0x3662e0e1cf503eb1, 0x000000119799812d},
+ {0xa47a2cf9f6433fbd, 0x0000000384b84d09},
+ {0x54186f653140a659, 0x00000000b424dc35},
+ {0x7738164770402145, 0x0000000024075f3d},
+ {0xe4a4d1417cd9a041, 0x000000000734aca5},
+ {0xc75429d9e5c5200d, 0x000000000170ef54},
+ {0xc1773b91fac10669, 0x000000000049c977},
+ {0x26b172506559ce15, 0x00000000000ec1e4},
+ {0xd489e3a9addec2d1, 0x000000000002f394},
+ {0x90e860bb892c8d5d, 0x000000000000971d},
+ {0x502e79bf1b6f4f79, 0x0000000000001e39},
+ {0xdcd618596be30fe5, 0x000000000000060b}};
+
+template <typename T>
+const uint64_t basic_data<T>::dragonbox_pow10_significands_64[] = {
+ 0x81ceb32c4b43fcf5, 0xa2425ff75e14fc32, 0xcad2f7f5359a3b3f,
+ 0xfd87b5f28300ca0e, 0x9e74d1b791e07e49, 0xc612062576589ddb,
+ 0xf79687aed3eec552, 0x9abe14cd44753b53, 0xc16d9a0095928a28,
+ 0xf1c90080baf72cb2, 0x971da05074da7bef, 0xbce5086492111aeb,
+ 0xec1e4a7db69561a6, 0x9392ee8e921d5d08, 0xb877aa3236a4b44a,
+ 0xe69594bec44de15c, 0x901d7cf73ab0acda, 0xb424dc35095cd810,
+ 0xe12e13424bb40e14, 0x8cbccc096f5088cc, 0xafebff0bcb24aaff,
+ 0xdbe6fecebdedd5bf, 0x89705f4136b4a598, 0xabcc77118461cefd,
+ 0xd6bf94d5e57a42bd, 0x8637bd05af6c69b6, 0xa7c5ac471b478424,
+ 0xd1b71758e219652c, 0x83126e978d4fdf3c, 0xa3d70a3d70a3d70b,
+ 0xcccccccccccccccd, 0x8000000000000000, 0xa000000000000000,
+ 0xc800000000000000, 0xfa00000000000000, 0x9c40000000000000,
+ 0xc350000000000000, 0xf424000000000000, 0x9896800000000000,
+ 0xbebc200000000000, 0xee6b280000000000, 0x9502f90000000000,
+ 0xba43b74000000000, 0xe8d4a51000000000, 0x9184e72a00000000,
+ 0xb5e620f480000000, 0xe35fa931a0000000, 0x8e1bc9bf04000000,
+ 0xb1a2bc2ec5000000, 0xde0b6b3a76400000, 0x8ac7230489e80000,
+ 0xad78ebc5ac620000, 0xd8d726b7177a8000, 0x878678326eac9000,
+ 0xa968163f0a57b400, 0xd3c21bcecceda100, 0x84595161401484a0,
+ 0xa56fa5b99019a5c8, 0xcecb8f27f4200f3a, 0x813f3978f8940984,
+ 0xa18f07d736b90be5, 0xc9f2c9cd04674ede, 0xfc6f7c4045812296,
+ 0x9dc5ada82b70b59d, 0xc5371912364ce305, 0xf684df56c3e01bc6,
+ 0x9a130b963a6c115c, 0xc097ce7bc90715b3, 0xf0bdc21abb48db20,
+ 0x96769950b50d88f4, 0xbc143fa4e250eb31, 0xeb194f8e1ae525fd,
+ 0x92efd1b8d0cf37be, 0xb7abc627050305ad, 0xe596b7b0c643c719,
+ 0x8f7e32ce7bea5c6f, 0xb35dbf821ae4f38b, 0xe0352f62a19e306e};
+
+template <typename T>
+const uint128_wrapper basic_data<T>::dragonbox_pow10_significands_128[] = {
+#if FMT_USE_FULL_CACHE_DRAGONBOX
+ {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
+ {0x9faacf3df73609b1, 0x77b191618c54e9ad},
+ {0xc795830d75038c1d, 0xd59df5b9ef6a2418},
+ {0xf97ae3d0d2446f25, 0x4b0573286b44ad1e},
+ {0x9becce62836ac577, 0x4ee367f9430aec33},
+ {0xc2e801fb244576d5, 0x229c41f793cda740},
+ {0xf3a20279ed56d48a, 0x6b43527578c11110},
+ {0x9845418c345644d6, 0x830a13896b78aaaa},
+ {0xbe5691ef416bd60c, 0x23cc986bc656d554},
+ {0xedec366b11c6cb8f, 0x2cbfbe86b7ec8aa9},
+ {0x94b3a202eb1c3f39, 0x7bf7d71432f3d6aa},
+ {0xb9e08a83a5e34f07, 0xdaf5ccd93fb0cc54},
+ {0xe858ad248f5c22c9, 0xd1b3400f8f9cff69},
+ {0x91376c36d99995be, 0x23100809b9c21fa2},
+ {0xb58547448ffffb2d, 0xabd40a0c2832a78b},
+ {0xe2e69915b3fff9f9, 0x16c90c8f323f516d},
+ {0x8dd01fad907ffc3b, 0xae3da7d97f6792e4},
+ {0xb1442798f49ffb4a, 0x99cd11cfdf41779d},
+ {0xdd95317f31c7fa1d, 0x40405643d711d584},
+ {0x8a7d3eef7f1cfc52, 0x482835ea666b2573},
+ {0xad1c8eab5ee43b66, 0xda3243650005eed0},
+ {0xd863b256369d4a40, 0x90bed43e40076a83},
+ {0x873e4f75e2224e68, 0x5a7744a6e804a292},
+ {0xa90de3535aaae202, 0x711515d0a205cb37},
+ {0xd3515c2831559a83, 0x0d5a5b44ca873e04},
+ {0x8412d9991ed58091, 0xe858790afe9486c3},
+ {0xa5178fff668ae0b6, 0x626e974dbe39a873},
+ {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},
+ {0x80fa687f881c7f8e, 0x7ce66634bc9d0b9a},
+ {0xa139029f6a239f72, 0x1c1fffc1ebc44e81},
+ {0xc987434744ac874e, 0xa327ffb266b56221},
+ {0xfbe9141915d7a922, 0x4bf1ff9f0062baa9},
+ {0x9d71ac8fada6c9b5, 0x6f773fc3603db4aa},
+ {0xc4ce17b399107c22, 0xcb550fb4384d21d4},
+ {0xf6019da07f549b2b, 0x7e2a53a146606a49},
+ {0x99c102844f94e0fb, 0x2eda7444cbfc426e},
+ {0xc0314325637a1939, 0xfa911155fefb5309},
+ {0xf03d93eebc589f88, 0x793555ab7eba27cb},
+ {0x96267c7535b763b5, 0x4bc1558b2f3458df},
+ {0xbbb01b9283253ca2, 0x9eb1aaedfb016f17},
+ {0xea9c227723ee8bcb, 0x465e15a979c1cadd},
+ {0x92a1958a7675175f, 0x0bfacd89ec191eca},
+ {0xb749faed14125d36, 0xcef980ec671f667c},
+ {0xe51c79a85916f484, 0x82b7e12780e7401b},
+ {0x8f31cc0937ae58d2, 0xd1b2ecb8b0908811},
+ {0xb2fe3f0b8599ef07, 0x861fa7e6dcb4aa16},
+ {0xdfbdcece67006ac9, 0x67a791e093e1d49b},
+ {0x8bd6a141006042bd, 0xe0c8bb2c5c6d24e1},
+ {0xaecc49914078536d, 0x58fae9f773886e19},
+ {0xda7f5bf590966848, 0xaf39a475506a899f},
+ {0x888f99797a5e012d, 0x6d8406c952429604},
+ {0xaab37fd7d8f58178, 0xc8e5087ba6d33b84},
+ {0xd5605fcdcf32e1d6, 0xfb1e4a9a90880a65},
+ {0x855c3be0a17fcd26, 0x5cf2eea09a550680},
+ {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},
+ {0xd0601d8efc57b08b, 0xf13b94daf124da27},
+ {0x823c12795db6ce57, 0x76c53d08d6b70859},
+ {0xa2cb1717b52481ed, 0x54768c4b0c64ca6f},
+ {0xcb7ddcdda26da268, 0xa9942f5dcf7dfd0a},
+ {0xfe5d54150b090b02, 0xd3f93b35435d7c4d},
+ {0x9efa548d26e5a6e1, 0xc47bc5014a1a6db0},
+ {0xc6b8e9b0709f109a, 0x359ab6419ca1091c},
+ {0xf867241c8cc6d4c0, 0xc30163d203c94b63},
+ {0x9b407691d7fc44f8, 0x79e0de63425dcf1e},
+ {0xc21094364dfb5636, 0x985915fc12f542e5},
+ {0xf294b943e17a2bc4, 0x3e6f5b7b17b2939e},
+ {0x979cf3ca6cec5b5a, 0xa705992ceecf9c43},
+ {0xbd8430bd08277231, 0x50c6ff782a838354},
+ {0xece53cec4a314ebd, 0xa4f8bf5635246429},
+ {0x940f4613ae5ed136, 0x871b7795e136be9a},
+ {0xb913179899f68584, 0x28e2557b59846e40},
+ {0xe757dd7ec07426e5, 0x331aeada2fe589d0},
+ {0x9096ea6f3848984f, 0x3ff0d2c85def7622},
+ {0xb4bca50b065abe63, 0x0fed077a756b53aa},
+ {0xe1ebce4dc7f16dfb, 0xd3e8495912c62895},
+ {0x8d3360f09cf6e4bd, 0x64712dd7abbbd95d},
+ {0xb080392cc4349dec, 0xbd8d794d96aacfb4},
+ {0xdca04777f541c567, 0xecf0d7a0fc5583a1},
+ {0x89e42caaf9491b60, 0xf41686c49db57245},
+ {0xac5d37d5b79b6239, 0x311c2875c522ced6},
+ {0xd77485cb25823ac7, 0x7d633293366b828c},
+ {0x86a8d39ef77164bc, 0xae5dff9c02033198},
+ {0xa8530886b54dbdeb, 0xd9f57f830283fdfd},
+ {0xd267caa862a12d66, 0xd072df63c324fd7c},
+ {0x8380dea93da4bc60, 0x4247cb9e59f71e6e},
+ {0xa46116538d0deb78, 0x52d9be85f074e609},
+ {0xcd795be870516656, 0x67902e276c921f8c},
+ {0x806bd9714632dff6, 0x00ba1cd8a3db53b7},
+ {0xa086cfcd97bf97f3, 0x80e8a40eccd228a5},
+ {0xc8a883c0fdaf7df0, 0x6122cd128006b2ce},
+ {0xfad2a4b13d1b5d6c, 0x796b805720085f82},
+ {0x9cc3a6eec6311a63, 0xcbe3303674053bb1},
+ {0xc3f490aa77bd60fc, 0xbedbfc4411068a9d},
+ {0xf4f1b4d515acb93b, 0xee92fb5515482d45},
+ {0x991711052d8bf3c5, 0x751bdd152d4d1c4b},
+ {0xbf5cd54678eef0b6, 0xd262d45a78a0635e},
+ {0xef340a98172aace4, 0x86fb897116c87c35},
+ {0x9580869f0e7aac0e, 0xd45d35e6ae3d4da1},
+ {0xbae0a846d2195712, 0x8974836059cca10a},
+ {0xe998d258869facd7, 0x2bd1a438703fc94c},
+ {0x91ff83775423cc06, 0x7b6306a34627ddd0},
+ {0xb67f6455292cbf08, 0x1a3bc84c17b1d543},
+ {0xe41f3d6a7377eeca, 0x20caba5f1d9e4a94},
+ {0x8e938662882af53e, 0x547eb47b7282ee9d},
+ {0xb23867fb2a35b28d, 0xe99e619a4f23aa44},
+ {0xdec681f9f4c31f31, 0x6405fa00e2ec94d5},
+ {0x8b3c113c38f9f37e, 0xde83bc408dd3dd05},
+ {0xae0b158b4738705e, 0x9624ab50b148d446},
+ {0xd98ddaee19068c76, 0x3badd624dd9b0958},
+ {0x87f8a8d4cfa417c9, 0xe54ca5d70a80e5d7},
+ {0xa9f6d30a038d1dbc, 0x5e9fcf4ccd211f4d},
+ {0xd47487cc8470652b, 0x7647c32000696720},
+ {0x84c8d4dfd2c63f3b, 0x29ecd9f40041e074},
+ {0xa5fb0a17c777cf09, 0xf468107100525891},
+ {0xcf79cc9db955c2cc, 0x7182148d4066eeb5},
+ {0x81ac1fe293d599bf, 0xc6f14cd848405531},
+ {0xa21727db38cb002f, 0xb8ada00e5a506a7d},
+ {0xca9cf1d206fdc03b, 0xa6d90811f0e4851d},
+ {0xfd442e4688bd304a, 0x908f4a166d1da664},
+ {0x9e4a9cec15763e2e, 0x9a598e4e043287ff},
+ {0xc5dd44271ad3cdba, 0x40eff1e1853f29fe},
+ {0xf7549530e188c128, 0xd12bee59e68ef47d},
+ {0x9a94dd3e8cf578b9, 0x82bb74f8301958cf},
+ {0xc13a148e3032d6e7, 0xe36a52363c1faf02},
+ {0xf18899b1bc3f8ca1, 0xdc44e6c3cb279ac2},
+ {0x96f5600f15a7b7e5, 0x29ab103a5ef8c0ba},
+ {0xbcb2b812db11a5de, 0x7415d448f6b6f0e8},
+ {0xebdf661791d60f56, 0x111b495b3464ad22},
+ {0x936b9fcebb25c995, 0xcab10dd900beec35},
+ {0xb84687c269ef3bfb, 0x3d5d514f40eea743},
+ {0xe65829b3046b0afa, 0x0cb4a5a3112a5113},
+ {0x8ff71a0fe2c2e6dc, 0x47f0e785eaba72ac},
+ {0xb3f4e093db73a093, 0x59ed216765690f57},
+ {0xe0f218b8d25088b8, 0x306869c13ec3532d},
+ {0x8c974f7383725573, 0x1e414218c73a13fc},
+ {0xafbd2350644eeacf, 0xe5d1929ef90898fb},
+ {0xdbac6c247d62a583, 0xdf45f746b74abf3a},
+ {0x894bc396ce5da772, 0x6b8bba8c328eb784},
+ {0xab9eb47c81f5114f, 0x066ea92f3f326565},
+ {0xd686619ba27255a2, 0xc80a537b0efefebe},
+ {0x8613fd0145877585, 0xbd06742ce95f5f37},
+ {0xa798fc4196e952e7, 0x2c48113823b73705},
+ {0xd17f3b51fca3a7a0, 0xf75a15862ca504c6},
+ {0x82ef85133de648c4, 0x9a984d73dbe722fc},
+ {0xa3ab66580d5fdaf5, 0xc13e60d0d2e0ebbb},
+ {0xcc963fee10b7d1b3, 0x318df905079926a9},
+ {0xffbbcfe994e5c61f, 0xfdf17746497f7053},
+ {0x9fd561f1fd0f9bd3, 0xfeb6ea8bedefa634},
+ {0xc7caba6e7c5382c8, 0xfe64a52ee96b8fc1},
+ {0xf9bd690a1b68637b, 0x3dfdce7aa3c673b1},
+ {0x9c1661a651213e2d, 0x06bea10ca65c084f},
+ {0xc31bfa0fe5698db8, 0x486e494fcff30a63},
+ {0xf3e2f893dec3f126, 0x5a89dba3c3efccfb},
+ {0x986ddb5c6b3a76b7, 0xf89629465a75e01d},
+ {0xbe89523386091465, 0xf6bbb397f1135824},
+ {0xee2ba6c0678b597f, 0x746aa07ded582e2d},
+ {0x94db483840b717ef, 0xa8c2a44eb4571cdd},
+ {0xba121a4650e4ddeb, 0x92f34d62616ce414},
+ {0xe896a0d7e51e1566, 0x77b020baf9c81d18},
+ {0x915e2486ef32cd60, 0x0ace1474dc1d122f},
+ {0xb5b5ada8aaff80b8, 0x0d819992132456bb},
+ {0xe3231912d5bf60e6, 0x10e1fff697ed6c6a},
+ {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},
+ {0xb1736b96b6fd83b3, 0xbd308ff8a6b17cb3},
+ {0xddd0467c64bce4a0, 0xac7cb3f6d05ddbdf},
+ {0x8aa22c0dbef60ee4, 0x6bcdf07a423aa96c},
+ {0xad4ab7112eb3929d, 0x86c16c98d2c953c7},
+ {0xd89d64d57a607744, 0xe871c7bf077ba8b8},
+ {0x87625f056c7c4a8b, 0x11471cd764ad4973},
+ {0xa93af6c6c79b5d2d, 0xd598e40d3dd89bd0},
+ {0xd389b47879823479, 0x4aff1d108d4ec2c4},
+ {0x843610cb4bf160cb, 0xcedf722a585139bb},
+ {0xa54394fe1eedb8fe, 0xc2974eb4ee658829},
+ {0xce947a3da6a9273e, 0x733d226229feea33},
+ {0x811ccc668829b887, 0x0806357d5a3f5260},
+ {0xa163ff802a3426a8, 0xca07c2dcb0cf26f8},
+ {0xc9bcff6034c13052, 0xfc89b393dd02f0b6},
+ {0xfc2c3f3841f17c67, 0xbbac2078d443ace3},
+ {0x9d9ba7832936edc0, 0xd54b944b84aa4c0e},
+ {0xc5029163f384a931, 0x0a9e795e65d4df12},
+ {0xf64335bcf065d37d, 0x4d4617b5ff4a16d6},
+ {0x99ea0196163fa42e, 0x504bced1bf8e4e46},
+ {0xc06481fb9bcf8d39, 0xe45ec2862f71e1d7},
+ {0xf07da27a82c37088, 0x5d767327bb4e5a4d},
+ {0x964e858c91ba2655, 0x3a6a07f8d510f870},
+ {0xbbe226efb628afea, 0x890489f70a55368c},
+ {0xeadab0aba3b2dbe5, 0x2b45ac74ccea842f},
+ {0x92c8ae6b464fc96f, 0x3b0b8bc90012929e},
+ {0xb77ada0617e3bbcb, 0x09ce6ebb40173745},
+ {0xe55990879ddcaabd, 0xcc420a6a101d0516},
+ {0x8f57fa54c2a9eab6, 0x9fa946824a12232e},
+ {0xb32df8e9f3546564, 0x47939822dc96abfa},
+ {0xdff9772470297ebd, 0x59787e2b93bc56f8},
+ {0x8bfbea76c619ef36, 0x57eb4edb3c55b65b},
+ {0xaefae51477a06b03, 0xede622920b6b23f2},
+ {0xdab99e59958885c4, 0xe95fab368e45ecee},
+ {0x88b402f7fd75539b, 0x11dbcb0218ebb415},
+ {0xaae103b5fcd2a881, 0xd652bdc29f26a11a},
+ {0xd59944a37c0752a2, 0x4be76d3346f04960},
+ {0x857fcae62d8493a5, 0x6f70a4400c562ddc},
+ {0xa6dfbd9fb8e5b88e, 0xcb4ccd500f6bb953},
+ {0xd097ad07a71f26b2, 0x7e2000a41346a7a8},
+ {0x825ecc24c873782f, 0x8ed400668c0c28c9},
+ {0xa2f67f2dfa90563b, 0x728900802f0f32fb},
+ {0xcbb41ef979346bca, 0x4f2b40a03ad2ffba},
+ {0xfea126b7d78186bc, 0xe2f610c84987bfa9},
+ {0x9f24b832e6b0f436, 0x0dd9ca7d2df4d7ca},
+ {0xc6ede63fa05d3143, 0x91503d1c79720dbc},
+ {0xf8a95fcf88747d94, 0x75a44c6397ce912b},
+ {0x9b69dbe1b548ce7c, 0xc986afbe3ee11abb},
+ {0xc24452da229b021b, 0xfbe85badce996169},
+ {0xf2d56790ab41c2a2, 0xfae27299423fb9c4},
+ {0x97c560ba6b0919a5, 0xdccd879fc967d41b},
+ {0xbdb6b8e905cb600f, 0x5400e987bbc1c921},
+ {0xed246723473e3813, 0x290123e9aab23b69},
+ {0x9436c0760c86e30b, 0xf9a0b6720aaf6522},
+ {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},
+ {0xe7958cb87392c2c2, 0xb60b1d1230b20e05},
+ {0x90bd77f3483bb9b9, 0xb1c6f22b5e6f48c3},
+ {0xb4ecd5f01a4aa828, 0x1e38aeb6360b1af4},
+ {0xe2280b6c20dd5232, 0x25c6da63c38de1b1},
+ {0x8d590723948a535f, 0x579c487e5a38ad0f},
+ {0xb0af48ec79ace837, 0x2d835a9df0c6d852},
+ {0xdcdb1b2798182244, 0xf8e431456cf88e66},
+ {0x8a08f0f8bf0f156b, 0x1b8e9ecb641b5900},
+ {0xac8b2d36eed2dac5, 0xe272467e3d222f40},
+ {0xd7adf884aa879177, 0x5b0ed81dcc6abb10},
+ {0x86ccbb52ea94baea, 0x98e947129fc2b4ea},
+ {0xa87fea27a539e9a5, 0x3f2398d747b36225},
+ {0xd29fe4b18e88640e, 0x8eec7f0d19a03aae},
+ {0x83a3eeeef9153e89, 0x1953cf68300424ad},
+ {0xa48ceaaab75a8e2b, 0x5fa8c3423c052dd8},
+ {0xcdb02555653131b6, 0x3792f412cb06794e},
+ {0x808e17555f3ebf11, 0xe2bbd88bbee40bd1},
+ {0xa0b19d2ab70e6ed6, 0x5b6aceaeae9d0ec5},
+ {0xc8de047564d20a8b, 0xf245825a5a445276},
+ {0xfb158592be068d2e, 0xeed6e2f0f0d56713},
+ {0x9ced737bb6c4183d, 0x55464dd69685606c},
+ {0xc428d05aa4751e4c, 0xaa97e14c3c26b887},
+ {0xf53304714d9265df, 0xd53dd99f4b3066a9},
+ {0x993fe2c6d07b7fab, 0xe546a8038efe402a},
+ {0xbf8fdb78849a5f96, 0xde98520472bdd034},
+ {0xef73d256a5c0f77c, 0x963e66858f6d4441},
+ {0x95a8637627989aad, 0xdde7001379a44aa9},
+ {0xbb127c53b17ec159, 0x5560c018580d5d53},
+ {0xe9d71b689dde71af, 0xaab8f01e6e10b4a7},
+ {0x9226712162ab070d, 0xcab3961304ca70e9},
+ {0xb6b00d69bb55c8d1, 0x3d607b97c5fd0d23},
+ {0xe45c10c42a2b3b05, 0x8cb89a7db77c506b},
+ {0x8eb98a7a9a5b04e3, 0x77f3608e92adb243},
+ {0xb267ed1940f1c61c, 0x55f038b237591ed4},
+ {0xdf01e85f912e37a3, 0x6b6c46dec52f6689},
+ {0x8b61313bbabce2c6, 0x2323ac4b3b3da016},
+ {0xae397d8aa96c1b77, 0xabec975e0a0d081b},
+ {0xd9c7dced53c72255, 0x96e7bd358c904a22},
+ {0x881cea14545c7575, 0x7e50d64177da2e55},
+ {0xaa242499697392d2, 0xdde50bd1d5d0b9ea},
+ {0xd4ad2dbfc3d07787, 0x955e4ec64b44e865},
+ {0x84ec3c97da624ab4, 0xbd5af13bef0b113f},
+ {0xa6274bbdd0fadd61, 0xecb1ad8aeacdd58f},
+ {0xcfb11ead453994ba, 0x67de18eda5814af3},
+ {0x81ceb32c4b43fcf4, 0x80eacf948770ced8},
+ {0xa2425ff75e14fc31, 0xa1258379a94d028e},
+ {0xcad2f7f5359a3b3e, 0x096ee45813a04331},
+ {0xfd87b5f28300ca0d, 0x8bca9d6e188853fd},
+ {0x9e74d1b791e07e48, 0x775ea264cf55347e},
+ {0xc612062576589dda, 0x95364afe032a819e},
+ {0xf79687aed3eec551, 0x3a83ddbd83f52205},
+ {0x9abe14cd44753b52, 0xc4926a9672793543},
+ {0xc16d9a0095928a27, 0x75b7053c0f178294},
+ {0xf1c90080baf72cb1, 0x5324c68b12dd6339},
+ {0x971da05074da7bee, 0xd3f6fc16ebca5e04},
+ {0xbce5086492111aea, 0x88f4bb1ca6bcf585},
+ {0xec1e4a7db69561a5, 0x2b31e9e3d06c32e6},
+ {0x9392ee8e921d5d07, 0x3aff322e62439fd0},
+ {0xb877aa3236a4b449, 0x09befeb9fad487c3},
+ {0xe69594bec44de15b, 0x4c2ebe687989a9b4},
+ {0x901d7cf73ab0acd9, 0x0f9d37014bf60a11},
+ {0xb424dc35095cd80f, 0x538484c19ef38c95},
+ {0xe12e13424bb40e13, 0x2865a5f206b06fba},
+ {0x8cbccc096f5088cb, 0xf93f87b7442e45d4},
+ {0xafebff0bcb24aafe, 0xf78f69a51539d749},
+ {0xdbe6fecebdedd5be, 0xb573440e5a884d1c},
+ {0x89705f4136b4a597, 0x31680a88f8953031},
+ {0xabcc77118461cefc, 0xfdc20d2b36ba7c3e},
+ {0xd6bf94d5e57a42bc, 0x3d32907604691b4d},
+ {0x8637bd05af6c69b5, 0xa63f9a49c2c1b110},
+ {0xa7c5ac471b478423, 0x0fcf80dc33721d54},
+ {0xd1b71758e219652b, 0xd3c36113404ea4a9},
+ {0x83126e978d4fdf3b, 0x645a1cac083126ea},
+ {0xa3d70a3d70a3d70a, 0x3d70a3d70a3d70a4},
+ {0xcccccccccccccccc, 0xcccccccccccccccd},
+ {0x8000000000000000, 0x0000000000000000},
+ {0xa000000000000000, 0x0000000000000000},
+ {0xc800000000000000, 0x0000000000000000},
+ {0xfa00000000000000, 0x0000000000000000},
+ {0x9c40000000000000, 0x0000000000000000},
+ {0xc350000000000000, 0x0000000000000000},
+ {0xf424000000000000, 0x0000000000000000},
+ {0x9896800000000000, 0x0000000000000000},
+ {0xbebc200000000000, 0x0000000000000000},
+ {0xee6b280000000000, 0x0000000000000000},
+ {0x9502f90000000000, 0x0000000000000000},
+ {0xba43b74000000000, 0x0000000000000000},
+ {0xe8d4a51000000000, 0x0000000000000000},
+ {0x9184e72a00000000, 0x0000000000000000},
+ {0xb5e620f480000000, 0x0000000000000000},
+ {0xe35fa931a0000000, 0x0000000000000000},
+ {0x8e1bc9bf04000000, 0x0000000000000000},
+ {0xb1a2bc2ec5000000, 0x0000000000000000},
+ {0xde0b6b3a76400000, 0x0000000000000000},
+ {0x8ac7230489e80000, 0x0000000000000000},
+ {0xad78ebc5ac620000, 0x0000000000000000},
+ {0xd8d726b7177a8000, 0x0000000000000000},
+ {0x878678326eac9000, 0x0000000000000000},
+ {0xa968163f0a57b400, 0x0000000000000000},
+ {0xd3c21bcecceda100, 0x0000000000000000},
+ {0x84595161401484a0, 0x0000000000000000},
+ {0xa56fa5b99019a5c8, 0x0000000000000000},
+ {0xcecb8f27f4200f3a, 0x0000000000000000},
+ {0x813f3978f8940984, 0x4000000000000000},
+ {0xa18f07d736b90be5, 0x5000000000000000},
+ {0xc9f2c9cd04674ede, 0xa400000000000000},
+ {0xfc6f7c4045812296, 0x4d00000000000000},
+ {0x9dc5ada82b70b59d, 0xf020000000000000},
+ {0xc5371912364ce305, 0x6c28000000000000},
+ {0xf684df56c3e01bc6, 0xc732000000000000},
+ {0x9a130b963a6c115c, 0x3c7f400000000000},
+ {0xc097ce7bc90715b3, 0x4b9f100000000000},
+ {0xf0bdc21abb48db20, 0x1e86d40000000000},
+ {0x96769950b50d88f4, 0x1314448000000000},
+ {0xbc143fa4e250eb31, 0x17d955a000000000},
+ {0xeb194f8e1ae525fd, 0x5dcfab0800000000},
+ {0x92efd1b8d0cf37be, 0x5aa1cae500000000},
+ {0xb7abc627050305ad, 0xf14a3d9e40000000},
+ {0xe596b7b0c643c719, 0x6d9ccd05d0000000},
+ {0x8f7e32ce7bea5c6f, 0xe4820023a2000000},
+ {0xb35dbf821ae4f38b, 0xdda2802c8a800000},
+ {0xe0352f62a19e306e, 0xd50b2037ad200000},
+ {0x8c213d9da502de45, 0x4526f422cc340000},
+ {0xaf298d050e4395d6, 0x9670b12b7f410000},
+ {0xdaf3f04651d47b4c, 0x3c0cdd765f114000},
+ {0x88d8762bf324cd0f, 0xa5880a69fb6ac800},
+ {0xab0e93b6efee0053, 0x8eea0d047a457a00},
+ {0xd5d238a4abe98068, 0x72a4904598d6d880},
+ {0x85a36366eb71f041, 0x47a6da2b7f864750},
+ {0xa70c3c40a64e6c51, 0x999090b65f67d924},
+ {0xd0cf4b50cfe20765, 0xfff4b4e3f741cf6d},
+ {0x82818f1281ed449f, 0xbff8f10e7a8921a4},
+ {0xa321f2d7226895c7, 0xaff72d52192b6a0d},
+ {0xcbea6f8ceb02bb39, 0x9bf4f8a69f764490},
+ {0xfee50b7025c36a08, 0x02f236d04753d5b4},
+ {0x9f4f2726179a2245, 0x01d762422c946590},
+ {0xc722f0ef9d80aad6, 0x424d3ad2b7b97ef5},
+ {0xf8ebad2b84e0d58b, 0xd2e0898765a7deb2},
+ {0x9b934c3b330c8577, 0x63cc55f49f88eb2f},
+ {0xc2781f49ffcfa6d5, 0x3cbf6b71c76b25fb},
+ {0xf316271c7fc3908a, 0x8bef464e3945ef7a},
+ {0x97edd871cfda3a56, 0x97758bf0e3cbb5ac},
+ {0xbde94e8e43d0c8ec, 0x3d52eeed1cbea317},
+ {0xed63a231d4c4fb27, 0x4ca7aaa863ee4bdd},
+ {0x945e455f24fb1cf8, 0x8fe8caa93e74ef6a},
+ {0xb975d6b6ee39e436, 0xb3e2fd538e122b44},
+ {0xe7d34c64a9c85d44, 0x60dbbca87196b616},
+ {0x90e40fbeea1d3a4a, 0xbc8955e946fe31cd},
+ {0xb51d13aea4a488dd, 0x6babab6398bdbe41},
+ {0xe264589a4dcdab14, 0xc696963c7eed2dd1},
+ {0x8d7eb76070a08aec, 0xfc1e1de5cf543ca2},
+ {0xb0de65388cc8ada8, 0x3b25a55f43294bcb},
+ {0xdd15fe86affad912, 0x49ef0eb713f39ebe},
+ {0x8a2dbf142dfcc7ab, 0x6e3569326c784337},
+ {0xacb92ed9397bf996, 0x49c2c37f07965404},
+ {0xd7e77a8f87daf7fb, 0xdc33745ec97be906},
+ {0x86f0ac99b4e8dafd, 0x69a028bb3ded71a3},
+ {0xa8acd7c0222311bc, 0xc40832ea0d68ce0c},
+ {0xd2d80db02aabd62b, 0xf50a3fa490c30190},
+ {0x83c7088e1aab65db, 0x792667c6da79e0fa},
+ {0xa4b8cab1a1563f52, 0x577001b891185938},
+ {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86},
+ {0x80b05e5ac60b6178, 0x544f8158315b05b4},
+ {0xa0dc75f1778e39d6, 0x696361ae3db1c721},
+ {0xc913936dd571c84c, 0x03bc3a19cd1e38e9},
+ {0xfb5878494ace3a5f, 0x04ab48a04065c723},
+ {0x9d174b2dcec0e47b, 0x62eb0d64283f9c76},
+ {0xc45d1df942711d9a, 0x3ba5d0bd324f8394},
+ {0xf5746577930d6500, 0xca8f44ec7ee36479},
+ {0x9968bf6abbe85f20, 0x7e998b13cf4e1ecb},
+ {0xbfc2ef456ae276e8, 0x9e3fedd8c321a67e},
+ {0xefb3ab16c59b14a2, 0xc5cfe94ef3ea101e},
+ {0x95d04aee3b80ece5, 0xbba1f1d158724a12},
+ {0xbb445da9ca61281f, 0x2a8a6e45ae8edc97},
+ {0xea1575143cf97226, 0xf52d09d71a3293bd},
+ {0x924d692ca61be758, 0x593c2626705f9c56},
+ {0xb6e0c377cfa2e12e, 0x6f8b2fb00c77836c},
+ {0xe498f455c38b997a, 0x0b6dfb9c0f956447},
+ {0x8edf98b59a373fec, 0x4724bd4189bd5eac},
+ {0xb2977ee300c50fe7, 0x58edec91ec2cb657},
+ {0xdf3d5e9bc0f653e1, 0x2f2967b66737e3ed},
+ {0x8b865b215899f46c, 0xbd79e0d20082ee74},
+ {0xae67f1e9aec07187, 0xecd8590680a3aa11},
+ {0xda01ee641a708de9, 0xe80e6f4820cc9495},
+ {0x884134fe908658b2, 0x3109058d147fdcdd},
+ {0xaa51823e34a7eede, 0xbd4b46f0599fd415},
+ {0xd4e5e2cdc1d1ea96, 0x6c9e18ac7007c91a},
+ {0x850fadc09923329e, 0x03e2cf6bc604ddb0},
+ {0xa6539930bf6bff45, 0x84db8346b786151c},
+ {0xcfe87f7cef46ff16, 0xe612641865679a63},
+ {0x81f14fae158c5f6e, 0x4fcb7e8f3f60c07e},
+ {0xa26da3999aef7749, 0xe3be5e330f38f09d},
+ {0xcb090c8001ab551c, 0x5cadf5bfd3072cc5},
+ {0xfdcb4fa002162a63, 0x73d9732fc7c8f7f6},
+ {0x9e9f11c4014dda7e, 0x2867e7fddcdd9afa},
+ {0xc646d63501a1511d, 0xb281e1fd541501b8},
+ {0xf7d88bc24209a565, 0x1f225a7ca91a4226},
+ {0x9ae757596946075f, 0x3375788de9b06958},
+ {0xc1a12d2fc3978937, 0x0052d6b1641c83ae},
+ {0xf209787bb47d6b84, 0xc0678c5dbd23a49a},
+ {0x9745eb4d50ce6332, 0xf840b7ba963646e0},
+ {0xbd176620a501fbff, 0xb650e5a93bc3d898},
+ {0xec5d3fa8ce427aff, 0xa3e51f138ab4cebe},
+ {0x93ba47c980e98cdf, 0xc66f336c36b10137},
+ {0xb8a8d9bbe123f017, 0xb80b0047445d4184},
+ {0xe6d3102ad96cec1d, 0xa60dc059157491e5},
+ {0x9043ea1ac7e41392, 0x87c89837ad68db2f},
+ {0xb454e4a179dd1877, 0x29babe4598c311fb},
+ {0xe16a1dc9d8545e94, 0xf4296dd6fef3d67a},
+ {0x8ce2529e2734bb1d, 0x1899e4a65f58660c},
+ {0xb01ae745b101e9e4, 0x5ec05dcff72e7f8f},
+ {0xdc21a1171d42645d, 0x76707543f4fa1f73},
+ {0x899504ae72497eba, 0x6a06494a791c53a8},
+ {0xabfa45da0edbde69, 0x0487db9d17636892},
+ {0xd6f8d7509292d603, 0x45a9d2845d3c42b6},
+ {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2},
+ {0xa7f26836f282b732, 0x8e6cac7768d7141e},
+ {0xd1ef0244af2364ff, 0x3207d795430cd926},
+ {0x8335616aed761f1f, 0x7f44e6bd49e807b8},
+ {0xa402b9c5a8d3a6e7, 0x5f16206c9c6209a6},
+ {0xcd036837130890a1, 0x36dba887c37a8c0f},
+ {0x802221226be55a64, 0xc2494954da2c9789},
+ {0xa02aa96b06deb0fd, 0xf2db9baa10b7bd6c},
+ {0xc83553c5c8965d3d, 0x6f92829494e5acc7},
+ {0xfa42a8b73abbf48c, 0xcb772339ba1f17f9},
+ {0x9c69a97284b578d7, 0xff2a760414536efb},
+ {0xc38413cf25e2d70d, 0xfef5138519684aba},
+ {0xf46518c2ef5b8cd1, 0x7eb258665fc25d69},
+ {0x98bf2f79d5993802, 0xef2f773ffbd97a61},
+ {0xbeeefb584aff8603, 0xaafb550ffacfd8fa},
+ {0xeeaaba2e5dbf6784, 0x95ba2a53f983cf38},
+ {0x952ab45cfa97a0b2, 0xdd945a747bf26183},
+ {0xba756174393d88df, 0x94f971119aeef9e4},
+ {0xe912b9d1478ceb17, 0x7a37cd5601aab85d},
+ {0x91abb422ccb812ee, 0xac62e055c10ab33a},
+ {0xb616a12b7fe617aa, 0x577b986b314d6009},
+ {0xe39c49765fdf9d94, 0xed5a7e85fda0b80b},
+ {0x8e41ade9fbebc27d, 0x14588f13be847307},
+ {0xb1d219647ae6b31c, 0x596eb2d8ae258fc8},
+ {0xde469fbd99a05fe3, 0x6fca5f8ed9aef3bb},
+ {0x8aec23d680043bee, 0x25de7bb9480d5854},
+ {0xada72ccc20054ae9, 0xaf561aa79a10ae6a},
+ {0xd910f7ff28069da4, 0x1b2ba1518094da04},
+ {0x87aa9aff79042286, 0x90fb44d2f05d0842},
+ {0xa99541bf57452b28, 0x353a1607ac744a53},
+ {0xd3fa922f2d1675f2, 0x42889b8997915ce8},
+ {0x847c9b5d7c2e09b7, 0x69956135febada11},
+ {0xa59bc234db398c25, 0x43fab9837e699095},
+ {0xcf02b2c21207ef2e, 0x94f967e45e03f4bb},
+ {0x8161afb94b44f57d, 0x1d1be0eebac278f5},
+ {0xa1ba1ba79e1632dc, 0x6462d92a69731732},
+ {0xca28a291859bbf93, 0x7d7b8f7503cfdcfe},
+ {0xfcb2cb35e702af78, 0x5cda735244c3d43e},
+ {0x9defbf01b061adab, 0x3a0888136afa64a7},
+ {0xc56baec21c7a1916, 0x088aaa1845b8fdd0},
+ {0xf6c69a72a3989f5b, 0x8aad549e57273d45},
+ {0x9a3c2087a63f6399, 0x36ac54e2f678864b},
+ {0xc0cb28a98fcf3c7f, 0x84576a1bb416a7dd},
+ {0xf0fdf2d3f3c30b9f, 0x656d44a2a11c51d5},
+ {0x969eb7c47859e743, 0x9f644ae5a4b1b325},
+ {0xbc4665b596706114, 0x873d5d9f0dde1fee},
+ {0xeb57ff22fc0c7959, 0xa90cb506d155a7ea},
+ {0x9316ff75dd87cbd8, 0x09a7f12442d588f2},
+ {0xb7dcbf5354e9bece, 0x0c11ed6d538aeb2f},
+ {0xe5d3ef282a242e81, 0x8f1668c8a86da5fa},
+ {0x8fa475791a569d10, 0xf96e017d694487bc},
+ {0xb38d92d760ec4455, 0x37c981dcc395a9ac},
+ {0xe070f78d3927556a, 0x85bbe253f47b1417},
+ {0x8c469ab843b89562, 0x93956d7478ccec8e},
+ {0xaf58416654a6babb, 0x387ac8d1970027b2},
+ {0xdb2e51bfe9d0696a, 0x06997b05fcc0319e},
+ {0x88fcf317f22241e2, 0x441fece3bdf81f03},
+ {0xab3c2fddeeaad25a, 0xd527e81cad7626c3},
+ {0xd60b3bd56a5586f1, 0x8a71e223d8d3b074},
+ {0x85c7056562757456, 0xf6872d5667844e49},
+ {0xa738c6bebb12d16c, 0xb428f8ac016561db},
+ {0xd106f86e69d785c7, 0xe13336d701beba52},
+ {0x82a45b450226b39c, 0xecc0024661173473},
+ {0xa34d721642b06084, 0x27f002d7f95d0190},
+ {0xcc20ce9bd35c78a5, 0x31ec038df7b441f4},
+ {0xff290242c83396ce, 0x7e67047175a15271},
+ {0x9f79a169bd203e41, 0x0f0062c6e984d386},
+ {0xc75809c42c684dd1, 0x52c07b78a3e60868},
+ {0xf92e0c3537826145, 0xa7709a56ccdf8a82},
+ {0x9bbcc7a142b17ccb, 0x88a66076400bb691},
+ {0xc2abf989935ddbfe, 0x6acff893d00ea435},
+ {0xf356f7ebf83552fe, 0x0583f6b8c4124d43},
+ {0x98165af37b2153de, 0xc3727a337a8b704a},
+ {0xbe1bf1b059e9a8d6, 0x744f18c0592e4c5c},
+ {0xeda2ee1c7064130c, 0x1162def06f79df73},
+ {0x9485d4d1c63e8be7, 0x8addcb5645ac2ba8},
+ {0xb9a74a0637ce2ee1, 0x6d953e2bd7173692},
+ {0xe8111c87c5c1ba99, 0xc8fa8db6ccdd0437},
+ {0x910ab1d4db9914a0, 0x1d9c9892400a22a2},
+ {0xb54d5e4a127f59c8, 0x2503beb6d00cab4b},
+ {0xe2a0b5dc971f303a, 0x2e44ae64840fd61d},
+ {0x8da471a9de737e24, 0x5ceaecfed289e5d2},
+ {0xb10d8e1456105dad, 0x7425a83e872c5f47},
+ {0xdd50f1996b947518, 0xd12f124e28f77719},
+ {0x8a5296ffe33cc92f, 0x82bd6b70d99aaa6f},
+ {0xace73cbfdc0bfb7b, 0x636cc64d1001550b},
+ {0xd8210befd30efa5a, 0x3c47f7e05401aa4e},
+ {0x8714a775e3e95c78, 0x65acfaec34810a71},
+ {0xa8d9d1535ce3b396, 0x7f1839a741a14d0d},
+ {0xd31045a8341ca07c, 0x1ede48111209a050},
+ {0x83ea2b892091e44d, 0x934aed0aab460432},
+ {0xa4e4b66b68b65d60, 0xf81da84d5617853f},
+ {0xce1de40642e3f4b9, 0x36251260ab9d668e},
+ {0x80d2ae83e9ce78f3, 0xc1d72b7c6b426019},
+ {0xa1075a24e4421730, 0xb24cf65b8612f81f},
+ {0xc94930ae1d529cfc, 0xdee033f26797b627},
+ {0xfb9b7cd9a4a7443c, 0x169840ef017da3b1},
+ {0x9d412e0806e88aa5, 0x8e1f289560ee864e},
+ {0xc491798a08a2ad4e, 0xf1a6f2bab92a27e2},
+ {0xf5b5d7ec8acb58a2, 0xae10af696774b1db},
+ {0x9991a6f3d6bf1765, 0xacca6da1e0a8ef29},
+ {0xbff610b0cc6edd3f, 0x17fd090a58d32af3},
+ {0xeff394dcff8a948e, 0xddfc4b4cef07f5b0},
+ {0x95f83d0a1fb69cd9, 0x4abdaf101564f98e},
+ {0xbb764c4ca7a4440f, 0x9d6d1ad41abe37f1},
+ {0xea53df5fd18d5513, 0x84c86189216dc5ed},
+ {0x92746b9be2f8552c, 0x32fd3cf5b4e49bb4},
+ {0xb7118682dbb66a77, 0x3fbc8c33221dc2a1},
+ {0xe4d5e82392a40515, 0x0fabaf3feaa5334a},
+ {0x8f05b1163ba6832d, 0x29cb4d87f2a7400e},
+ {0xb2c71d5bca9023f8, 0x743e20e9ef511012},
+ {0xdf78e4b2bd342cf6, 0x914da9246b255416},
+ {0x8bab8eefb6409c1a, 0x1ad089b6c2f7548e},
+ {0xae9672aba3d0c320, 0xa184ac2473b529b1},
+ {0xda3c0f568cc4f3e8, 0xc9e5d72d90a2741e},
+ {0x8865899617fb1871, 0x7e2fa67c7a658892},
+ {0xaa7eebfb9df9de8d, 0xddbb901b98feeab7},
+ {0xd51ea6fa85785631, 0x552a74227f3ea565},
+ {0x8533285c936b35de, 0xd53a88958f87275f},
+ {0xa67ff273b8460356, 0x8a892abaf368f137},
+ {0xd01fef10a657842c, 0x2d2b7569b0432d85},
+ {0x8213f56a67f6b29b, 0x9c3b29620e29fc73},
+ {0xa298f2c501f45f42, 0x8349f3ba91b47b8f},
+ {0xcb3f2f7642717713, 0x241c70a936219a73},
+ {0xfe0efb53d30dd4d7, 0xed238cd383aa0110},
+ {0x9ec95d1463e8a506, 0xf4363804324a40aa},
+ {0xc67bb4597ce2ce48, 0xb143c6053edcd0d5},
+ {0xf81aa16fdc1b81da, 0xdd94b7868e94050a},
+ {0x9b10a4e5e9913128, 0xca7cf2b4191c8326},
+ {0xc1d4ce1f63f57d72, 0xfd1c2f611f63a3f0},
+ {0xf24a01a73cf2dccf, 0xbc633b39673c8cec},
+ {0x976e41088617ca01, 0xd5be0503e085d813},
+ {0xbd49d14aa79dbc82, 0x4b2d8644d8a74e18},
+ {0xec9c459d51852ba2, 0xddf8e7d60ed1219e},
+ {0x93e1ab8252f33b45, 0xcabb90e5c942b503},
+ {0xb8da1662e7b00a17, 0x3d6a751f3b936243},
+ {0xe7109bfba19c0c9d, 0x0cc512670a783ad4},
+ {0x906a617d450187e2, 0x27fb2b80668b24c5},
+ {0xb484f9dc9641e9da, 0xb1f9f660802dedf6},
+ {0xe1a63853bbd26451, 0x5e7873f8a0396973},
+ {0x8d07e33455637eb2, 0xdb0b487b6423e1e8},
+ {0xb049dc016abc5e5f, 0x91ce1a9a3d2cda62},
+ {0xdc5c5301c56b75f7, 0x7641a140cc7810fb},
+ {0x89b9b3e11b6329ba, 0xa9e904c87fcb0a9d},
+ {0xac2820d9623bf429, 0x546345fa9fbdcd44},
+ {0xd732290fbacaf133, 0xa97c177947ad4095},
+ {0x867f59a9d4bed6c0, 0x49ed8eabcccc485d},
+ {0xa81f301449ee8c70, 0x5c68f256bfff5a74},
+ {0xd226fc195c6a2f8c, 0x73832eec6fff3111},
+ {0x83585d8fd9c25db7, 0xc831fd53c5ff7eab},
+ {0xa42e74f3d032f525, 0xba3e7ca8b77f5e55},
+ {0xcd3a1230c43fb26f, 0x28ce1bd2e55f35eb},
+ {0x80444b5e7aa7cf85, 0x7980d163cf5b81b3},
+ {0xa0555e361951c366, 0xd7e105bcc332621f},
+ {0xc86ab5c39fa63440, 0x8dd9472bf3fefaa7},
+ {0xfa856334878fc150, 0xb14f98f6f0feb951},
+ {0x9c935e00d4b9d8d2, 0x6ed1bf9a569f33d3},
+ {0xc3b8358109e84f07, 0x0a862f80ec4700c8},
+ {0xf4a642e14c6262c8, 0xcd27bb612758c0fa},
+ {0x98e7e9cccfbd7dbd, 0x8038d51cb897789c},
+ {0xbf21e44003acdd2c, 0xe0470a63e6bd56c3},
+ {0xeeea5d5004981478, 0x1858ccfce06cac74},
+ {0x95527a5202df0ccb, 0x0f37801e0c43ebc8},
+ {0xbaa718e68396cffd, 0xd30560258f54e6ba},
+ {0xe950df20247c83fd, 0x47c6b82ef32a2069},
+ {0x91d28b7416cdd27e, 0x4cdc331d57fa5441},
+ {0xb6472e511c81471d, 0xe0133fe4adf8e952},
+ {0xe3d8f9e563a198e5, 0x58180fddd97723a6},
+ {0x8e679c2f5e44ff8f, 0x570f09eaa7ea7648},
+ {0xb201833b35d63f73, 0x2cd2cc6551e513da},
+ {0xde81e40a034bcf4f, 0xf8077f7ea65e58d1},
+ {0x8b112e86420f6191, 0xfb04afaf27faf782},
+ {0xadd57a27d29339f6, 0x79c5db9af1f9b563},
+ {0xd94ad8b1c7380874, 0x18375281ae7822bc},
+ {0x87cec76f1c830548, 0x8f2293910d0b15b5},
+ {0xa9c2794ae3a3c69a, 0xb2eb3875504ddb22},
+ {0xd433179d9c8cb841, 0x5fa60692a46151eb},
+ {0x849feec281d7f328, 0xdbc7c41ba6bcd333},
+ {0xa5c7ea73224deff3, 0x12b9b522906c0800},
+ {0xcf39e50feae16bef, 0xd768226b34870a00},
+ {0x81842f29f2cce375, 0xe6a1158300d46640},
+ {0xa1e53af46f801c53, 0x60495ae3c1097fd0},
+ {0xca5e89b18b602368, 0x385bb19cb14bdfc4},
+ {0xfcf62c1dee382c42, 0x46729e03dd9ed7b5},
+ {0x9e19db92b4e31ba9, 0x6c07a2c26a8346d1},
+ {0xc5a05277621be293, 0xc7098b7305241885},
+ {0xf70867153aa2db38, 0xb8cbee4fc66d1ea7}
+#else
+ {0xff77b1fcbebcdc4f, 0x25e8e89c13bb0f7b},
+ {0xce5d73ff402d98e3, 0xfb0a3d212dc81290},
+ {0xa6b34ad8c9dfc06f, 0xf42faa48c0ea481f},
+ {0x86a8d39ef77164bc, 0xae5dff9c02033198},
+ {0xd98ddaee19068c76, 0x3badd624dd9b0958},
+ {0xafbd2350644eeacf, 0xe5d1929ef90898fb},
+ {0x8df5efabc5979c8f, 0xca8d3ffa1ef463c2},
+ {0xe55990879ddcaabd, 0xcc420a6a101d0516},
+ {0xb94470938fa89bce, 0xf808e40e8d5b3e6a},
+ {0x95a8637627989aad, 0xdde7001379a44aa9},
+ {0xf1c90080baf72cb1, 0x5324c68b12dd6339},
+ {0xc350000000000000, 0x0000000000000000},
+ {0x9dc5ada82b70b59d, 0xf020000000000000},
+ {0xfee50b7025c36a08, 0x02f236d04753d5b4},
+ {0xcde6fd5e09abcf26, 0xed4c0226b55e6f86},
+ {0xa6539930bf6bff45, 0x84db8346b786151c},
+ {0x865b86925b9bc5c2, 0x0b8a2392ba45a9b2},
+ {0xd910f7ff28069da4, 0x1b2ba1518094da04},
+ {0xaf58416654a6babb, 0x387ac8d1970027b2},
+ {0x8da471a9de737e24, 0x5ceaecfed289e5d2},
+ {0xe4d5e82392a40515, 0x0fabaf3feaa5334a},
+ {0xb8da1662e7b00a17, 0x3d6a751f3b936243},
+ {0x95527a5202df0ccb, 0x0f37801e0c43ebc8}
+#endif
+};
+
+#if !FMT_USE_FULL_CACHE_DRAGONBOX
+template <typename T>
+const uint64_t basic_data<T>::powers_of_5_64[] = {
+ 0x0000000000000001, 0x0000000000000005, 0x0000000000000019,
+ 0x000000000000007d, 0x0000000000000271, 0x0000000000000c35,
+ 0x0000000000003d09, 0x000000000001312d, 0x000000000005f5e1,
+ 0x00000000001dcd65, 0x00000000009502f9, 0x0000000002e90edd,
+ 0x000000000e8d4a51, 0x0000000048c27395, 0x000000016bcc41e9,
+ 0x000000071afd498d, 0x0000002386f26fc1, 0x000000b1a2bc2ec5,
+ 0x000003782dace9d9, 0x00001158e460913d, 0x000056bc75e2d631,
+ 0x0001b1ae4d6e2ef5, 0x000878678326eac9, 0x002a5a058fc295ed,
+ 0x00d3c21bcecceda1, 0x0422ca8b0a00a425, 0x14adf4b7320334b9};
+
+template <typename T>
+const uint32_t basic_data<T>::dragonbox_pow10_recovery_errors[] = {
+ 0x50001400, 0x54044100, 0x54014555, 0x55954415, 0x54115555, 0x00000001,
+ 0x50000000, 0x00104000, 0x54010004, 0x05004001, 0x55555544, 0x41545555,
+ 0x54040551, 0x15445545, 0x51555514, 0x10000015, 0x00101100, 0x01100015,
+ 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x04450514, 0x45414110,
+ 0x55555145, 0x50544050, 0x15040155, 0x11054140, 0x50111514, 0x11451454,
+ 0x00400541, 0x00000000, 0x55555450, 0x10056551, 0x10054011, 0x55551014,
+ 0x69514555, 0x05151109, 0x00155555};
+#endif
+
+template <typename T>
+const char basic_data<T>::foreground_color[] = "\x1b[38;2;";
+template <typename T>
+const char basic_data<T>::background_color[] = "\x1b[48;2;";
+template <typename T> const char basic_data<T>::reset_color[] = "\x1b[0m";
+template <typename T> const wchar_t basic_data<T>::wreset_color[] = L"\x1b[0m";
+template <typename T> const char basic_data<T>::signs[] = {0, '-', '+', ' '};
+template <typename T>
+const char basic_data<T>::left_padding_shifts[] = {31, 31, 0, 1, 0};
+template <typename T>
+const char basic_data<T>::right_padding_shifts[] = {0, 31, 0, 1, 0};
+
+template <typename T> struct bits {
+ static FMT_CONSTEXPR_DECL const int value =
+ static_cast<int>(sizeof(T) * std::numeric_limits<unsigned char>::digits);
+};
+
+class fp;
+template <int SHIFT = 0> fp normalize(fp value);
+
+// Lower (upper) boundary is a value half way between a floating-point value
+// and its predecessor (successor). Boundaries have the same exponent as the
+// value so only significands are stored.
+struct boundaries {
+ uint64_t lower;
+ uint64_t upper;
+};
+
+// A handmade floating-point number f * pow(2, e).
+class fp {
+ private:
+ using significand_type = uint64_t;
+
+ template <typename Float>
+ using is_supported_float = bool_constant<sizeof(Float) == sizeof(uint64_t) ||
+ sizeof(Float) == sizeof(uint32_t)>;
+
+ public:
+ significand_type f;
+ int e;
+
+ // All sizes are in bits.
+ // Subtract 1 to account for an implicit most significant bit in the
+ // normalized form.
+ static FMT_CONSTEXPR_DECL const int double_significand_size =
+ std::numeric_limits<double>::digits - 1;
+ static FMT_CONSTEXPR_DECL const uint64_t implicit_bit =
+ 1ULL << double_significand_size;
+ static FMT_CONSTEXPR_DECL const int significand_size =
+ bits<significand_type>::value;
+
+ fp() : f(0), e(0) {}
+ fp(uint64_t f_val, int e_val) : f(f_val), e(e_val) {}
+
+ // Constructs fp from an IEEE754 double. It is a template to prevent compile
+ // errors on platforms where double is not IEEE754.
+ template <typename Double> explicit fp(Double d) { assign(d); }
+
+ // Assigns d to this and return true iff predecessor is closer than successor.
+ template <typename Float, FMT_ENABLE_IF(is_supported_float<Float>::value)>
+ bool assign(Float d) {
+ // Assume float is in the format [sign][exponent][significand].
+ using limits = std::numeric_limits<Float>;
+ const int float_significand_size = limits::digits - 1;
+ const int exponent_size =
+ bits<Float>::value - float_significand_size - 1; // -1 for sign
+ const uint64_t float_implicit_bit = 1ULL << float_significand_size;
+ const uint64_t significand_mask = float_implicit_bit - 1;
+ const uint64_t exponent_mask = (~0ULL >> 1) & ~significand_mask;
+ const int exponent_bias = (1 << exponent_size) - limits::max_exponent - 1;
+ constexpr bool is_double = sizeof(Float) == sizeof(uint64_t);
+ auto u = bit_cast<conditional_t<is_double, uint64_t, uint32_t>>(d);
+ f = u & significand_mask;
+ int biased_e =
+ static_cast<int>((u & exponent_mask) >> float_significand_size);
+ // Predecessor is closer if d is a normalized power of 2 (f == 0) other than
+ // the smallest normalized number (biased_e > 1).
+ bool is_predecessor_closer = f == 0 && biased_e > 1;
+ if (biased_e != 0)
+ f += float_implicit_bit;
+ else
+ biased_e = 1; // Subnormals use biased exponent 1 (min exponent).
+ e = biased_e - exponent_bias - float_significand_size;
+ return is_predecessor_closer;
+ }
+
+ template <typename Float, FMT_ENABLE_IF(!is_supported_float<Float>::value)>
+ bool assign(Float) {
+ *this = fp();
+ return false;
+ }
+};
+
+// Normalizes the value converted from double and multiplied by (1 << SHIFT).
+template <int SHIFT> fp normalize(fp value) {
+ // Handle subnormals.
+ const auto shifted_implicit_bit = fp::implicit_bit << SHIFT;
+ while ((value.f & shifted_implicit_bit) == 0) {
+ value.f <<= 1;
+ --value.e;
+ }
+ // Subtract 1 to account for hidden bit.
+ const auto offset =
+ fp::significand_size - fp::double_significand_size - SHIFT - 1;
+ value.f <<= offset;
+ value.e -= offset;
+ return value;
+}
+
+inline bool operator==(fp x, fp y) { return x.f == y.f && x.e == y.e; }
+
+// Computes lhs * rhs / pow(2, 64) rounded to nearest with half-up tie breaking.
+inline uint64_t multiply(uint64_t lhs, uint64_t rhs) {
+#if FMT_USE_INT128
+ auto product = static_cast<__uint128_t>(lhs) * rhs;
+ auto f = static_cast<uint64_t>(product >> 64);
+ return (static_cast<uint64_t>(product) & (1ULL << 63)) != 0 ? f + 1 : f;
+#else
+ // Multiply 32-bit parts of significands.
+ uint64_t mask = (1ULL << 32) - 1;
+ uint64_t a = lhs >> 32, b = lhs & mask;
+ uint64_t c = rhs >> 32, d = rhs & mask;
+ uint64_t ac = a * c, bc = b * c, ad = a * d, bd = b * d;
+ // Compute mid 64-bit of result and round.
+ uint64_t mid = (bd >> 32) + (ad & mask) + (bc & mask) + (1U << 31);
+ return ac + (ad >> 32) + (bc >> 32) + (mid >> 32);
+#endif
+}
+
+inline fp operator*(fp x, fp y) { return {multiply(x.f, y.f), x.e + y.e + 64}; }
+
+// Returns a cached power of 10 `c_k = c_k.f * pow(2, c_k.e)` such that its
+// (binary) exponent satisfies `min_exponent <= c_k.e <= min_exponent + 28`.
+inline fp get_cached_power(int min_exponent, int& pow10_exponent) {
+ const int shift = 32;
+ const auto significand = static_cast<int64_t>(data::log10_2_significand);
+ int index = static_cast<int>(
+ ((min_exponent + fp::significand_size - 1) * (significand >> shift) +
+ ((int64_t(1) << shift) - 1)) // ceil
+ >> 32 // arithmetic shift
+ );
+ // Decimal exponent of the first (smallest) cached power of 10.
+ const int first_dec_exp = -348;
+ // Difference between 2 consecutive decimal exponents in cached powers of 10.
+ const int dec_exp_step = 8;
+ index = (index - first_dec_exp - 1) / dec_exp_step + 1;
+ pow10_exponent = first_dec_exp + index * dec_exp_step;
+ return {data::grisu_pow10_significands[index],
+ data::grisu_pow10_exponents[index]};
+}
+
+// A simple accumulator to hold the sums of terms in bigint::square if uint128_t
+// is not available.
+struct accumulator {
+ uint64_t lower;
+ uint64_t upper;
+
+ accumulator() : lower(0), upper(0) {}
+ explicit operator uint32_t() const { return static_cast<uint32_t>(lower); }
+
+ void operator+=(uint64_t n) {
+ lower += n;
+ if (lower < n) ++upper;
+ }
+ void operator>>=(int shift) {
+ assert(shift == 32);
+ (void)shift;
+ lower = (upper << 32) | (lower >> 32);
+ upper >>= 32;
+ }
+};
+
+class bigint {
+ private:
+ // A bigint is stored as an array of bigits (big digits), with bigit at index
+ // 0 being the least significant one.
+ using bigit = uint32_t;
+ using double_bigit = uint64_t;
+ enum { bigits_capacity = 32 };
+ basic_memory_buffer<bigit, bigits_capacity> bigits_;
+ int exp_;
+
+ bigit operator[](int index) const { return bigits_[to_unsigned(index)]; }
+ bigit& operator[](int index) { return bigits_[to_unsigned(index)]; }
+
+ static FMT_CONSTEXPR_DECL const int bigit_bits = bits<bigit>::value;
+
+ friend struct formatter<bigint>;
+
+ void subtract_bigits(int index, bigit other, bigit& borrow) {
+ auto result = static_cast<double_bigit>((*this)[index]) - other - borrow;
+ (*this)[index] = static_cast<bigit>(result);
+ borrow = static_cast<bigit>(result >> (bigit_bits * 2 - 1));
+ }
+
+ void remove_leading_zeros() {
+ int num_bigits = static_cast<int>(bigits_.size()) - 1;
+ while (num_bigits > 0 && (*this)[num_bigits] == 0) --num_bigits;
+ bigits_.resize(to_unsigned(num_bigits + 1));
+ }
+
+ // Computes *this -= other assuming aligned bigints and *this >= other.
+ void subtract_aligned(const bigint& other) {
+ FMT_ASSERT(other.exp_ >= exp_, "unaligned bigints");
+ FMT_ASSERT(compare(*this, other) >= 0, "");
+ bigit borrow = 0;
+ int i = other.exp_ - exp_;
+ for (size_t j = 0, n = other.bigits_.size(); j != n; ++i, ++j)
+ subtract_bigits(i, other.bigits_[j], borrow);
+ while (borrow > 0) subtract_bigits(i, 0, borrow);
+ remove_leading_zeros();
+ }
+
+ void multiply(uint32_t value) {
+ const double_bigit wide_value = value;
+ bigit carry = 0;
+ for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+ double_bigit result = bigits_[i] * wide_value + carry;
+ bigits_[i] = static_cast<bigit>(result);
+ carry = static_cast<bigit>(result >> bigit_bits);
+ }
+ if (carry != 0) bigits_.push_back(carry);
+ }
+
+ void multiply(uint64_t value) {
+ const bigit mask = ~bigit(0);
+ const double_bigit lower = value & mask;
+ const double_bigit upper = value >> bigit_bits;
+ double_bigit carry = 0;
+ for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+ double_bigit result = bigits_[i] * lower + (carry & mask);
+ carry =
+ bigits_[i] * upper + (result >> bigit_bits) + (carry >> bigit_bits);
+ bigits_[i] = static_cast<bigit>(result);
+ }
+ while (carry != 0) {
+ bigits_.push_back(carry & mask);
+ carry >>= bigit_bits;
+ }
+ }
+
+ public:
+ bigint() : exp_(0) {}
+ explicit bigint(uint64_t n) { assign(n); }
+ ~bigint() { assert(bigits_.capacity() <= bigits_capacity); }
+
+ bigint(const bigint&) = delete;
+ void operator=(const bigint&) = delete;
+
+ void assign(const bigint& other) {
+ auto size = other.bigits_.size();
+ bigits_.resize(size);
+ auto data = other.bigits_.data();
+ std::copy(data, data + size, make_checked(bigits_.data(), size));
+ exp_ = other.exp_;
+ }
+
+ void assign(uint64_t n) {
+ size_t num_bigits = 0;
+ do {
+ bigits_[num_bigits++] = n & ~bigit(0);
+ n >>= bigit_bits;
+ } while (n != 0);
+ bigits_.resize(num_bigits);
+ exp_ = 0;
+ }
+
+ int num_bigits() const { return static_cast<int>(bigits_.size()) + exp_; }
+
+ FMT_NOINLINE bigint& operator<<=(int shift) {
+ assert(shift >= 0);
+ exp_ += shift / bigit_bits;
+ shift %= bigit_bits;
+ if (shift == 0) return *this;
+ bigit carry = 0;
+ for (size_t i = 0, n = bigits_.size(); i < n; ++i) {
+ bigit c = bigits_[i] >> (bigit_bits - shift);
+ bigits_[i] = (bigits_[i] << shift) + carry;
+ carry = c;
+ }
+ if (carry != 0) bigits_.push_back(carry);
+ return *this;
+ }
+
+ template <typename Int> bigint& operator*=(Int value) {
+ FMT_ASSERT(value > 0, "");
+ multiply(uint32_or_64_or_128_t<Int>(value));
+ return *this;
+ }
+
+ friend int compare(const bigint& lhs, const bigint& rhs) {
+ int num_lhs_bigits = lhs.num_bigits(), num_rhs_bigits = rhs.num_bigits();
+ if (num_lhs_bigits != num_rhs_bigits)
+ return num_lhs_bigits > num_rhs_bigits ? 1 : -1;
+ int i = static_cast<int>(lhs.bigits_.size()) - 1;
+ int j = static_cast<int>(rhs.bigits_.size()) - 1;
+ int end = i - j;
+ if (end < 0) end = 0;
+ for (; i >= end; --i, --j) {
+ bigit lhs_bigit = lhs[i], rhs_bigit = rhs[j];
+ if (lhs_bigit != rhs_bigit) return lhs_bigit > rhs_bigit ? 1 : -1;
+ }
+ if (i != j) return i > j ? 1 : -1;
+ return 0;
+ }
+
+ // Returns compare(lhs1 + lhs2, rhs).
+ friend int add_compare(const bigint& lhs1, const bigint& lhs2,
+ const bigint& rhs) {
+ int max_lhs_bigits = (std::max)(lhs1.num_bigits(), lhs2.num_bigits());
+ int num_rhs_bigits = rhs.num_bigits();
+ if (max_lhs_bigits + 1 < num_rhs_bigits) return -1;
+ if (max_lhs_bigits > num_rhs_bigits) return 1;
+ auto get_bigit = [](const bigint& n, int i) -> bigit {
+ return i >= n.exp_ && i < n.num_bigits() ? n[i - n.exp_] : 0;
+ };
+ double_bigit borrow = 0;
+ int min_exp = (std::min)((std::min)(lhs1.exp_, lhs2.exp_), rhs.exp_);
+ for (int i = num_rhs_bigits - 1; i >= min_exp; --i) {
+ double_bigit sum =
+ static_cast<double_bigit>(get_bigit(lhs1, i)) + get_bigit(lhs2, i);
+ bigit rhs_bigit = get_bigit(rhs, i);
+ if (sum > rhs_bigit + borrow) return 1;
+ borrow = rhs_bigit + borrow - sum;
+ if (borrow > 1) return -1;
+ borrow <<= bigit_bits;
+ }
+ return borrow != 0 ? -1 : 0;
+ }
+
+ // Assigns pow(10, exp) to this bigint.
+ void assign_pow10(int exp) {
+ assert(exp >= 0);
+ if (exp == 0) return assign(1);
+ // Find the top bit.
+ int bitmask = 1;
+ while (exp >= bitmask) bitmask <<= 1;
+ bitmask >>= 1;
+ // pow(10, exp) = pow(5, exp) * pow(2, exp). First compute pow(5, exp) by
+ // repeated squaring and multiplication.
+ assign(5);
+ bitmask >>= 1;
+ while (bitmask != 0) {
+ square();
+ if ((exp & bitmask) != 0) *this *= 5;
+ bitmask >>= 1;
+ }
+ *this <<= exp; // Multiply by pow(2, exp) by shifting.
+ }
+
+ void square() {
+ basic_memory_buffer<bigit, bigits_capacity> n(std::move(bigits_));
+ int num_bigits = static_cast<int>(bigits_.size());
+ int num_result_bigits = 2 * num_bigits;
+ bigits_.resize(to_unsigned(num_result_bigits));
+ using accumulator_t = conditional_t<FMT_USE_INT128, uint128_t, accumulator>;
+ auto sum = accumulator_t();
+ for (int bigit_index = 0; bigit_index < num_bigits; ++bigit_index) {
+ // Compute bigit at position bigit_index of the result by adding
+ // cross-product terms n[i] * n[j] such that i + j == bigit_index.
+ for (int i = 0, j = bigit_index; j >= 0; ++i, --j) {
+ // Most terms are multiplied twice which can be optimized in the future.
+ sum += static_cast<double_bigit>(n[i]) * n[j];
+ }
+ (*this)[bigit_index] = static_cast<bigit>(sum);
+ sum >>= bits<bigit>::value; // Compute the carry.
+ }
+ // Do the same for the top half.
+ for (int bigit_index = num_bigits; bigit_index < num_result_bigits;
+ ++bigit_index) {
+ for (int j = num_bigits - 1, i = bigit_index - j; i < num_bigits;)
+ sum += static_cast<double_bigit>(n[i++]) * n[j--];
+ (*this)[bigit_index] = static_cast<bigit>(sum);
+ sum >>= bits<bigit>::value;
+ }
+ --num_result_bigits;
+ remove_leading_zeros();
+ exp_ *= 2;
+ }
+
+ // If this bigint has a bigger exponent than other, adds trailing zero to make
+ // exponents equal. This simplifies some operations such as subtraction.
+ void align(const bigint& other) {
+ int exp_difference = exp_ - other.exp_;
+ if (exp_difference <= 0) return;
+ int num_bigits = static_cast<int>(bigits_.size());
+ bigits_.resize(to_unsigned(num_bigits + exp_difference));
+ for (int i = num_bigits - 1, j = i + exp_difference; i >= 0; --i, --j)
+ bigits_[j] = bigits_[i];
+ std::uninitialized_fill_n(bigits_.data(), exp_difference, 0);
+ exp_ -= exp_difference;
+ }
+
+ // Divides this bignum by divisor, assigning the remainder to this and
+ // returning the quotient.
+ int divmod_assign(const bigint& divisor) {
+ FMT_ASSERT(this != &divisor, "");
+ if (compare(*this, divisor) < 0) return 0;
+ FMT_ASSERT(divisor.bigits_[divisor.bigits_.size() - 1u] != 0, "");
+ align(divisor);
+ int quotient = 0;
+ do {
+ subtract_aligned(divisor);
+ ++quotient;
+ } while (compare(*this, divisor) >= 0);
+ return quotient;
+ }
+};
+
+enum class round_direction { unknown, up, down };
+
+// Given the divisor (normally a power of 10), the remainder = v % divisor for
+// some number v and the error, returns whether v should be rounded up, down, or
+// whether the rounding direction can't be determined due to error.
+// error should be less than divisor / 2.
+inline round_direction get_round_direction(uint64_t divisor, uint64_t remainder,
+ uint64_t error) {
+ FMT_ASSERT(remainder < divisor, ""); // divisor - remainder won't overflow.
+ FMT_ASSERT(error < divisor, ""); // divisor - error won't overflow.
+ FMT_ASSERT(error < divisor - error, ""); // error * 2 won't overflow.
+ // Round down if (remainder + error) * 2 <= divisor.
+ if (remainder <= divisor - remainder && error * 2 <= divisor - remainder * 2)
+ return round_direction::down;
+ // Round up if (remainder - error) * 2 >= divisor.
+ if (remainder >= error &&
+ remainder - error >= divisor - (remainder - error)) {
+ return round_direction::up;
+ }
+ return round_direction::unknown;
+}
+
+namespace digits {
+enum result {
+ more, // Generate more digits.
+ done, // Done generating digits.
+ error // Digit generation cancelled due to an error.
+};
+}
+
+// Generates output using the Grisu digit-gen algorithm.
+// error: the size of the region (lower, upper) outside of which numbers
+// definitely do not round to value (Delta in Grisu3).
+template <typename Handler>
+FMT_ALWAYS_INLINE digits::result grisu_gen_digits(fp value, uint64_t error,
+ int& exp, Handler& handler) {
+ const fp one(1ULL << -value.e, value.e);
+ // The integral part of scaled value (p1 in Grisu) = value / one. It cannot be
+ // zero because it contains a product of two 64-bit numbers with MSB set (due
+ // to normalization) - 1, shifted right by at most 60 bits.
+ auto integral = static_cast<uint32_t>(value.f >> -one.e);
+ FMT_ASSERT(integral != 0, "");
+ FMT_ASSERT(integral == value.f >> -one.e, "");
+ // The fractional part of scaled value (p2 in Grisu) c = value % one.
+ uint64_t fractional = value.f & (one.f - 1);
+ exp = count_digits(integral); // kappa in Grisu.
+ // Divide by 10 to prevent overflow.
+ auto result = handler.on_start(data::powers_of_10_64[exp - 1] << -one.e,
+ value.f / 10, error * 10, exp);
+ if (result != digits::more) return result;
+ // Generate digits for the integral part. This can produce up to 10 digits.
+ do {
+ uint32_t digit = 0;
+ auto divmod_integral = [&](uint32_t divisor) {
+ digit = integral / divisor;
+ integral %= divisor;
+ };
+ // This optimization by Milo Yip reduces the number of integer divisions by
+ // one per iteration.
+ switch (exp) {
+ case 10:
+ divmod_integral(1000000000);
+ break;
+ case 9:
+ divmod_integral(100000000);
+ break;
+ case 8:
+ divmod_integral(10000000);
+ break;
+ case 7:
+ divmod_integral(1000000);
+ break;
+ case 6:
+ divmod_integral(100000);
+ break;
+ case 5:
+ divmod_integral(10000);
+ break;
+ case 4:
+ divmod_integral(1000);
+ break;
+ case 3:
+ divmod_integral(100);
+ break;
+ case 2:
+ divmod_integral(10);
+ break;
+ case 1:
+ digit = integral;
+ integral = 0;
+ break;
+ default:
+ FMT_ASSERT(false, "invalid number of digits");
+ }
+ --exp;
+ auto remainder = (static_cast<uint64_t>(integral) << -one.e) + fractional;
+ result = handler.on_digit(static_cast<char>('0' + digit),
+ data::powers_of_10_64[exp] << -one.e, remainder,
+ error, exp, true);
+ if (result != digits::more) return result;
+ } while (exp > 0);
+ // Generate digits for the fractional part.
+ for (;;) {
+ fractional *= 10;
+ error *= 10;
+ char digit = static_cast<char>('0' + (fractional >> -one.e));
+ fractional &= one.f - 1;
+ --exp;
+ result = handler.on_digit(digit, one.f, fractional, error, exp, false);
+ if (result != digits::more) return result;
+ }
+}
+
+// The fixed precision digit handler.
+struct fixed_handler {
+ char* buf;
+ int size;
+ int precision;
+ int exp10;
+ bool fixed;
+
+ digits::result on_start(uint64_t divisor, uint64_t remainder, uint64_t error,
+ int& exp) {
+ // Non-fixed formats require at least one digit and no precision adjustment.
+ if (!fixed) return digits::more;
+ // Adjust fixed precision by exponent because it is relative to decimal
+ // point.
+ precision += exp + exp10;
+ // Check if precision is satisfied just by leading zeros, e.g.
+ // format("{:.2f}", 0.001) gives "0.00" without generating any digits.
+ if (precision > 0) return digits::more;
+ if (precision < 0) return digits::done;
+ auto dir = get_round_direction(divisor, remainder, error);
+ if (dir == round_direction::unknown) return digits::error;
+ buf[size++] = dir == round_direction::up ? '1' : '0';
+ return digits::done;
+ }
+
+ digits::result on_digit(char digit, uint64_t divisor, uint64_t remainder,
+ uint64_t error, int, bool integral) {
+ FMT_ASSERT(remainder < divisor, "");
+ buf[size++] = digit;
+ if (!integral && error >= remainder) return digits::error;
+ if (size < precision) return digits::more;
+ if (!integral) {
+ // Check if error * 2 < divisor with overflow prevention.
+ // The check is not needed for the integral part because error = 1
+ // and divisor > (1 << 32) there.
+ if (error >= divisor || error >= divisor - error) return digits::error;
+ } else {
+ FMT_ASSERT(error == 1 && divisor > 2, "");
+ }
+ auto dir = get_round_direction(divisor, remainder, error);
+ if (dir != round_direction::up)
+ return dir == round_direction::down ? digits::done : digits::error;
+ ++buf[size - 1];
+ for (int i = size - 1; i > 0 && buf[i] > '9'; --i) {
+ buf[i] = '0';
+ ++buf[i - 1];
+ }
+ if (buf[0] > '9') {
+ buf[0] = '1';
+ if (fixed)
+ buf[size++] = '0';
+ else
+ ++exp10;
+ }
+ return digits::done;
+ }
+};
+
+// Implementation of Dragonbox algorithm: https://github.com/jk-jeon/dragonbox.
+namespace dragonbox {
+// Computes 128-bit result of multiplication of two 64-bit unsigned integers.
+FMT_SAFEBUFFERS inline uint128_wrapper umul128(uint64_t x,
+ uint64_t y) FMT_NOEXCEPT {
+#if FMT_USE_INT128
+ return static_cast<uint128_t>(x) * static_cast<uint128_t>(y);
+#elif defined(_MSC_VER) && defined(_M_X64)
+ uint128_wrapper result;
+ result.low_ = _umul128(x, y, &result.high_);
+ return result;
+#else
+ const uint64_t mask = (uint64_t(1) << 32) - uint64_t(1);
+
+ uint64_t a = x >> 32;
+ uint64_t b = x & mask;
+ uint64_t c = y >> 32;
+ uint64_t d = y & mask;
+
+ uint64_t ac = a * c;
+ uint64_t bc = b * c;
+ uint64_t ad = a * d;
+ uint64_t bd = b * d;
+
+ uint64_t intermediate = (bd >> 32) + (ad & mask) + (bc & mask);
+
+ return {ac + (intermediate >> 32) + (ad >> 32) + (bc >> 32),
+ (intermediate << 32) + (bd & mask)};
+#endif
+}
+
+// Computes upper 64 bits of multiplication of two 64-bit unsigned integers.
+FMT_SAFEBUFFERS inline uint64_t umul128_upper64(uint64_t x,
+ uint64_t y) FMT_NOEXCEPT {
+#if FMT_USE_INT128
+ auto p = static_cast<uint128_t>(x) * static_cast<uint128_t>(y);
+ return static_cast<uint64_t>(p >> 64);
+#elif defined(_MSC_VER) && defined(_M_X64)
+ return __umulh(x, y);
+#else
+ return umul128(x, y).high();
+#endif
+}
+
+// Computes upper 64 bits of multiplication of a 64-bit unsigned integer and a
+// 128-bit unsigned integer.
+FMT_SAFEBUFFERS inline uint64_t umul192_upper64(uint64_t x, uint128_wrapper y)
+ FMT_NOEXCEPT {
+ uint128_wrapper g0 = umul128(x, y.high());
+ g0 += umul128_upper64(x, y.low());
+ return g0.high();
+}
+
+// Computes upper 32 bits of multiplication of a 32-bit unsigned integer and a
+// 64-bit unsigned integer.
+inline uint32_t umul96_upper32(uint32_t x, uint64_t y) FMT_NOEXCEPT {
+ return static_cast<uint32_t>(umul128_upper64(x, y));
+}
+
+// Computes middle 64 bits of multiplication of a 64-bit unsigned integer and a
+// 128-bit unsigned integer.
+FMT_SAFEBUFFERS inline uint64_t umul192_middle64(uint64_t x, uint128_wrapper y)
+ FMT_NOEXCEPT {
+ uint64_t g01 = x * y.high();
+ uint64_t g10 = umul128_upper64(x, y.low());
+ return g01 + g10;
+}
+
+// Computes lower 64 bits of multiplication of a 32-bit unsigned integer and a
+// 64-bit unsigned integer.
+inline uint64_t umul96_lower64(uint32_t x, uint64_t y) FMT_NOEXCEPT {
+ return x * y;
+}
+
+// Computes floor(log10(pow(2, e))) for e in [-1700, 1700] using the method from
+// https://fmt.dev/papers/Grisu-Exact.pdf#page=5, section 3.4.
+inline int floor_log10_pow2(int e) FMT_NOEXCEPT {
+ FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent");
+ const int shift = 22;
+ return (e * static_cast<int>(data::log10_2_significand >> (64 - shift))) >>
+ shift;
+}
+
+// Various fast log computations.
+inline int floor_log2_pow10(int e) FMT_NOEXCEPT {
+ FMT_ASSERT(e <= 1233 && e >= -1233, "too large exponent");
+ const uint64_t log2_10_integer_part = 3;
+ const uint64_t log2_10_fractional_digits = 0x5269e12f346e2bf9;
+ const int shift_amount = 19;
+ return (e * static_cast<int>(
+ (log2_10_integer_part << shift_amount) |
+ (log2_10_fractional_digits >> (64 - shift_amount)))) >>
+ shift_amount;
+}
+inline int floor_log10_pow2_minus_log10_4_over_3(int e) FMT_NOEXCEPT {
+ FMT_ASSERT(e <= 1700 && e >= -1700, "too large exponent");
+ const uint64_t log10_4_over_3_fractional_digits = 0x1ffbfc2bbc780375;
+ const int shift_amount = 22;
+ return (e * static_cast<int>(data::log10_2_significand >>
+ (64 - shift_amount)) -
+ static_cast<int>(log10_4_over_3_fractional_digits >>
+ (64 - shift_amount))) >>
+ shift_amount;
+}
+
+// Returns true iff x is divisible by pow(2, exp).
+inline bool divisible_by_power_of_2(uint32_t x, int exp) FMT_NOEXCEPT {
+ FMT_ASSERT(exp >= 1, "");
+ FMT_ASSERT(x != 0, "");
+#ifdef FMT_BUILTIN_CTZ
+ return FMT_BUILTIN_CTZ(x) >= exp;
+#else
+ return exp < num_bits<uint32_t>() && x == ((x >> exp) << exp);
+#endif
+}
+inline bool divisible_by_power_of_2(uint64_t x, int exp) FMT_NOEXCEPT {
+ FMT_ASSERT(exp >= 1, "");
+ FMT_ASSERT(x != 0, "");
+#ifdef FMT_BUILTIN_CTZLL
+ return FMT_BUILTIN_CTZLL(x) >= exp;
+#else
+ return exp < num_bits<uint64_t>() && x == ((x >> exp) << exp);
+#endif
+}
+
+// Returns true iff x is divisible by pow(5, exp).
+inline bool divisible_by_power_of_5(uint32_t x, int exp) FMT_NOEXCEPT {
+ FMT_ASSERT(exp <= 10, "too large exponent");
+ return x * data::divtest_table_for_pow5_32[exp].mod_inv <=
+ data::divtest_table_for_pow5_32[exp].max_quotient;
+}
+inline bool divisible_by_power_of_5(uint64_t x, int exp) FMT_NOEXCEPT {
+ FMT_ASSERT(exp <= 23, "too large exponent");
+ return x * data::divtest_table_for_pow5_64[exp].mod_inv <=
+ data::divtest_table_for_pow5_64[exp].max_quotient;
+}
+
+// Replaces n by floor(n / pow(5, N)) returning true if and only if n is
+// divisible by pow(5, N).
+// Precondition: n <= 2 * pow(5, N + 1).
+template <int N>
+bool check_divisibility_and_divide_by_pow5(uint32_t& n) FMT_NOEXCEPT {
+ static constexpr struct {
+ uint32_t magic_number;
+ int bits_for_comparison;
+ uint32_t threshold;
+ int shift_amount;
+ } infos[] = {{0xcccd, 16, 0x3333, 18}, {0xa429, 8, 0x0a, 20}};
+ constexpr auto info = infos[N - 1];
+ n *= info.magic_number;
+ const uint32_t comparison_mask = (1u << info.bits_for_comparison) - 1;
+ bool result = (n & comparison_mask) <= info.threshold;
+ n >>= info.shift_amount;
+ return result;
+}
+
+// Computes floor(n / pow(10, N)) for small n and N.
+// Precondition: n <= pow(10, N + 1).
+template <int N> uint32_t small_division_by_pow10(uint32_t n) FMT_NOEXCEPT {
+ static constexpr struct {
+ uint32_t magic_number;
+ int shift_amount;
+ uint32_t divisor_times_10;
+ } infos[] = {{0xcccd, 19, 100}, {0xa3d8, 22, 1000}};
+ constexpr auto info = infos[N - 1];
+ FMT_ASSERT(n <= info.divisor_times_10, "n is too large");
+ return n * info.magic_number >> info.shift_amount;
+}
+
+// Computes floor(n / 10^(kappa + 1)) (float)
+inline uint32_t divide_by_10_to_kappa_plus_1(uint32_t n) FMT_NOEXCEPT {
+ return n / float_info<float>::big_divisor;
+}
+// Computes floor(n / 10^(kappa + 1)) (double)
+inline uint64_t divide_by_10_to_kappa_plus_1(uint64_t n) FMT_NOEXCEPT {
+ return umul128_upper64(n, 0x83126e978d4fdf3c) >> 9;
+}
+
+// Various subroutines using pow10 cache
+template <class T> struct cache_accessor;
+
+template <> struct cache_accessor<float> {
+ using carrier_uint = float_info<float>::carrier_uint;
+ using cache_entry_type = uint64_t;
+
+ static uint64_t get_cached_power(int k) FMT_NOEXCEPT {
+ FMT_ASSERT(k >= float_info<float>::min_k && k <= float_info<float>::max_k,
+ "k is out of range");
+ return data::dragonbox_pow10_significands_64[k - float_info<float>::min_k];
+ }
+
+ static carrier_uint compute_mul(carrier_uint u,
+ const cache_entry_type& cache) FMT_NOEXCEPT {
+ return umul96_upper32(u, cache);
+ }
+
+ static uint32_t compute_delta(const cache_entry_type& cache,
+ int beta_minus_1) FMT_NOEXCEPT {
+ return static_cast<uint32_t>(cache >> (64 - 1 - beta_minus_1));
+ }
+
+ static bool compute_mul_parity(carrier_uint two_f,
+ const cache_entry_type& cache,
+ int beta_minus_1) FMT_NOEXCEPT {
+ FMT_ASSERT(beta_minus_1 >= 1, "");
+ FMT_ASSERT(beta_minus_1 < 64, "");
+
+ return ((umul96_lower64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0;
+ }
+
+ static carrier_uint compute_left_endpoint_for_shorter_interval_case(
+ const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+ return static_cast<carrier_uint>(
+ (cache - (cache >> (float_info<float>::significand_bits + 2))) >>
+ (64 - float_info<float>::significand_bits - 1 - beta_minus_1));
+ }
+
+ static carrier_uint compute_right_endpoint_for_shorter_interval_case(
+ const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+ return static_cast<carrier_uint>(
+ (cache + (cache >> (float_info<float>::significand_bits + 1))) >>
+ (64 - float_info<float>::significand_bits - 1 - beta_minus_1));
+ }
+
+ static carrier_uint compute_round_up_for_shorter_interval_case(
+ const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+ return (static_cast<carrier_uint>(
+ cache >>
+ (64 - float_info<float>::significand_bits - 2 - beta_minus_1)) +
+ 1) /
+ 2;
+ }
+};
+
+template <> struct cache_accessor<double> {
+ using carrier_uint = float_info<double>::carrier_uint;
+ using cache_entry_type = uint128_wrapper;
+
+ static uint128_wrapper get_cached_power(int k) FMT_NOEXCEPT {
+ FMT_ASSERT(k >= float_info<double>::min_k && k <= float_info<double>::max_k,
+ "k is out of range");
+
+#if FMT_USE_FULL_CACHE_DRAGONBOX
+ return data::dragonbox_pow10_significands_128[k -
+ float_info<double>::min_k];
+#else
+ static const int compression_ratio = 27;
+
+ // Compute base index.
+ int cache_index = (k - float_info<double>::min_k) / compression_ratio;
+ int kb = cache_index * compression_ratio + float_info<double>::min_k;
+ int offset = k - kb;
+
+ // Get base cache.
+ uint128_wrapper base_cache =
+ data::dragonbox_pow10_significands_128[cache_index];
+ if (offset == 0) return base_cache;
+
+ // Compute the required amount of bit-shift.
+ int alpha = floor_log2_pow10(kb + offset) - floor_log2_pow10(kb) - offset;
+ FMT_ASSERT(alpha > 0 && alpha < 64, "shifting error detected");
+
+ // Try to recover the real cache.
+ uint64_t pow5 = data::powers_of_5_64[offset];
+ uint128_wrapper recovered_cache = umul128(base_cache.high(), pow5);
+ uint128_wrapper middle_low =
+ umul128(base_cache.low() - (kb < 0 ? 1u : 0u), pow5);
+
+ recovered_cache += middle_low.high();
+
+ uint64_t high_to_middle = recovered_cache.high() << (64 - alpha);
+ uint64_t middle_to_low = recovered_cache.low() << (64 - alpha);
+
+ recovered_cache =
+ uint128_wrapper{(recovered_cache.low() >> alpha) | high_to_middle,
+ ((middle_low.low() >> alpha) | middle_to_low)};
+
+ if (kb < 0) recovered_cache += 1;
+
+ // Get error.
+ int error_idx = (k - float_info<double>::min_k) / 16;
+ uint32_t error = (data::dragonbox_pow10_recovery_errors[error_idx] >>
+ ((k - float_info<double>::min_k) % 16) * 2) &
+ 0x3;
+
+ // Add the error back.
+ FMT_ASSERT(recovered_cache.low() + error >= recovered_cache.low(), "");
+ return {recovered_cache.high(), recovered_cache.low() + error};
+#endif
+ }
+
+ static carrier_uint compute_mul(carrier_uint u,
+ const cache_entry_type& cache) FMT_NOEXCEPT {
+ return umul192_upper64(u, cache);
+ }
+
+ static uint32_t compute_delta(cache_entry_type const& cache,
+ int beta_minus_1) FMT_NOEXCEPT {
+ return static_cast<uint32_t>(cache.high() >> (64 - 1 - beta_minus_1));
+ }
+
+ static bool compute_mul_parity(carrier_uint two_f,
+ const cache_entry_type& cache,
+ int beta_minus_1) FMT_NOEXCEPT {
+ FMT_ASSERT(beta_minus_1 >= 1, "");
+ FMT_ASSERT(beta_minus_1 < 64, "");
+
+ return ((umul192_middle64(two_f, cache) >> (64 - beta_minus_1)) & 1) != 0;
+ }
+
+ static carrier_uint compute_left_endpoint_for_shorter_interval_case(
+ const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+ return (cache.high() -
+ (cache.high() >> (float_info<double>::significand_bits + 2))) >>
+ (64 - float_info<double>::significand_bits - 1 - beta_minus_1);
+ }
+
+ static carrier_uint compute_right_endpoint_for_shorter_interval_case(
+ const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+ return (cache.high() +
+ (cache.high() >> (float_info<double>::significand_bits + 1))) >>
+ (64 - float_info<double>::significand_bits - 1 - beta_minus_1);
+ }
+
+ static carrier_uint compute_round_up_for_shorter_interval_case(
+ const cache_entry_type& cache, int beta_minus_1) FMT_NOEXCEPT {
+ return ((cache.high() >>
+ (64 - float_info<double>::significand_bits - 2 - beta_minus_1)) +
+ 1) /
+ 2;
+ }
+};
+
+// Various integer checks
+template <class T>
+bool is_left_endpoint_integer_shorter_interval(int exponent) FMT_NOEXCEPT {
+ return exponent >=
+ float_info<
+ T>::case_shorter_interval_left_endpoint_lower_threshold &&
+ exponent <=
+ float_info<T>::case_shorter_interval_left_endpoint_upper_threshold;
+}
+template <class T>
+bool is_endpoint_integer(typename float_info<T>::carrier_uint two_f,
+ int exponent, int minus_k) FMT_NOEXCEPT {
+ if (exponent < float_info<T>::case_fc_pm_half_lower_threshold) return false;
+ // For k >= 0.
+ if (exponent <= float_info<T>::case_fc_pm_half_upper_threshold) return true;
+ // For k < 0.
+ if (exponent > float_info<T>::divisibility_check_by_5_threshold) return false;
+ return divisible_by_power_of_5(two_f, minus_k);
+}
+
+template <class T>
+bool is_center_integer(typename float_info<T>::carrier_uint two_f, int exponent,
+ int minus_k) FMT_NOEXCEPT {
+ // Exponent for 5 is negative.
+ if (exponent > float_info<T>::divisibility_check_by_5_threshold) return false;
+ if (exponent > float_info<T>::case_fc_upper_threshold)
+ return divisible_by_power_of_5(two_f, minus_k);
+ // Both exponents are nonnegative.
+ if (exponent >= float_info<T>::case_fc_lower_threshold) return true;
+ // Exponent for 2 is negative.
+ return divisible_by_power_of_2(two_f, minus_k - exponent + 1);
+}
+
+// Remove trailing zeros from n and return the number of zeros removed (float)
+FMT_ALWAYS_INLINE int remove_trailing_zeros(uint32_t& n) FMT_NOEXCEPT {
+#ifdef FMT_BUILTIN_CTZ
+ int t = FMT_BUILTIN_CTZ(n);
+#else
+ int t = ctz(n);
+#endif
+ if (t > float_info<float>::max_trailing_zeros)
+ t = float_info<float>::max_trailing_zeros;
+
+ const uint32_t mod_inv1 = 0xcccccccd;
+ const uint32_t max_quotient1 = 0x33333333;
+ const uint32_t mod_inv2 = 0xc28f5c29;
+ const uint32_t max_quotient2 = 0x0a3d70a3;
+
+ int s = 0;
+ for (; s < t - 1; s += 2) {
+ if (n * mod_inv2 > max_quotient2) break;
+ n *= mod_inv2;
+ }
+ if (s < t && n * mod_inv1 <= max_quotient1) {
+ n *= mod_inv1;
+ ++s;
+ }
+ n >>= s;
+ return s;
+}
+
+// Removes trailing zeros and returns the number of zeros removed (double)
+FMT_ALWAYS_INLINE int remove_trailing_zeros(uint64_t& n) FMT_NOEXCEPT {
+#ifdef FMT_BUILTIN_CTZLL
+ int t = FMT_BUILTIN_CTZLL(n);
+#else
+ int t = ctzll(n);
+#endif
+ if (t > float_info<double>::max_trailing_zeros)
+ t = float_info<double>::max_trailing_zeros;
+ // Divide by 10^8 and reduce to 32-bits
+ // Since ret_value.significand <= (2^64 - 1) / 1000 < 10^17,
+ // both of the quotient and the r should fit in 32-bits
+
+ const uint32_t mod_inv1 = 0xcccccccd;
+ const uint32_t max_quotient1 = 0x33333333;
+ const uint64_t mod_inv8 = 0xc767074b22e90e21;
+ const uint64_t max_quotient8 = 0x00002af31dc46118;
+
+ // If the number is divisible by 1'0000'0000, work with the quotient
+ if (t >= 8) {
+ auto quotient_candidate = n * mod_inv8;
+
+ if (quotient_candidate <= max_quotient8) {
+ auto quotient = static_cast<uint32_t>(quotient_candidate >> 8);
+
+ int s = 8;
+ for (; s < t; ++s) {
+ if (quotient * mod_inv1 > max_quotient1) break;
+ quotient *= mod_inv1;
+ }
+ quotient >>= (s - 8);
+ n = quotient;
+ return s;
+ }
+ }
+
+ // Otherwise, work with the remainder
+ auto quotient = static_cast<uint32_t>(n / 100000000);
+ auto remainder = static_cast<uint32_t>(n - 100000000 * quotient);
+
+ if (t == 0 || remainder * mod_inv1 > max_quotient1) {
+ return 0;
+ }
+ remainder *= mod_inv1;
+
+ if (t == 1 || remainder * mod_inv1 > max_quotient1) {
+ n = (remainder >> 1) + quotient * 10000000ull;
+ return 1;
+ }
+ remainder *= mod_inv1;
+
+ if (t == 2 || remainder * mod_inv1 > max_quotient1) {
+ n = (remainder >> 2) + quotient * 1000000ull;
+ return 2;
+ }
+ remainder *= mod_inv1;
+
+ if (t == 3 || remainder * mod_inv1 > max_quotient1) {
+ n = (remainder >> 3) + quotient * 100000ull;
+ return 3;
+ }
+ remainder *= mod_inv1;
+
+ if (t == 4 || remainder * mod_inv1 > max_quotient1) {
+ n = (remainder >> 4) + quotient * 10000ull;
+ return 4;
+ }
+ remainder *= mod_inv1;
+
+ if (t == 5 || remainder * mod_inv1 > max_quotient1) {
+ n = (remainder >> 5) + quotient * 1000ull;
+ return 5;
+ }
+ remainder *= mod_inv1;
+
+ if (t == 6 || remainder * mod_inv1 > max_quotient1) {
+ n = (remainder >> 6) + quotient * 100ull;
+ return 6;
+ }
+ remainder *= mod_inv1;
+
+ n = (remainder >> 7) + quotient * 10ull;
+ return 7;
+}
+
+// The main algorithm for shorter interval case
+template <class T>
+FMT_ALWAYS_INLINE FMT_SAFEBUFFERS decimal_fp<T> shorter_interval_case(
+ int exponent) FMT_NOEXCEPT {
+ decimal_fp<T> ret_value;
+ // Compute k and beta
+ const int minus_k = floor_log10_pow2_minus_log10_4_over_3(exponent);
+ const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k);
+
+ // Compute xi and zi
+ using cache_entry_type = typename cache_accessor<T>::cache_entry_type;
+ const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
+
+ auto xi = cache_accessor<T>::compute_left_endpoint_for_shorter_interval_case(
+ cache, beta_minus_1);
+ auto zi = cache_accessor<T>::compute_right_endpoint_for_shorter_interval_case(
+ cache, beta_minus_1);
+
+ // If the left endpoint is not an integer, increase it
+ if (!is_left_endpoint_integer_shorter_interval<T>(exponent)) ++xi;
+
+ // Try bigger divisor
+ ret_value.significand = zi / 10;
+
+ // If succeed, remove trailing zeros if necessary and return
+ if (ret_value.significand * 10 >= xi) {
+ ret_value.exponent = minus_k + 1;
+ ret_value.exponent += remove_trailing_zeros(ret_value.significand);
+ return ret_value;
+ }
+
+ // Otherwise, compute the round-up of y
+ ret_value.significand =
+ cache_accessor<T>::compute_round_up_for_shorter_interval_case(
+ cache, beta_minus_1);
+ ret_value.exponent = minus_k;
+
+ // When tie occurs, choose one of them according to the rule
+ if (exponent >= float_info<T>::shorter_interval_tie_lower_threshold &&
+ exponent <= float_info<T>::shorter_interval_tie_upper_threshold) {
+ ret_value.significand = ret_value.significand % 2 == 0
+ ? ret_value.significand
+ : ret_value.significand - 1;
+ } else if (ret_value.significand < xi) {
+ ++ret_value.significand;
+ }
+ return ret_value;
+}
+
+template <typename T>
+FMT_SAFEBUFFERS decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT {
+ // Step 1: integer promotion & Schubfach multiplier calculation.
+
+ using carrier_uint = typename float_info<T>::carrier_uint;
+ using cache_entry_type = typename cache_accessor<T>::cache_entry_type;
+ auto br = bit_cast<carrier_uint>(x);
+
+ // Extract significand bits and exponent bits.
+ const carrier_uint significand_mask =
+ (static_cast<carrier_uint>(1) << float_info<T>::significand_bits) - 1;
+ carrier_uint significand = (br & significand_mask);
+ int exponent = static_cast<int>((br & exponent_mask<T>()) >>
+ float_info<T>::significand_bits);
+
+ if (exponent != 0) { // Check if normal.
+ exponent += float_info<T>::exponent_bias - float_info<T>::significand_bits;
+
+ // Shorter interval case; proceed like Schubfach.
+ if (significand == 0) return shorter_interval_case<T>(exponent);
+
+ significand |=
+ (static_cast<carrier_uint>(1) << float_info<T>::significand_bits);
+ } else {
+ // Subnormal case; the interval is always regular.
+ if (significand == 0) return {0, 0};
+ exponent = float_info<T>::min_exponent - float_info<T>::significand_bits;
+ }
+
+ const bool include_left_endpoint = (significand % 2 == 0);
+ const bool include_right_endpoint = include_left_endpoint;
+
+ // Compute k and beta.
+ const int minus_k = floor_log10_pow2(exponent) - float_info<T>::kappa;
+ const cache_entry_type cache = cache_accessor<T>::get_cached_power(-minus_k);
+ const int beta_minus_1 = exponent + floor_log2_pow10(-minus_k);
+
+ // Compute zi and deltai
+ // 10^kappa <= deltai < 10^(kappa + 1)
+ const uint32_t deltai = cache_accessor<T>::compute_delta(cache, beta_minus_1);
+ const carrier_uint two_fc = significand << 1;
+ const carrier_uint two_fr = two_fc | 1;
+ const carrier_uint zi =
+ cache_accessor<T>::compute_mul(two_fr << beta_minus_1, cache);
+
+ // Step 2: Try larger divisor; remove trailing zeros if necessary
+
+ // Using an upper bound on zi, we might be able to optimize the division
+ // better than the compiler; we are computing zi / big_divisor here
+ decimal_fp<T> ret_value;
+ ret_value.significand = divide_by_10_to_kappa_plus_1(zi);
+ uint32_t r = static_cast<uint32_t>(zi - float_info<T>::big_divisor *
+ ret_value.significand);
+
+ if (r > deltai) {
+ goto small_divisor_case_label;
+ } else if (r < deltai) {
+ // Exclude the right endpoint if necessary
+ if (r == 0 && !include_right_endpoint &&
+ is_endpoint_integer<T>(two_fr, exponent, minus_k)) {
+ --ret_value.significand;
+ r = float_info<T>::big_divisor;
+ goto small_divisor_case_label;
+ }
+ } else {
+ // r == deltai; compare fractional parts
+ // Check conditions in the order different from the paper
+ // to take advantage of short-circuiting
+ const carrier_uint two_fl = two_fc - 1;
+ if ((!include_left_endpoint ||
+ !is_endpoint_integer<T>(two_fl, exponent, minus_k)) &&
+ !cache_accessor<T>::compute_mul_parity(two_fl, cache, beta_minus_1)) {
+ goto small_divisor_case_label;
+ }
+ }
+ ret_value.exponent = minus_k + float_info<T>::kappa + 1;
+
+ // We may need to remove trailing zeros
+ ret_value.exponent += remove_trailing_zeros(ret_value.significand);
+ return ret_value;
+
+ // Step 3: Find the significand with the smaller divisor
+
+small_divisor_case_label:
+ ret_value.significand *= 10;
+ ret_value.exponent = minus_k + float_info<T>::kappa;
+
+ const uint32_t mask = (1u << float_info<T>::kappa) - 1;
+ auto dist = r - (deltai / 2) + (float_info<T>::small_divisor / 2);
+
+ // Is dist divisible by 2^kappa?
+ if ((dist & mask) == 0) {
+ const bool approx_y_parity =
+ ((dist ^ (float_info<T>::small_divisor / 2)) & 1) != 0;
+ dist >>= float_info<T>::kappa;
+
+ // Is dist divisible by 5^kappa?
+ if (check_divisibility_and_divide_by_pow5<float_info<T>::kappa>(dist)) {
+ ret_value.significand += dist;
+
+ // Check z^(f) >= epsilon^(f)
+ // We have either yi == zi - epsiloni or yi == (zi - epsiloni) - 1,
+ // where yi == zi - epsiloni if and only if z^(f) >= epsilon^(f)
+ // Since there are only 2 possibilities, we only need to care about the
+ // parity. Also, zi and r should have the same parity since the divisor
+ // is an even number
+ if (cache_accessor<T>::compute_mul_parity(two_fc, cache, beta_minus_1) !=
+ approx_y_parity) {
+ --ret_value.significand;
+ } else {
+ // If z^(f) >= epsilon^(f), we might have a tie
+ // when z^(f) == epsilon^(f), or equivalently, when y is an integer
+ if (is_center_integer<T>(two_fc, exponent, minus_k)) {
+ ret_value.significand = ret_value.significand % 2 == 0
+ ? ret_value.significand
+ : ret_value.significand - 1;
+ }
+ }
+ }
+ // Is dist not divisible by 5^kappa?
+ else {
+ ret_value.significand += dist;
+ }
+ }
+ // Is dist not divisible by 2^kappa?
+ else {
+ // Since we know dist is small, we might be able to optimize the division
+ // better than the compiler; we are computing dist / small_divisor here
+ ret_value.significand +=
+ small_division_by_pow10<float_info<T>::kappa>(dist);
+ }
+ return ret_value;
+}
+} // namespace dragonbox
+
+// Formats value using a variation of the Fixed-Precision Positive
+// Floating-Point Printout ((FPP)^2) algorithm by Steele & White:
+// https://fmt.dev/p372-steele.pdf.
+template <typename Double>
+void fallback_format(Double d, int num_digits, bool binary32, buffer<char>& buf,
+ int& exp10) {
+ bigint numerator; // 2 * R in (FPP)^2.
+ bigint denominator; // 2 * S in (FPP)^2.
+ // lower and upper are differences between value and corresponding boundaries.
+ bigint lower; // (M^- in (FPP)^2).
+ bigint upper_store; // upper's value if different from lower.
+ bigint* upper = nullptr; // (M^+ in (FPP)^2).
+ fp value;
+ // Shift numerator and denominator by an extra bit or two (if lower boundary
+ // is closer) to make lower and upper integers. This eliminates multiplication
+ // by 2 during later computations.
+ const bool is_predecessor_closer =
+ binary32 ? value.assign(static_cast<float>(d)) : value.assign(d);
+ int shift = is_predecessor_closer ? 2 : 1;
+ uint64_t significand = value.f << shift;
+ if (value.e >= 0) {
+ numerator.assign(significand);
+ numerator <<= value.e;
+ lower.assign(1);
+ lower <<= value.e;
+ if (shift != 1) {
+ upper_store.assign(1);
+ upper_store <<= value.e + 1;
+ upper = &upper_store;
+ }
+ denominator.assign_pow10(exp10);
+ denominator <<= shift;
+ } else if (exp10 < 0) {
+ numerator.assign_pow10(-exp10);
+ lower.assign(numerator);
+ if (shift != 1) {
+ upper_store.assign(numerator);
+ upper_store <<= 1;
+ upper = &upper_store;
+ }
+ numerator *= significand;
+ denominator.assign(1);
+ denominator <<= shift - value.e;
+ } else {
+ numerator.assign(significand);
+ denominator.assign_pow10(exp10);
+ denominator <<= shift - value.e;
+ lower.assign(1);
+ if (shift != 1) {
+ upper_store.assign(1ULL << 1);
+ upper = &upper_store;
+ }
+ }
+ // Invariant: value == (numerator / denominator) * pow(10, exp10).
+ if (num_digits < 0) {
+ // Generate the shortest representation.
+ if (!upper) upper = &lower;
+ bool even = (value.f & 1) == 0;
+ num_digits = 0;
+ char* data = buf.data();
+ for (;;) {
+ int digit = numerator.divmod_assign(denominator);
+ bool low = compare(numerator, lower) - even < 0; // numerator <[=] lower.
+ // numerator + upper >[=] pow10:
+ bool high = add_compare(numerator, *upper, denominator) + even > 0;
+ data[num_digits++] = static_cast<char>('0' + digit);
+ if (low || high) {
+ if (!low) {
+ ++data[num_digits - 1];
+ } else if (high) {
+ int result = add_compare(numerator, numerator, denominator);
+ // Round half to even.
+ if (result > 0 || (result == 0 && (digit % 2) != 0))
+ ++data[num_digits - 1];
+ }
+ buf.try_resize(to_unsigned(num_digits));
+ exp10 -= num_digits - 1;
+ return;
+ }
+ numerator *= 10;
+ lower *= 10;
+ if (upper != &lower) *upper *= 10;
+ }
+ }
+ // Generate the given number of digits.
+ exp10 -= num_digits - 1;
+ if (num_digits == 0) {
+ buf.try_resize(1);
+ denominator *= 10;
+ buf[0] = add_compare(numerator, numerator, denominator) > 0 ? '1' : '0';
+ return;
+ }
+ buf.try_resize(to_unsigned(num_digits));
+ for (int i = 0; i < num_digits - 1; ++i) {
+ int digit = numerator.divmod_assign(denominator);
+ buf[i] = static_cast<char>('0' + digit);
+ numerator *= 10;
+ }
+ int digit = numerator.divmod_assign(denominator);
+ auto result = add_compare(numerator, numerator, denominator);
+ if (result > 0 || (result == 0 && (digit % 2) != 0)) {
+ if (digit == 9) {
+ const auto overflow = '0' + 10;
+ buf[num_digits - 1] = overflow;
+ // Propagate the carry.
+ for (int i = num_digits - 1; i > 0 && buf[i] == overflow; --i) {
+ buf[i] = '0';
+ ++buf[i - 1];
+ }
+ if (buf[0] == overflow) {
+ buf[0] = '1';
+ ++exp10;
+ }
+ return;
+ }
+ ++digit;
+ }
+ buf[num_digits - 1] = static_cast<char>('0' + digit);
+}
+
+template <typename T>
+int format_float(T value, int precision, float_specs specs, buffer<char>& buf) {
+ static_assert(!std::is_same<T, float>::value, "");
+ FMT_ASSERT(value >= 0, "value is negative");
+
+ const bool fixed = specs.format == float_format::fixed;
+ if (value <= 0) { // <= instead of == to silence a warning.
+ if (precision <= 0 || !fixed) {
+ buf.push_back('0');
+ return 0;
+ }
+ buf.try_resize(to_unsigned(precision));
+ std::uninitialized_fill_n(buf.data(), precision, '0');
+ return -precision;
+ }
+
+ if (!specs.use_grisu) return snprintf_float(value, precision, specs, buf);
+
+ if (precision < 0) {
+ // Use Dragonbox for the shortest format.
+ if (specs.binary32) {
+ auto dec = dragonbox::to_decimal(static_cast<float>(value));
+ write<char>(buffer_appender<char>(buf), dec.significand);
+ return dec.exponent;
+ }
+ auto dec = dragonbox::to_decimal(static_cast<double>(value));
+ write<char>(buffer_appender<char>(buf), dec.significand);
+ return dec.exponent;
+ }
+
+ // Use Grisu + Dragon4 for the given precision:
+ // https://www.cs.tufts.edu/~nr/cs257/archive/florian-loitsch/printf.pdf.
+ int exp = 0;
+ const int min_exp = -60; // alpha in Grisu.
+ int cached_exp10 = 0; // K in Grisu.
+ fp normalized = normalize(fp(value));
+ const auto cached_pow = get_cached_power(
+ min_exp - (normalized.e + fp::significand_size), cached_exp10);
+ normalized = normalized * cached_pow;
+ // Limit precision to the maximum possible number of significant digits in an
+ // IEEE754 double because we don't need to generate zeros.
+ const int max_double_digits = 767;
+ if (precision > max_double_digits) precision = max_double_digits;
+ fixed_handler handler{buf.data(), 0, precision, -cached_exp10, fixed};
+ if (grisu_gen_digits(normalized, 1, exp, handler) == digits::error) {
+ exp += handler.size - cached_exp10 - 1;
+ fallback_format(value, handler.precision, specs.binary32, buf, exp);
+ } else {
+ exp += handler.exp10;
+ buf.try_resize(to_unsigned(handler.size));
+ }
+ if (!fixed && !specs.showpoint) {
+ // Remove trailing zeros.
+ auto num_digits = buf.size();
+ while (num_digits > 0 && buf[num_digits - 1] == '0') {
+ --num_digits;
+ ++exp;
+ }
+ buf.try_resize(num_digits);
+ }
+ return exp;
+} // namespace detail
+
+template <typename T>
+int snprintf_float(T value, int precision, float_specs specs,
+ buffer<char>& buf) {
+ // Buffer capacity must be non-zero, otherwise MSVC's vsnprintf_s will fail.
+ FMT_ASSERT(buf.capacity() > buf.size(), "empty buffer");
+ static_assert(!std::is_same<T, float>::value, "");
+
+ // Subtract 1 to account for the difference in precision since we use %e for
+ // both general and exponent format.
+ if (specs.format == float_format::general ||
+ specs.format == float_format::exp)
+ precision = (precision >= 0 ? precision : 6) - 1;
+
+ // Build the format string.
+ enum { max_format_size = 7 }; // The longest format is "%#.*Le".
+ char format[max_format_size];
+ char* format_ptr = format;
+ *format_ptr++ = '%';
+ if (specs.showpoint && specs.format == float_format::hex) *format_ptr++ = '#';
+ if (precision >= 0) {
+ *format_ptr++ = '.';
+ *format_ptr++ = '*';
+ }
+ if (std::is_same<T, long double>()) *format_ptr++ = 'L';
+ *format_ptr++ = specs.format != float_format::hex
+ ? (specs.format == float_format::fixed ? 'f' : 'e')
+ : (specs.upper ? 'A' : 'a');
+ *format_ptr = '\0';
+
+ // Format using snprintf.
+ auto offset = buf.size();
+ for (;;) {
+ auto begin = buf.data() + offset;
+ auto capacity = buf.capacity() - offset;
+#ifdef FMT_FUZZ
+ if (precision > 100000)
+ throw std::runtime_error(
+ "fuzz mode - avoid large allocation inside snprintf");
+#endif
+ // Suppress the warning about a nonliteral format string.
+ // Cannot use auto because of a bug in MinGW (#1532).
+ int (*snprintf_ptr)(char*, size_t, const char*, ...) = FMT_SNPRINTF;
+ int result = precision >= 0
+ ? snprintf_ptr(begin, capacity, format, precision, value)
+ : snprintf_ptr(begin, capacity, format, value);
+ if (result < 0) {
+ // The buffer will grow exponentially.
+ buf.try_reserve(buf.capacity() + 1);
+ continue;
+ }
+ auto size = to_unsigned(result);
+ // Size equal to capacity means that the last character was truncated.
+ if (size >= capacity) {
+ buf.try_reserve(size + offset + 1); // Add 1 for the terminating '\0'.
+ continue;
+ }
+ auto is_digit = [](char c) { return c >= '0' && c <= '9'; };
+ if (specs.format == float_format::fixed) {
+ if (precision == 0) {
+ buf.try_resize(size);
+ return 0;
+ }
+ // Find and remove the decimal point.
+ auto end = begin + size, p = end;
+ do {
+ --p;
+ } while (is_digit(*p));
+ int fraction_size = static_cast<int>(end - p - 1);
+ std::memmove(p, p + 1, to_unsigned(fraction_size));
+ buf.try_resize(size - 1);
+ return -fraction_size;
+ }
+ if (specs.format == float_format::hex) {
+ buf.try_resize(size + offset);
+ return 0;
+ }
+ // Find and parse the exponent.
+ auto end = begin + size, exp_pos = end;
+ do {
+ --exp_pos;
+ } while (*exp_pos != 'e');
+ char sign = exp_pos[1];
+ assert(sign == '+' || sign == '-');
+ int exp = 0;
+ auto p = exp_pos + 2; // Skip 'e' and sign.
+ do {
+ assert(is_digit(*p));
+ exp = exp * 10 + (*p++ - '0');
+ } while (p != end);
+ if (sign == '-') exp = -exp;
+ int fraction_size = 0;
+ if (exp_pos != begin + 1) {
+ // Remove trailing zeros.
+ auto fraction_end = exp_pos - 1;
+ while (*fraction_end == '0') --fraction_end;
+ // Move the fractional part left to get rid of the decimal point.
+ fraction_size = static_cast<int>(fraction_end - begin - 1);
+ std::memmove(begin + 1, begin + 2, to_unsigned(fraction_size));
+ }
+ buf.try_resize(to_unsigned(fraction_size) + offset + 1);
+ return exp - fraction_size;
+ }
+}
+
+// A public domain branchless UTF-8 decoder by Christopher Wellons:
+// https://github.com/skeeto/branchless-utf8
+/* Decode the next character, c, from buf, reporting errors in e.
+ *
+ * Since this is a branchless decoder, four bytes will be read from the
+ * buffer regardless of the actual length of the next character. This
+ * means the buffer _must_ have at least three bytes of zero padding
+ * following the end of the data stream.
+ *
+ * Errors are reported in e, which will be non-zero if the parsed
+ * character was somehow invalid: invalid byte sequence, non-canonical
+ * encoding, or a surrogate half.
+ *
+ * The function returns a pointer to the next character. When an error
+ * occurs, this pointer will be a guess that depends on the particular
+ * error, but it will always advance at least one byte.
+ */
+inline const char* utf8_decode(const char* buf, uint32_t* c, int* e) {
+ static const int masks[] = {0x00, 0x7f, 0x1f, 0x0f, 0x07};
+ static const uint32_t mins[] = {4194304, 0, 128, 2048, 65536};
+ static const int shiftc[] = {0, 18, 12, 6, 0};
+ static const int shifte[] = {0, 6, 4, 2, 0};
+
+ int len = code_point_length(buf);
+ const char* next = buf + len;
+
+ // Assume a four-byte character and load four bytes. Unused bits are
+ // shifted out.
+ auto s = reinterpret_cast<const unsigned char*>(buf);
+ *c = uint32_t(s[0] & masks[len]) << 18;
+ *c |= uint32_t(s[1] & 0x3f) << 12;
+ *c |= uint32_t(s[2] & 0x3f) << 6;
+ *c |= uint32_t(s[3] & 0x3f) << 0;
+ *c >>= shiftc[len];
+
+ // Accumulate the various error conditions.
+ *e = (*c < mins[len]) << 6; // non-canonical encoding
+ *e |= ((*c >> 11) == 0x1b) << 7; // surrogate half?
+ *e |= (*c > 0x10FFFF) << 8; // out of range?
+ *e |= (s[1] & 0xc0) >> 2;
+ *e |= (s[2] & 0xc0) >> 4;
+ *e |= (s[3]) >> 6;
+ *e ^= 0x2a; // top two bits of each tail byte correct?
+ *e >>= shifte[len];
+
+ return next;
+}
+
+struct stringifier {
+ template <typename T> FMT_INLINE std::string operator()(T value) const {
+ return to_string(value);
+ }
+ std::string operator()(basic_format_arg<format_context>::handle h) const {
+ memory_buffer buf;
+ format_parse_context parse_ctx({});
+ format_context format_ctx(buffer_appender<char>(buf), {}, {});
+ h.format(parse_ctx, format_ctx);
+ return to_string(buf);
+ }
+};
+} // namespace detail
+
+template <> struct formatter<detail::bigint> {
+ format_parse_context::iterator parse(format_parse_context& ctx) {
+ return ctx.begin();
+ }
+
+ format_context::iterator format(const detail::bigint& n,
+ format_context& ctx) {
+ auto out = ctx.out();
+ bool first = true;
+ for (auto i = n.bigits_.size(); i > 0; --i) {
+ auto value = n.bigits_[i - 1u];
+ if (first) {
+ out = format_to(out, "{:x}", value);
+ first = false;
+ continue;
+ }
+ out = format_to(out, "{:08x}", value);
+ }
+ if (n.exp_ > 0)
+ out = format_to(out, "p{}", n.exp_ * detail::bigint::bigit_bits);
+ return out;
+ }
+};
+
+FMT_FUNC detail::utf8_to_utf16::utf8_to_utf16(string_view s) {
+ auto transcode = [this](const char* p) {
+ auto cp = uint32_t();
+ auto error = 0;
+ p = utf8_decode(p, &cp, &error);
+ if (error != 0) FMT_THROW(std::runtime_error("invalid utf8"));
+ if (cp <= 0xFFFF) {
+ buffer_.push_back(static_cast<wchar_t>(cp));
+ } else {
+ cp -= 0x10000;
+ buffer_.push_back(static_cast<wchar_t>(0xD800 + (cp >> 10)));
+ buffer_.push_back(static_cast<wchar_t>(0xDC00 + (cp & 0x3FF)));
+ }
+ return p;
+ };
+ auto p = s.data();
+ const size_t block_size = 4; // utf8_decode always reads blocks of 4 chars.
+ if (s.size() >= block_size) {
+ for (auto end = p + s.size() - block_size + 1; p < end;) p = transcode(p);
+ }
+ if (auto num_chars_left = s.data() + s.size() - p) {
+ char buf[2 * block_size - 1] = {};
+ memcpy(buf, p, to_unsigned(num_chars_left));
+ p = buf;
+ do {
+ p = transcode(p);
+ } while (p - buf < num_chars_left);
+ }
+ buffer_.push_back(0);
+}
+
+FMT_FUNC void format_system_error(detail::buffer<char>& out, int error_code,
+ string_view message) FMT_NOEXCEPT {
+ FMT_TRY {
+ memory_buffer buf;
+ buf.resize(inline_buffer_size);
+ for (;;) {
+ char* system_message = &buf[0];
+ int result =
+ detail::safe_strerror(error_code, system_message, buf.size());
+ if (result == 0) {
+ format_to(detail::buffer_appender<char>(out), "{}: {}", message,
+ system_message);
+ return;
+ }
+ if (result != ERANGE)
+ break; // Can't get error message, report error code instead.
+ buf.resize(buf.size() * 2);
+ }
+ }
+ FMT_CATCH(...) {}
+ format_error_code(out, error_code, message);
+}
+
+FMT_FUNC void detail::error_handler::on_error(const char* message) {
+ FMT_THROW(format_error(message));
+}
+
+FMT_FUNC void report_system_error(int error_code,
+ fmt::string_view message) FMT_NOEXCEPT {
+ report_error(format_system_error, error_code, message);
+}
+
+FMT_FUNC std::string detail::vformat(string_view format_str, format_args args) {
+ if (format_str.size() == 2 && equal2(format_str.data(), "{}")) {
+ auto arg = args.get(0);
+ if (!arg) error_handler().on_error("argument not found");
+ return visit_format_arg(stringifier(), arg);
+ }
+ memory_buffer buffer;
+ detail::vformat_to(buffer, format_str, args);
+ return to_string(buffer);
+}
+
+#ifdef _WIN32
+namespace detail {
+using dword = conditional_t<sizeof(long) == 4, unsigned long, unsigned>;
+extern "C" __declspec(dllimport) int __stdcall WriteConsoleW( //
+ void*, const void*, dword, dword*, void*);
+} // namespace detail
+#endif
+
+FMT_FUNC void vprint(std::FILE* f, string_view format_str, format_args args) {
+ memory_buffer buffer;
+ detail::vformat_to(buffer, format_str,
+ basic_format_args<buffer_context<char>>(args));
+#ifdef _WIN32
+ auto fd = _fileno(f);
+ if (_isatty(fd)) {
+ detail::utf8_to_utf16 u16(string_view(buffer.data(), buffer.size()));
+ auto written = detail::dword();
+ if (!detail::WriteConsoleW(reinterpret_cast<void*>(_get_osfhandle(fd)),
+ u16.c_str(), static_cast<uint32_t>(u16.size()),
+ &written, nullptr)) {
+ FMT_THROW(format_error("failed to write to console"));
+ }
+ return;
+ }
+#endif
+ detail::fwrite_fully(buffer.data(), 1, buffer.size(), f);
+}
+
+#ifdef _WIN32
+// Print assuming legacy (non-Unicode) encoding.
+FMT_FUNC void detail::vprint_mojibake(std::FILE* f, string_view format_str,
+ format_args args) {
+ memory_buffer buffer;
+ detail::vformat_to(buffer, format_str,
+ basic_format_args<buffer_context<char>>(args));
+ fwrite_fully(buffer.data(), 1, buffer.size(), f);
+}
+#endif
+
+FMT_FUNC void vprint(string_view format_str, format_args args) {
+ vprint(stdout, format_str, args);
+}
+
+FMT_END_NAMESPACE
+
+#endif // FMT_FORMAT_INL_H_
diff --git a/include/spdlog/fmt/bundled/format.h b/include/spdlog/fmt/bundled/format.h
new file mode 100644
index 00000000..1a037b02
--- /dev/null
+++ b/include/spdlog/fmt/bundled/format.h
@@ -0,0 +1,3960 @@
+/*
+ Formatting library for C++
+
+ Copyright (c) 2012 - present, Victor Zverovich
+
+ 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.
+
+ --- Optional exception to the license ---
+
+ As an exception, if, as a result of your compiling your source code, portions
+ of this Software are embedded into a machine-executable object form of such
+ source code, you may redistribute such embedded portions in such object form
+ without including the above copyright and permission notices.
+ */
+
+#ifndef FMT_FORMAT_H_
+#define FMT_FORMAT_H_
+
+#include <algorithm>
+#include <cerrno>
+#include <cmath>
+#include <cstdint>
+#include <limits>
+#include <memory>
+#include <stdexcept>
+
+#include "core.h"
+
+#ifdef __INTEL_COMPILER
+# define FMT_ICC_VERSION __INTEL_COMPILER
+#elif defined(__ICL)
+# define FMT_ICC_VERSION __ICL
+#else
+# define FMT_ICC_VERSION 0
+#endif
+
+#ifdef __NVCC__
+# define FMT_CUDA_VERSION (__CUDACC_VER_MAJOR__ * 100 + __CUDACC_VER_MINOR__)
+#else
+# define FMT_CUDA_VERSION 0
+#endif
+
+#ifdef __has_builtin
+# define FMT_HAS_BUILTIN(x) __has_builtin(x)
+#else
+# define FMT_HAS_BUILTIN(x) 0
+#endif
+
+#if FMT_GCC_VERSION || FMT_CLANG_VERSION
+# define FMT_NOINLINE __attribute__((noinline))
+#else
+# define FMT_NOINLINE
+#endif
+
+#if __cplusplus == 201103L || __cplusplus == 201402L
+# if defined(__INTEL_COMPILER) || defined(__PGI)
+# define FMT_FALLTHROUGH
+# elif defined(__clang__)
+# define FMT_FALLTHROUGH [[clang::fallthrough]]
+# elif FMT_GCC_VERSION >= 700 && \
+ (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 520)
+# define FMT_FALLTHROUGH [[gnu::fallthrough]]
+# else
+# define FMT_FALLTHROUGH
+# endif
+#elif FMT_HAS_CPP17_ATTRIBUTE(fallthrough) || \
+ (defined(_MSVC_LANG) && _MSVC_LANG >= 201703L)
+# define FMT_FALLTHROUGH [[fallthrough]]
+#else
+# define FMT_FALLTHROUGH
+#endif
+
+#ifndef FMT_MAYBE_UNUSED
+# if FMT_HAS_CPP17_ATTRIBUTE(maybe_unused)
+# define FMT_MAYBE_UNUSED [[maybe_unused]]
+# else
+# define FMT_MAYBE_UNUSED
+# endif
+#endif
+
+#ifndef FMT_THROW
+# if FMT_EXCEPTIONS
+# if FMT_MSC_VER || FMT_NVCC
+FMT_BEGIN_NAMESPACE
+namespace detail {
+template <typename Exception> inline void do_throw(const Exception& x) {
+ // Silence unreachable code warnings in MSVC and NVCC because these
+ // are nearly impossible to fix in a generic code.
+ volatile bool b = true;
+ if (b) throw x;
+}
+} // namespace detail
+FMT_END_NAMESPACE
+# define FMT_THROW(x) detail::do_throw(x)
+# else
+# define FMT_THROW(x) throw x
+# endif
+# else
+# define FMT_THROW(x) \
+ do { \
+ static_cast<void>(sizeof(x)); \
+ FMT_ASSERT(false, ""); \
+ } while (false)
+# endif
+#endif
+
+#if FMT_EXCEPTIONS
+# define FMT_TRY try
+# define FMT_CATCH(x) catch (x)
+#else
+# define FMT_TRY if (true)
+# define FMT_CATCH(x) if (false)
+#endif
+
+#ifndef FMT_USE_USER_DEFINED_LITERALS
+// EDG based compilers (Intel, NVIDIA, Elbrus, etc), GCC and MSVC support UDLs.
+# if (FMT_HAS_FEATURE(cxx_user_literals) || FMT_GCC_VERSION >= 407 || \
+ FMT_MSC_VER >= 1900) && \
+ (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= /* UDL feature */ 480)
+# define FMT_USE_USER_DEFINED_LITERALS 1
+# else
+# define FMT_USE_USER_DEFINED_LITERALS 0
+# endif
+#endif
+
+#ifndef FMT_USE_UDL_TEMPLATE
+// EDG frontend based compilers (icc, nvcc, PGI, etc) and GCC < 6.4 do not
+// properly support UDL templates and GCC >= 9 warns about them.
+# if FMT_USE_USER_DEFINED_LITERALS && \
+ (!defined(__EDG_VERSION__) || __EDG_VERSION__ >= 501) && \
+ ((FMT_GCC_VERSION >= 604 && __cplusplus >= 201402L) || \
+ FMT_CLANG_VERSION >= 304) && \
+ !defined(__PGI) && !defined(__NVCC__)
+# define FMT_USE_UDL_TEMPLATE 1
+# else
+# define FMT_USE_UDL_TEMPLATE 0
+# endif
+#endif
+
+#ifndef FMT_USE_FLOAT
+# define FMT_USE_FLOAT 1
+#endif
+
+#ifndef FMT_USE_DOUBLE
+# define FMT_USE_DOUBLE 1
+#endif
+
+#ifndef FMT_USE_LONG_DOUBLE
+# define FMT_USE_LONG_DOUBLE 1
+#endif
+
+// Defining FMT_REDUCE_INT_INSTANTIATIONS to 1, will reduce the number of
+// int_writer template instances to just one by only using the largest integer
+// type. This results in a reduction in binary size but will cause a decrease in
+// integer formatting performance.
+#if !defined(FMT_REDUCE_INT_INSTANTIATIONS)
+# define FMT_REDUCE_INT_INSTANTIATIONS 0
+#endif
+
+// __builtin_clz is broken in clang with Microsoft CodeGen:
+// https://github.com/fmtlib/fmt/issues/519
+#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clz)) && !FMT_MSC_VER
+# define FMT_BUILTIN_CLZ(n) __builtin_clz(n)
+#endif
+#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_clzll)) && !FMT_MSC_VER
+# define FMT_BUILTIN_CLZLL(n) __builtin_clzll(n)
+#endif
+#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_ctz))
+# define FMT_BUILTIN_CTZ(n) __builtin_ctz(n)
+#endif
+#if (FMT_GCC_VERSION || FMT_HAS_BUILTIN(__builtin_ctzll))
+# define FMT_BUILTIN_CTZLL(n) __builtin_ctzll(n)
+#endif
+
+#if FMT_MSC_VER
+# include <intrin.h> // _BitScanReverse[64], _BitScanForward[64], _umul128
+#endif
+
+// Some compilers masquerade as both MSVC and GCC-likes or otherwise support
+// __builtin_clz and __builtin_clzll, so only define FMT_BUILTIN_CLZ using the
+// MSVC intrinsics if the clz and clzll builtins are not available.
+#if FMT_MSC_VER && !defined(FMT_BUILTIN_CLZLL) && \
+ !defined(FMT_BUILTIN_CTZLL) && !defined(_MANAGED)
+FMT_BEGIN_NAMESPACE
+namespace detail {
+// Avoid Clang with Microsoft CodeGen's -Wunknown-pragmas warning.
+# ifndef __clang__
+# pragma intrinsic(_BitScanForward)
+# pragma intrinsic(_BitScanReverse)
+# endif
+# if defined(_WIN64) && !defined(__clang__)
+# pragma intrinsic(_BitScanForward64)
+# pragma intrinsic(_BitScanReverse64)
+# endif
+
+inline int clz(uint32_t x) {
+ unsigned long r = 0;
+ _BitScanReverse(&r, x);
+ FMT_ASSERT(x != 0, "");
+ // Static analysis complains about using uninitialized data
+ // "r", but the only way that can happen is if "x" is 0,
+ // which the callers guarantee to not happen.
+ FMT_SUPPRESS_MSC_WARNING(6102)
+ return 31 ^ static_cast<int>(r);
+}
+# define FMT_BUILTIN_CLZ(n) detail::clz(n)
+
+inline int clzll(uint64_t x) {
+ unsigned long r = 0;
+# ifdef _WIN64
+ _BitScanReverse64(&r, x);
+# else
+ // Scan the high 32 bits.
+ if (_BitScanReverse(&r, static_cast<uint32_t>(x >> 32))) return 63 ^ (r + 32);
+ // Scan the low 32 bits.
+ _BitScanReverse(&r, static_cast<uint32_t>(x));
+# endif
+ FMT_ASSERT(x != 0, "");
+ FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning.
+ return 63 ^ static_cast<int>(r);
+}
+# define FMT_BUILTIN_CLZLL(n) detail::clzll(n)
+
+inline int ctz(uint32_t x) {
+ unsigned long r = 0;
+ _BitScanForward(&r, x);
+ FMT_ASSERT(x != 0, "");
+ FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning.
+ return static_cast<int>(r);
+}
+# define FMT_BUILTIN_CTZ(n) detail::ctz(n)
+
+inline int ctzll(uint64_t x) {
+ unsigned long r = 0;
+ FMT_ASSERT(x != 0, "");
+ FMT_SUPPRESS_MSC_WARNING(6102) // Suppress a bogus static analysis warning.
+# ifdef _WIN64
+ _BitScanForward64(&r, x);
+# else
+ // Scan the low 32 bits.
+ if (_BitScanForward(&r, static_cast<uint32_t>(x))) return static_cast<int>(r);
+ // Scan the high 32 bits.
+ _BitScanForward(&r, static_cast<uint32_t>(x >> 32));
+ r += 32;
+# endif
+ return static_cast<int>(r);
+}
+# define FMT_BUILTIN_CTZLL(n) detail::ctzll(n)
+} // namespace detail
+FMT_END_NAMESPACE
+#endif
+
+// Enable the deprecated numeric alignment.
+#ifndef FMT_DEPRECATED_NUMERIC_ALIGN
+# define FMT_DEPRECATED_NUMERIC_ALIGN 0
+#endif
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+// An equivalent of `*reinterpret_cast<Dest*>(&source)` that doesn't have
+// undefined behavior (e.g. due to type aliasing).
+// Example: uint64_t d = bit_cast<uint64_t>(2.718);
+template <typename Dest, typename Source>
+inline Dest bit_cast(const Source& source) {
+ static_assert(sizeof(Dest) == sizeof(Source), "size mismatch");
+ Dest dest;
+ std::memcpy(&dest, &source, sizeof(dest));
+ return dest;
+}
+
+inline bool is_big_endian() {
+ const auto u = 1u;
+ struct bytes {
+ char data[sizeof(u)];
+ };
+ return bit_cast<bytes>(u).data[0] == 0;
+}
+
+// A fallback implementation of uintptr_t for systems that lack it.
+struct fallback_uintptr {
+ unsigned char value[sizeof(void*)];
+
+ fallback_uintptr() = default;
+ explicit fallback_uintptr(const void* p) {
+ *this = bit_cast<fallback_uintptr>(p);
+ if (is_big_endian()) {
+ for (size_t i = 0, j = sizeof(void*) - 1; i < j; ++i, --j)
+ std::swap(value[i], value[j]);
+ }
+ }
+};
+#ifdef UINTPTR_MAX
+using uintptr_t = ::uintptr_t;
+inline uintptr_t to_uintptr(const void* p) { return bit_cast<uintptr_t>(p); }
+#else
+using uintptr_t = fallback_uintptr;
+inline fallback_uintptr to_uintptr(const void* p) {
+ return fallback_uintptr(p);
+}
+#endif
+
+// Returns the largest possible value for type T. Same as
+// std::numeric_limits<T>::max() but shorter and not affected by the max macro.
+template <typename T> constexpr T max_value() {
+ return (std::numeric_limits<T>::max)();
+}
+template <typename T> constexpr int num_bits() {
+ return std::numeric_limits<T>::digits;
+}
+// std::numeric_limits<T>::digits may return 0 for 128-bit ints.
+template <> constexpr int num_bits<int128_t>() { return 128; }
+template <> constexpr int num_bits<uint128_t>() { return 128; }
+template <> constexpr int num_bits<fallback_uintptr>() {
+ return static_cast<int>(sizeof(void*) *
+ std::numeric_limits<unsigned char>::digits);
+}
+
+FMT_INLINE void assume(bool condition) {
+ (void)condition;
+#if FMT_HAS_BUILTIN(__builtin_assume)
+ __builtin_assume(condition);
+#endif
+}
+
+// An approximation of iterator_t for pre-C++20 systems.
+template <typename T>
+using iterator_t = decltype(std::begin(std::declval<T&>()));
+template <typename T> using sentinel_t = decltype(std::end(std::declval<T&>()));
+
+// A workaround for std::string not having mutable data() until C++17.
+template <typename Char> inline Char* get_data(std::basic_string<Char>& s) {
+ return &s[0];
+}
+template <typename Container>
+inline typename Container::value_type* get_data(Container& c) {
+ return c.data();
+}
+
+#if defined(_SECURE_SCL) && _SECURE_SCL
+// Make a checked iterator to avoid MSVC warnings.
+template <typename T> using checked_ptr = stdext::checked_array_iterator<T*>;
+template <typename T> checked_ptr<T> make_checked(T* p, size_t size) {
+ return {p, size};
+}
+#else
+template <typename T> using checked_ptr = T*;
+template <typename T> inline T* make_checked(T* p, size_t) { return p; }
+#endif
+
+template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
+#if FMT_CLANG_VERSION
+__attribute__((no_sanitize("undefined")))
+#endif
+inline checked_ptr<typename Container::value_type>
+reserve(std::back_insert_iterator<Container> it, size_t n) {
+ Container& c = get_container(it);
+ size_t size = c.size();
+ c.resize(size + n);
+ return make_checked(get_data(c) + size, n);
+}
+
+template <typename T>
+inline buffer_appender<T> reserve(buffer_appender<T> it, size_t n) {
+ buffer<T>& buf = get_container(it);
+ buf.try_reserve(buf.size() + n);
+ return it;
+}
+
+template <typename Iterator> inline Iterator& reserve(Iterator& it, size_t) {
+ return it;
+}
+
+template <typename T, typename OutputIt>
+constexpr T* to_pointer(OutputIt, size_t) {
+ return nullptr;
+}
+template <typename T> T* to_pointer(buffer_appender<T> it, size_t n) {
+ buffer<T>& buf = get_container(it);
+ auto size = buf.size();
+ if (buf.capacity() < size + n) return nullptr;
+ buf.try_resize(size + n);
+ return buf.data() + size;
+}
+
+template <typename Container, FMT_ENABLE_IF(is_contiguous<Container>::value)>
+inline std::back_insert_iterator<Container> base_iterator(
+ std::back_insert_iterator<Container>& it,
+ checked_ptr<typename Container::value_type>) {
+ return it;
+}
+
+template <typename Iterator>
+inline Iterator base_iterator(Iterator, Iterator it) {
+ return it;
+}
+
+// An output iterator that counts the number of objects written to it and
+// discards them.
+class counting_iterator {
+ private:
+ size_t count_;
+
+ public:
+ using iterator_category = std::output_iterator_tag;
+ using difference_type = std::ptrdiff_t;
+ using pointer = void;
+ using reference = void;
+ using _Unchecked_type = counting_iterator; // Mark iterator as checked.
+
+ struct value_type {
+ template <typename T> void operator=(const T&) {}
+ };
+
+ counting_iterator() : count_(0) {}
+
+ size_t count() const { return count_; }
+
+ counting_iterator& operator++() {
+ ++count_;
+ return *this;
+ }
+ counting_iterator operator++(int) {
+ auto it = *this;
+ ++*this;
+ return it;
+ }
+
+ friend counting_iterator operator+(counting_iterator it, difference_type n) {
+ it.count_ += static_cast<size_t>(n);
+ return it;
+ }
+
+ value_type operator*() const { return {}; }
+};
+
+template <typename OutputIt> class truncating_iterator_base {
+ protected:
+ OutputIt out_;
+ size_t limit_;
+ size_t count_;
+
+ truncating_iterator_base(OutputIt out, size_t limit)
+ : out_(out), limit_(limit), count_(0) {}
+
+ public:
+ using iterator_category = std::output_iterator_tag;
+ using value_type = typename std::iterator_traits<OutputIt>::value_type;
+ using difference_type = void;
+ using pointer = void;
+ using reference = void;
+ using _Unchecked_type =
+ truncating_iterator_base; // Mark iterator as checked.
+
+ OutputIt base() const { return out_; }
+ size_t count() const { return count_; }
+};
+
+// An output iterator that truncates the output and counts the number of objects
+// written to it.
+template <typename OutputIt,
+ typename Enable = typename std::is_void<
+ typename std::iterator_traits<OutputIt>::value_type>::type>
+class truncating_iterator;
+
+template <typename OutputIt>
+class truncating_iterator<OutputIt, std::false_type>
+ : public truncating_iterator_base<OutputIt> {
+ mutable typename truncating_iterator_base<OutputIt>::value_type blackhole_;
+
+ public:
+ using value_type = typename truncating_iterator_base<OutputIt>::value_type;
+
+ truncating_iterator(OutputIt out, size_t limit)
+ : truncating_iterator_base<OutputIt>(out, limit) {}
+
+ truncating_iterator& operator++() {
+ if (this->count_++ < this->limit_) ++this->out_;
+ return *this;
+ }
+
+ truncating_iterator operator++(int) {
+ auto it = *this;
+ ++*this;
+ return it;
+ }
+
+ value_type& operator*() const {
+ return this->count_ < this->limit_ ? *this->out_ : blackhole_;
+ }
+};
+
+template <typename OutputIt>
+class truncating_iterator<OutputIt, std::true_type>
+ : public truncating_iterator_base<OutputIt> {
+ public:
+ truncating_iterator(OutputIt out, size_t limit)
+ : truncating_iterator_base<OutputIt>(out, limit) {}
+
+ template <typename T> truncating_iterator& operator=(T val) {
+ if (this->count_++ < this->limit_) *this->out_++ = val;
+ return *this;
+ }
+
+ truncating_iterator& operator++() { return *this; }
+ truncating_iterator& operator++(int) { return *this; }
+ truncating_iterator& operator*() { return *this; }
+};
+
+template <typename Char>
+inline size_t count_code_points(basic_string_view<Char> s) {
+ return s.size();
+}
+
+// Counts the number of code points in a UTF-8 string.
+inline size_t count_code_points(basic_string_view<char> s) {
+ const char* data = s.data();
+ size_t num_code_points = 0;
+ for (size_t i = 0, size = s.size(); i != size; ++i) {
+ if ((data[i] & 0xc0) != 0x80) ++num_code_points;
+ }
+ return num_code_points;
+}
+
+inline size_t count_code_points(basic_string_view<char8_type> s) {
+ return count_code_points(basic_string_view<char>(
+ reinterpret_cast<const char*>(s.data()), s.size()));
+}
+
+template <typename Char>
+inline size_t code_point_index(basic_string_view<Char> s, size_t n) {
+ size_t size = s.size();
+ return n < size ? n : size;
+}
+
+// Calculates the index of the nth code point in a UTF-8 string.
+inline size_t code_point_index(basic_string_view<char8_type> s, size_t n) {
+ const char8_type* data = s.data();
+ size_t num_code_points = 0;
+ for (size_t i = 0, size = s.size(); i != size; ++i) {
+ if ((data[i] & 0xc0) != 0x80 && ++num_code_points > n) {
+ return i;
+ }
+ }
+ return s.size();
+}
+
+template <typename InputIt, typename OutChar>
+using needs_conversion = bool_constant<
+ std::is_same<typename std::iterator_traits<InputIt>::value_type,
+ char>::value &&
+ std::is_same<OutChar, char8_type>::value>;
+
+template <typename OutChar, typename InputIt, typename OutputIt,
+ FMT_ENABLE_IF(!needs_conversion<InputIt, OutChar>::value)>
+OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) {
+ return std::copy(begin, end, it);
+}
+
+template <typename OutChar, typename InputIt, typename OutputIt,
+ FMT_ENABLE_IF(needs_conversion<InputIt, OutChar>::value)>
+OutputIt copy_str(InputIt begin, InputIt end, OutputIt it) {
+ return std::transform(begin, end, it,
+ [](char c) { return static_cast<char8_type>(c); });
+}
+
+template <typename Char, typename InputIt>
+inline counting_iterator copy_str(InputIt begin, InputIt end,
+ counting_iterator it) {
+ return it + (end - begin);
+}
+
+template <typename T>
+using is_fast_float = bool_constant<std::numeric_limits<T>::is_iec559 &&
+ sizeof(T) <= sizeof(double)>;
+
+#ifndef FMT_USE_FULL_CACHE_DRAGONBOX
+# define FMT_USE_FULL_CACHE_DRAGONBOX 0
+#endif
+
+template <typename T>
+template <typename U>
+void buffer<T>::append(const U* begin, const U* end) {
+ do {
+ auto count = to_unsigned(end - begin);
+ try_reserve(size_ + count);
+ auto free_cap = capacity_ - size_;
+ if (free_cap < count) count = free_cap;
+ std::uninitialized_copy_n(begin, count, make_checked(ptr_ + size_, count));
+ size_ += count;
+ begin += count;
+ } while (begin != end);
+}
+
+template <typename OutputIt, typename T, typename Traits>
+void iterator_buffer<OutputIt, T, Traits>::flush() {
+ out_ = std::copy_n(data_, this->limit(this->size()), out_);
+ this->clear();
+}
+} // namespace detail
+
+// The number of characters to store in the basic_memory_buffer object itself
+// to avoid dynamic memory allocation.
+enum { inline_buffer_size = 500 };
+
+/**
+ \rst
+ A dynamically growing memory buffer for trivially copyable/constructible types
+ with the first ``SIZE`` elements stored in the object itself.
+
+ You can use one of the following type aliases for common character types:
+
+ +----------------+------------------------------+
+ | Type | Definition |
+ +================+==============================+
+ | memory_buffer | basic_memory_buffer<char> |
+ +----------------+------------------------------+
+ | wmemory_buffer | basic_memory_buffer<wchar_t> |
+ +----------------+------------------------------+
+
+ **Example**::
+
+ fmt::memory_buffer out;
+ format_to(out, "The answer is {}.", 42);
+
+ This will append the following output to the ``out`` object:
+
+ .. code-block:: none
+
+ The answer is 42.
+
+ The output can be converted to an ``std::string`` with ``to_string(out)``.
+ \endrst
+ */
+template <typename T, size_t SIZE = inline_buffer_size,
+ typename Allocator = std::allocator<T>>
+class basic_memory_buffer final : public detail::buffer<T> {
+ private:
+ T store_[SIZE];
+
+ // Don't inherit from Allocator avoid generating type_info for it.
+ Allocator alloc_;
+
+ // Deallocate memory allocated by the buffer.
+ void deallocate() {
+ T* data = this->data();
+ if (data != store_) alloc_.deallocate(data, this->capacity());
+ }
+
+ protected:
+ void grow(size_t size) final FMT_OVERRIDE;
+
+ public:
+ using value_type = T;
+ using const_reference = const T&;
+
+ explicit basic_memory_buffer(const Allocator& alloc = Allocator())
+ : alloc_(alloc) {
+ this->set(store_, SIZE);
+ }
+ ~basic_memory_buffer() { deallocate(); }
+
+ private:
+ // Move data from other to this buffer.
+ void move(basic_memory_buffer& other) {
+ alloc_ = std::move(other.alloc_);
+ T* data = other.data();
+ size_t size = other.size(), capacity = other.capacity();
+ if (data == other.store_) {
+ this->set(store_, capacity);
+ std::uninitialized_copy(other.store_, other.store_ + size,
+ detail::make_checked(store_, capacity));
+ } else {
+ this->set(data, capacity);
+ // Set pointer to the inline array so that delete is not called
+ // when deallocating.
+ other.set(other.store_, 0);
+ }
+ this->resize(size);
+ }
+
+ public:
+ /**
+ \rst
+ Constructs a :class:`fmt::basic_memory_buffer` object moving the content
+ of the other object to it.
+ \endrst
+ */
+ basic_memory_buffer(basic_memory_buffer&& other) FMT_NOEXCEPT { move(other); }
+
+ /**
+ \rst
+ Moves the content of the other ``basic_memory_buffer`` object to this one.
+ \endrst
+ */
+ basic_memory_buffer& operator=(basic_memory_buffer&& other) FMT_NOEXCEPT {
+ FMT_ASSERT(this != &other, "");
+ deallocate();
+ move(other);
+ return *this;
+ }
+
+ // Returns a copy of the allocator associated with this buffer.
+ Allocator get_allocator() const { return alloc_; }
+
+ /**
+ Resizes the buffer to contain *count* elements. If T is a POD type new
+ elements may not be initialized.
+ */
+ void resize(size_t count) { this->try_resize(count); }
+
+ /** Increases the buffer capacity to *new_capacity*. */
+ void reserve(size_t new_capacity) { this->try_reserve(new_capacity); }
+
+ // Directly append data into the buffer
+ using detail::buffer<T>::append;
+ template <typename ContiguousRange>
+ void append(const ContiguousRange& range) {
+ append(range.data(), range.data() + range.size());
+ }
+};
+
+template <typename T, size_t SIZE, typename Allocator>
+void basic_memory_buffer<T, SIZE, Allocator>::grow(size_t size) {
+#ifdef FMT_FUZZ
+ if (size > 5000) throw std::runtime_error("fuzz mode - won't grow that much");
+#endif
+ size_t old_capacity = this->capacity();
+ size_t new_capacity = old_capacity + old_capacity / 2;
+ if (size > new_capacity) new_capacity = size;
+ T* old_data = this->data();
+ T* new_data =
+ std::allocator_traits<Allocator>::allocate(alloc_, new_capacity);
+ // The following code doesn't throw, so the raw pointer above doesn't leak.
+ std::uninitialized_copy(old_data, old_data + this->size(),
+ detail::make_checked(new_data, new_capacity));
+ this->set(new_data, new_capacity);
+ // deallocate must not throw according to the standard, but even if it does,
+ // the buffer already uses the new storage and will deallocate it in
+ // destructor.
+ if (old_data != store_) alloc_.deallocate(old_data, old_capacity);
+}
+
+using memory_buffer = basic_memory_buffer<char>;
+using wmemory_buffer = basic_memory_buffer<wchar_t>;
+
+template <typename T, size_t SIZE, typename Allocator>
+struct is_contiguous<basic_memory_buffer<T, SIZE, Allocator>> : std::true_type {
+};
+
+/** A formatting error such as invalid format string. */
+FMT_CLASS_API
+class FMT_API format_error : public std::runtime_error {
+ public:
+ explicit format_error(const char* message) : std::runtime_error(message) {}
+ explicit format_error(const std::string& message)
+ : std::runtime_error(message) {}
+ format_error(const format_error&) = default;
+ format_error& operator=(const format_error&) = default;
+ format_error(format_error&&) = default;
+ format_error& operator=(format_error&&) = default;
+ ~format_error() FMT_NOEXCEPT FMT_OVERRIDE;
+};
+
+namespace detail {
+
+template <typename T>
+using is_signed =
+ std::integral_constant<bool, std::numeric_limits<T>::is_signed ||
+ std::is_same<T, int128_t>::value>;
+
+// Returns true if value is negative, false otherwise.
+// Same as `value < 0` but doesn't produce warnings if T is an unsigned type.
+template <typename T, FMT_ENABLE_IF(is_signed<T>::value)>
+FMT_CONSTEXPR bool is_negative(T value) {
+ return value < 0;
+}
+template <typename T, FMT_ENABLE_IF(!is_signed<T>::value)>
+FMT_CONSTEXPR bool is_negative(T) {
+ return false;
+}
+
+template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+FMT_CONSTEXPR bool is_supported_floating_point(T) {
+ return (std::is_same<T, float>::value && FMT_USE_FLOAT) ||
+ (std::is_same<T, double>::value && FMT_USE_DOUBLE) ||
+ (std::is_same<T, long double>::value && FMT_USE_LONG_DOUBLE);
+}
+
+// Smallest of uint32_t, uint64_t, uint128_t that is large enough to
+// represent all values of an integral type T.
+template <typename T>
+using uint32_or_64_or_128_t =
+ conditional_t<num_bits<T>() <= 32 && !FMT_REDUCE_INT_INSTANTIATIONS,
+ uint32_t,
+ conditional_t<num_bits<T>() <= 64, uint64_t, uint128_t>>;
+
+// 128-bit integer type used internally
+struct FMT_EXTERN_TEMPLATE_API uint128_wrapper {
+ uint128_wrapper() = default;
+
+#if FMT_USE_INT128
+ uint128_t internal_;
+
+ uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT
+ : internal_{static_cast<uint128_t>(low) |
+ (static_cast<uint128_t>(high) << 64)} {}
+
+ uint128_wrapper(uint128_t u) : internal_{u} {}
+
+ uint64_t high() const FMT_NOEXCEPT { return uint64_t(internal_ >> 64); }
+ uint64_t low() const FMT_NOEXCEPT { return uint64_t(internal_); }
+
+ uint128_wrapper& operator+=(uint64_t n) FMT_NOEXCEPT {
+ internal_ += n;
+ return *this;
+ }
+#else
+ uint64_t high_;
+ uint64_t low_;
+
+ uint128_wrapper(uint64_t high, uint64_t low) FMT_NOEXCEPT : high_{high},
+ low_{low} {}
+
+ uint64_t high() const FMT_NOEXCEPT { return high_; }
+ uint64_t low() const FMT_NOEXCEPT { return low_; }
+
+ uint128_wrapper& operator+=(uint64_t n) FMT_NOEXCEPT {
+# if defined(_MSC_VER) && defined(_M_X64)
+ unsigned char carry = _addcarry_u64(0, low_, n, &low_);
+ _addcarry_u64(carry, high_, 0, &high_);
+ return *this;
+# else
+ uint64_t sum = low_ + n;
+ high_ += (sum < low_ ? 1 : 0);
+ low_ = sum;
+ return *this;
+# endif
+ }
+#endif
+};
+
+// Table entry type for divisibility test used internally
+template <typename T> struct FMT_EXTERN_TEMPLATE_API divtest_table_entry {
+ T mod_inv;
+ T max_quotient;
+};
+
+// Static data is placed in this class template for the header-only config.
+template <typename T = void> struct FMT_EXTERN_TEMPLATE_API basic_data {
+ static const uint64_t powers_of_10_64[];
+ static const uint32_t zero_or_powers_of_10_32_new[];
+ static const uint64_t zero_or_powers_of_10_64_new[];
+ static const uint64_t grisu_pow10_significands[];
+ static const int16_t grisu_pow10_exponents[];
+ static const divtest_table_entry<uint32_t> divtest_table_for_pow5_32[];
+ static const divtest_table_entry<uint64_t> divtest_table_for_pow5_64[];
+ static const uint64_t dragonbox_pow10_significands_64[];
+ static const uint128_wrapper dragonbox_pow10_significands_128[];
+ // log10(2) = 0x0.4d104d427de7fbcc...
+ static const uint64_t log10_2_significand = 0x4d104d427de7fbcc;
+#if !FMT_USE_FULL_CACHE_DRAGONBOX
+ static const uint64_t powers_of_5_64[];
+ static const uint32_t dragonbox_pow10_recovery_errors[];
+#endif
+ // GCC generates slightly better code for pairs than chars.
+ using digit_pair = char[2];
+ static const digit_pair digits[];
+ static const char hex_digits[];
+ static const char foreground_color[];
+ static const char background_color[];
+ static const char reset_color[5];
+ static const wchar_t wreset_color[5];
+ static const char signs[];
+ static const char left_padding_shifts[5];
+ static const char right_padding_shifts[5];
+
+ // DEPRECATED! These are for ABI compatibility.
+ static const uint32_t zero_or_powers_of_10_32[];
+ static const uint64_t zero_or_powers_of_10_64[];
+};
+
+// Maps bsr(n) to ceil(log10(pow(2, bsr(n) + 1) - 1)).
+// This is a function instead of an array to workaround a bug in GCC10 (#1810).
+FMT_INLINE uint16_t bsr2log10(int bsr) {
+ static constexpr uint16_t data[] = {
+ 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5,
+ 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 10, 10, 10,
+ 10, 11, 11, 11, 12, 12, 12, 13, 13, 13, 13, 14, 14, 14, 15, 15,
+ 15, 16, 16, 16, 16, 17, 17, 17, 18, 18, 18, 19, 19, 19, 19, 20};
+ return data[bsr];
+}
+
+#ifndef FMT_EXPORTED
+FMT_EXTERN template struct basic_data<void>;
+#endif
+
+// This is a struct rather than an alias to avoid shadowing warnings in gcc.
+struct data : basic_data<> {};
+
+#ifdef FMT_BUILTIN_CLZLL
+// Returns the number of decimal digits in n. Leading zeros are not counted
+// except for n == 0 in which case count_digits returns 1.
+inline int count_digits(uint64_t n) {
+ // https://github.com/fmtlib/format-benchmark/blob/master/digits10
+ auto t = bsr2log10(FMT_BUILTIN_CLZLL(n | 1) ^ 63);
+ return t - (n < data::zero_or_powers_of_10_64_new[t]);
+}
+#else
+// Fallback version of count_digits used when __builtin_clz is not available.
+inline int count_digits(uint64_t n) {
+ int count = 1;
+ for (;;) {
+ // Integer division is slow so do it for a group of four digits instead
+ // of for every digit. The idea comes from the talk by Alexandrescu
+ // "Three Optimization Tips for C++". See speed-test for a comparison.
+ if (n < 10) return count;
+ if (n < 100) return count + 1;
+ if (n < 1000) return count + 2;
+ if (n < 10000) return count + 3;
+ n /= 10000u;
+ count += 4;
+ }
+}
+#endif
+
+#if FMT_USE_INT128
+inline int count_digits(uint128_t n) {
+ int count = 1;
+ for (;;) {
+ // Integer division is slow so do it for a group of four digits instead
+ // of for every digit. The idea comes from the talk by Alexandrescu
+ // "Three Optimization Tips for C++". See speed-test for a comparison.
+ if (n < 10) return count;
+ if (n < 100) return count + 1;
+ if (n < 1000) return count + 2;
+ if (n < 10000) return count + 3;
+ n /= 10000U;
+ count += 4;
+ }
+}
+#endif
+
+// Counts the number of digits in n. BITS = log2(radix).
+template <unsigned BITS, typename UInt> inline int count_digits(UInt n) {
+ int num_digits = 0;
+ do {
+ ++num_digits;
+ } while ((n >>= BITS) != 0);
+ return num_digits;
+}
+
+template <> int count_digits<4>(detail::fallback_uintptr n);
+
+#if FMT_GCC_VERSION || FMT_CLANG_VERSION
+# define FMT_ALWAYS_INLINE inline __attribute__((always_inline))
+#elif FMT_MSC_VER
+# define FMT_ALWAYS_INLINE __forceinline
+#else
+# define FMT_ALWAYS_INLINE inline
+#endif
+
+// To suppress unnecessary security cookie checks
+#if FMT_MSC_VER && !FMT_CLANG_VERSION
+# define FMT_SAFEBUFFERS __declspec(safebuffers)
+#else
+# define FMT_SAFEBUFFERS
+#endif
+
+#ifdef FMT_BUILTIN_CLZ
+// Optional version of count_digits for better performance on 32-bit platforms.
+inline int count_digits(uint32_t n) {
+ auto t = bsr2log10(FMT_BUILTIN_CLZ(n | 1) ^ 31);
+ return t - (n < data::zero_or_powers_of_10_32_new[t]);
+}
+#endif
+
+template <typename Int> constexpr int digits10() FMT_NOEXCEPT {
+ return std::numeric_limits<Int>::digits10;
+}
+template <> constexpr int digits10<int128_t>() FMT_NOEXCEPT { return 38; }
+template <> constexpr int digits10<uint128_t>() FMT_NOEXCEPT { return 38; }
+
+template <typename Char> FMT_API std::string grouping_impl(locale_ref loc);
+template <typename Char> inline std::string grouping(locale_ref loc) {
+ return grouping_impl<char>(loc);
+}
+template <> inline std::string grouping<wchar_t>(locale_ref loc) {
+ return grouping_impl<wchar_t>(loc);
+}
+
+template <typename Char> FMT_API Char thousands_sep_impl(locale_ref loc);
+template <typename Char> inline Char thousands_sep(locale_ref loc) {
+ return Char(thousands_sep_impl<char>(loc));
+}
+template <> inline wchar_t thousands_sep(locale_ref loc) {
+ return thousands_sep_impl<wchar_t>(loc);
+}
+
+template <typename Char> FMT_API Char decimal_point_impl(locale_ref loc);
+template <typename Char> inline Char decimal_point(locale_ref loc) {
+ return Char(decimal_point_impl<char>(loc));
+}
+template <> inline wchar_t decimal_point(locale_ref loc) {
+ return decimal_point_impl<wchar_t>(loc);
+}
+
+// Compares two characters for equality.
+template <typename Char> bool equal2(const Char* lhs, const char* rhs) {
+ return lhs[0] == rhs[0] && lhs[1] == rhs[1];
+}
+inline bool equal2(const char* lhs, const char* rhs) {
+ return memcmp(lhs, rhs, 2) == 0;
+}
+
+// Copies two characters from src to dst.
+template <typename Char> void copy2(Char* dst, const char* src) {
+ *dst++ = static_cast<Char>(*src++);
+ *dst = static_cast<Char>(*src);
+}
+FMT_INLINE void copy2(char* dst, const char* src) { memcpy(dst, src, 2); }
+
+template <typename Iterator> struct format_decimal_result {
+ Iterator begin;
+ Iterator end;
+};
+
+// Formats a decimal unsigned integer value writing into out pointing to a
+// buffer of specified size. The caller must ensure that the buffer is large
+// enough.
+template <typename Char, typename UInt>
+inline format_decimal_result<Char*> format_decimal(Char* out, UInt value,
+ int size) {
+ FMT_ASSERT(size >= count_digits(value), "invalid digit count");
+ out += size;
+ Char* end = out;
+ while (value >= 100) {
+ // Integer division is slow so do it for a group of two digits instead
+ // of for every digit. The idea comes from the talk by Alexandrescu
+ // "Three Optimization Tips for C++". See speed-test for a comparison.
+ out -= 2;
+ copy2(out, data::digits[value % 100]);
+ value /= 100;
+ }
+ if (value < 10) {
+ *--out = static_cast<Char>('0' + value);
+ return {out, end};
+ }
+ out -= 2;
+ copy2(out, data::digits[value]);
+ return {out, end};
+}
+
+template <typename Char, typename UInt, typename Iterator,
+ FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<Iterator>>::value)>
+inline format_decimal_result<Iterator> format_decimal(Iterator out, UInt value,
+ int size) {
+ // Buffer is large enough to hold all digits (digits10 + 1).
+ Char buffer[digits10<UInt>() + 1];
+ auto end = format_decimal(buffer, value, size).end;
+ return {out, detail::copy_str<Char>(buffer, end, out)};
+}
+
+template <unsigned BASE_BITS, typename Char, typename UInt>
+inline Char* format_uint(Char* buffer, UInt value, int num_digits,
+ bool upper = false) {
+ buffer += num_digits;
+ Char* end = buffer;
+ do {
+ const char* digits = upper ? "0123456789ABCDEF" : data::hex_digits;
+ unsigned digit = (value & ((1 << BASE_BITS) - 1));
+ *--buffer = static_cast<Char>(BASE_BITS < 4 ? static_cast<char>('0' + digit)
+ : digits[digit]);
+ } while ((value >>= BASE_BITS) != 0);
+ return end;
+}
+
+template <unsigned BASE_BITS, typename Char>
+Char* format_uint(Char* buffer, detail::fallback_uintptr n, int num_digits,
+ bool = false) {
+ auto char_digits = std::numeric_limits<unsigned char>::digits / 4;
+ int start = (num_digits + char_digits - 1) / char_digits - 1;
+ if (int start_digits = num_digits % char_digits) {
+ unsigned value = n.value[start--];
+ buffer = format_uint<BASE_BITS>(buffer, value, start_digits);
+ }
+ for (; start >= 0; --start) {
+ unsigned value = n.value[start];
+ buffer += char_digits;
+ auto p = buffer;
+ for (int i = 0; i < char_digits; ++i) {
+ unsigned digit = (value & ((1 << BASE_BITS) - 1));
+ *--p = static_cast<Char>(data::hex_digits[digit]);
+ value >>= BASE_BITS;
+ }
+ }
+ return buffer;
+}
+
+template <unsigned BASE_BITS, typename Char, typename It, typename UInt>
+inline It format_uint(It out, UInt value, int num_digits, bool upper = false) {
+ if (auto ptr = to_pointer<Char>(out, to_unsigned(num_digits))) {
+ format_uint<BASE_BITS>(ptr, value, num_digits, upper);
+ return out;
+ }
+ // Buffer should be large enough to hold all digits (digits / BASE_BITS + 1).
+ char buffer[num_bits<UInt>() / BASE_BITS + 1];
+ format_uint<BASE_BITS>(buffer, value, num_digits, upper);
+ return detail::copy_str<Char>(buffer, buffer + num_digits, out);
+}
+
+// A converter from UTF-8 to UTF-16.
+class utf8_to_utf16 {
+ private:
+ wmemory_buffer buffer_;
+
+ public:
+ FMT_API explicit utf8_to_utf16(string_view s);
+ operator wstring_view() const { return {&buffer_[0], size()}; }
+ size_t size() const { return buffer_.size() - 1; }
+ const wchar_t* c_str() const { return &buffer_[0]; }
+ std::wstring str() const { return {&buffer_[0], size()}; }
+};
+
+template <typename T = void> struct null {};
+
+// Workaround an array initialization issue in gcc 4.8.
+template <typename Char> struct fill_t {
+ private:
+ enum { max_size = 4 };
+ Char data_[max_size] = {Char(' '), Char(0), Char(0), Char(0)};
+ unsigned char size_ = 1;
+
+ public:
+ FMT_CONSTEXPR void operator=(basic_string_view<Char> s) {
+ auto size = s.size();
+ if (size > max_size) {
+ FMT_THROW(format_error("invalid fill"));
+ return;
+ }
+ for (size_t i = 0; i < size; ++i) data_[i] = s[i];
+ size_ = static_cast<unsigned char>(size);
+ }
+
+ size_t size() const { return size_; }
+ const Char* data() const { return data_; }
+
+ FMT_CONSTEXPR Char& operator[](size_t index) { return data_[index]; }
+ FMT_CONSTEXPR const Char& operator[](size_t index) const {
+ return data_[index];
+ }
+};
+} // namespace detail
+
+// We cannot use enum classes as bit fields because of a gcc bug
+// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=61414.
+namespace align {
+enum type { none, left, right, center, numeric };
+}
+using align_t = align::type;
+
+namespace sign {
+enum type { none, minus, plus, space };
+}
+using sign_t = sign::type;
+
+// Format specifiers for built-in and string types.
+template <typename Char> struct basic_format_specs {
+ int width;
+ int precision;
+ char type;
+ align_t align : 4;
+ sign_t sign : 3;
+ bool alt : 1; // Alternate form ('#').
+ detail::fill_t<Char> fill;
+
+ constexpr basic_format_specs()
+ : width(0),
+ precision(-1),
+ type(0),
+ align(align::none),
+ sign(sign::none),
+ alt(false) {}
+};
+
+using format_specs = basic_format_specs<char>;
+
+namespace detail {
+namespace dragonbox {
+
+// Type-specific information that Dragonbox uses.
+template <class T> struct float_info;
+
+template <> struct float_info<float> {
+ using carrier_uint = uint32_t;
+ static const int significand_bits = 23;
+ static const int exponent_bits = 8;
+ static const int min_exponent = -126;
+ static const int max_exponent = 127;
+ static const int exponent_bias = -127;
+ static const int decimal_digits = 9;
+ static const int kappa = 1;
+ static const int big_divisor = 100;
+ static const int small_divisor = 10;
+ static const int min_k = -31;
+ static const int max_k = 46;
+ static const int cache_bits = 64;
+ static const int divisibility_check_by_5_threshold = 39;
+ static const int case_fc_pm_half_lower_threshold = -1;
+ static const int case_fc_pm_half_upper_threshold = 6;
+ static const int case_fc_lower_threshold = -2;
+ static const int case_fc_upper_threshold = 6;
+ static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
+ static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
+ static const int shorter_interval_tie_lower_threshold = -35;
+ static const int shorter_interval_tie_upper_threshold = -35;
+ static const int max_trailing_zeros = 7;
+};
+
+template <> struct float_info<double> {
+ using carrier_uint = uint64_t;
+ static const int significand_bits = 52;
+ static const int exponent_bits = 11;
+ static const int min_exponent = -1022;
+ static const int max_exponent = 1023;
+ static const int exponent_bias = -1023;
+ static const int decimal_digits = 17;
+ static const int kappa = 2;
+ static const int big_divisor = 1000;
+ static const int small_divisor = 100;
+ static const int min_k = -292;
+ static const int max_k = 326;
+ static const int cache_bits = 128;
+ static const int divisibility_check_by_5_threshold = 86;
+ static const int case_fc_pm_half_lower_threshold = -2;
+ static const int case_fc_pm_half_upper_threshold = 9;
+ static const int case_fc_lower_threshold = -4;
+ static const int case_fc_upper_threshold = 9;
+ static const int case_shorter_interval_left_endpoint_lower_threshold = 2;
+ static const int case_shorter_interval_left_endpoint_upper_threshold = 3;
+ static const int shorter_interval_tie_lower_threshold = -77;
+ static const int shorter_interval_tie_upper_threshold = -77;
+ static const int max_trailing_zeros = 16;
+};
+
+template <typename T> struct decimal_fp {
+ using significand_type = typename float_info<T>::carrier_uint;
+ significand_type significand;
+ int exponent;
+};
+
+template <typename T> FMT_API decimal_fp<T> to_decimal(T x) FMT_NOEXCEPT;
+} // namespace dragonbox
+
+template <typename T>
+constexpr typename dragonbox::float_info<T>::carrier_uint exponent_mask() {
+ using uint = typename dragonbox::float_info<T>::carrier_uint;
+ return ((uint(1) << dragonbox::float_info<T>::exponent_bits) - 1)
+ << dragonbox::float_info<T>::significand_bits;
+}
+
+// A floating-point presentation format.
+enum class float_format : unsigned char {
+ general, // General: exponent notation or fixed point based on magnitude.
+ exp, // Exponent notation with the default precision of 6, e.g. 1.2e-3.
+ fixed, // Fixed point with the default precision of 6, e.g. 0.0012.
+ hex
+};
+
+struct float_specs {
+ int precision;
+ float_format format : 8;
+ sign_t sign : 8;
+ bool upper : 1;
+ bool locale : 1;
+ bool binary32 : 1;
+ bool use_grisu : 1;
+ bool showpoint : 1;
+};
+
+// Writes the exponent exp in the form "[+-]d{2,3}" to buffer.
+template <typename Char, typename It> It write_exponent(int exp, It it) {
+ FMT_ASSERT(-10000 < exp && exp < 10000, "exponent out of range");
+ if (exp < 0) {
+ *it++ = static_cast<Char>('-');
+ exp = -exp;
+ } else {
+ *it++ = static_cast<Char>('+');
+ }
+ if (exp >= 100) {
+ const char* top = data::digits[exp / 100];
+ if (exp >= 1000) *it++ = static_cast<Char>(top[0]);
+ *it++ = static_cast<Char>(top[1]);
+ exp %= 100;
+ }
+ const char* d = data::digits[exp];
+ *it++ = static_cast<Char>(d[0]);
+ *it++ = static_cast<Char>(d[1]);
+ return it;
+}
+
+template <typename T>
+int format_float(T value, int precision, float_specs specs, buffer<char>& buf);
+
+// Formats a floating-point number with snprintf.
+template <typename T>
+int snprintf_float(T value, int precision, float_specs specs,
+ buffer<char>& buf);
+
+template <typename T> T promote_float(T value) { return value; }
+inline double promote_float(float value) { return static_cast<double>(value); }
+
+template <typename Handler>
+FMT_CONSTEXPR void handle_int_type_spec(char spec, Handler&& handler) {
+ switch (spec) {
+ case 0:
+ case 'd':
+ handler.on_dec();
+ break;
+ case 'x':
+ case 'X':
+ handler.on_hex();
+ break;
+ case 'b':
+ case 'B':
+ handler.on_bin();
+ break;
+ case 'o':
+ handler.on_oct();
+ break;
+#ifdef FMT_DEPRECATED_N_SPECIFIER
+ case 'n':
+#endif
+ case 'L':
+ handler.on_num();
+ break;
+ case 'c':
+ handler.on_chr();
+ break;
+ default:
+ handler.on_error();
+ }
+}
+
+template <typename ErrorHandler = error_handler, typename Char>
+FMT_CONSTEXPR float_specs parse_float_type_spec(
+ const basic_format_specs<Char>& specs, ErrorHandler&& eh = {}) {
+ auto result = float_specs();
+ result.showpoint = specs.alt;
+ switch (specs.type) {
+ case 0:
+ result.format = float_format::general;
+ result.showpoint |= specs.precision > 0;
+ break;
+ case 'G':
+ result.upper = true;
+ FMT_FALLTHROUGH;
+ case 'g':
+ result.format = float_format::general;
+ break;
+ case 'E':
+ result.upper = true;
+ FMT_FALLTHROUGH;
+ case 'e':
+ result.format = float_format::exp;
+ result.showpoint |= specs.precision != 0;
+ break;
+ case 'F':
+ result.upper = true;
+ FMT_FALLTHROUGH;
+ case 'f':
+ result.format = float_format::fixed;
+ result.showpoint |= specs.precision != 0;
+ break;
+ case 'A':
+ result.upper = true;
+ FMT_FALLTHROUGH;
+ case 'a':
+ result.format = float_format::hex;
+ break;
+#ifdef FMT_DEPRECATED_N_SPECIFIER
+ case 'n':
+#endif
+ case 'L':
+ result.locale = true;
+ break;
+ default:
+ eh.on_error("invalid type specifier");
+ break;
+ }
+ return result;
+}
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR void handle_char_specs(const basic_format_specs<Char>* specs,
+ Handler&& handler) {
+ if (!specs) return handler.on_char();
+ if (specs->type && specs->type != 'c') return handler.on_int();
+ if (specs->align == align::numeric || specs->sign != sign::none || specs->alt)
+ handler.on_error("invalid format specifier for char");
+ handler.on_char();
+}
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR void handle_cstring_type_spec(Char spec, Handler&& handler) {
+ if (spec == 0 || spec == 's')
+ handler.on_string();
+ else if (spec == 'p')
+ handler.on_pointer();
+ else
+ handler.on_error("invalid type specifier");
+}
+
+template <typename Char, typename ErrorHandler>
+FMT_CONSTEXPR void check_string_type_spec(Char spec, ErrorHandler&& eh) {
+ if (spec != 0 && spec != 's') eh.on_error("invalid type specifier");
+}
+
+template <typename Char, typename ErrorHandler>
+FMT_CONSTEXPR void check_pointer_type_spec(Char spec, ErrorHandler&& eh) {
+ if (spec != 0 && spec != 'p') eh.on_error("invalid type specifier");
+}
+
+template <typename ErrorHandler> class int_type_checker : private ErrorHandler {
+ public:
+ FMT_CONSTEXPR explicit int_type_checker(ErrorHandler eh) : ErrorHandler(eh) {}
+
+ FMT_CONSTEXPR void on_dec() {}
+ FMT_CONSTEXPR void on_hex() {}
+ FMT_CONSTEXPR void on_bin() {}
+ FMT_CONSTEXPR void on_oct() {}
+ FMT_CONSTEXPR void on_num() {}
+ FMT_CONSTEXPR void on_chr() {}
+
+ FMT_CONSTEXPR void on_error() {
+ ErrorHandler::on_error("invalid type specifier");
+ }
+};
+
+template <typename ErrorHandler>
+class char_specs_checker : public ErrorHandler {
+ private:
+ char type_;
+
+ public:
+ FMT_CONSTEXPR char_specs_checker(char type, ErrorHandler eh)
+ : ErrorHandler(eh), type_(type) {}
+
+ FMT_CONSTEXPR void on_int() {
+ handle_int_type_spec(type_, int_type_checker<ErrorHandler>(*this));
+ }
+ FMT_CONSTEXPR void on_char() {}
+};
+
+template <typename ErrorHandler>
+class cstring_type_checker : public ErrorHandler {
+ public:
+ FMT_CONSTEXPR explicit cstring_type_checker(ErrorHandler eh)
+ : ErrorHandler(eh) {}
+
+ FMT_CONSTEXPR void on_string() {}
+ FMT_CONSTEXPR void on_pointer() {}
+};
+
+template <typename OutputIt, typename Char>
+FMT_NOINLINE OutputIt fill(OutputIt it, size_t n, const fill_t<Char>& fill) {
+ auto fill_size = fill.size();
+ if (fill_size == 1) return std::fill_n(it, n, fill[0]);
+ for (size_t i = 0; i < n; ++i) it = std::copy_n(fill.data(), fill_size, it);
+ return it;
+}
+
+// Writes the output of f, padded according to format specifications in specs.
+// size: output size in code units.
+// width: output display width in (terminal) column positions.
+template <align::type align = align::left, typename OutputIt, typename Char,
+ typename F>
+inline OutputIt write_padded(OutputIt out,
+ const basic_format_specs<Char>& specs, size_t size,
+ size_t width, F&& f) {
+ static_assert(align == align::left || align == align::right, "");
+ unsigned spec_width = to_unsigned(specs.width);
+ size_t padding = spec_width > width ? spec_width - width : 0;
+ auto* shifts = align == align::left ? data::left_padding_shifts
+ : data::right_padding_shifts;
+ size_t left_padding = padding >> shifts[specs.align];
+ auto it = reserve(out, size + padding * specs.fill.size());
+ it = fill(it, left_padding, specs.fill);
+ it = f(it);
+ it = fill(it, padding - left_padding, specs.fill);
+ return base_iterator(out, it);
+}
+
+template <align::type align = align::left, typename OutputIt, typename Char,
+ typename F>
+inline OutputIt write_padded(OutputIt out,
+ const basic_format_specs<Char>& specs, size_t size,
+ F&& f) {
+ return write_padded<align>(out, specs, size, size, f);
+}
+
+template <typename Char, typename OutputIt>
+OutputIt write_bytes(OutputIt out, string_view bytes,
+ const basic_format_specs<Char>& specs) {
+ using iterator = remove_reference_t<decltype(reserve(out, 0))>;
+ return write_padded(out, specs, bytes.size(), [bytes](iterator it) {
+ const char* data = bytes.data();
+ return copy_str<Char>(data, data + bytes.size(), it);
+ });
+}
+
+// Data for write_int that doesn't depend on output iterator type. It is used to
+// avoid template code bloat.
+template <typename Char> struct write_int_data {
+ size_t size;
+ size_t padding;
+
+ write_int_data(int num_digits, string_view prefix,
+ const basic_format_specs<Char>& specs)
+ : size(prefix.size() + to_unsigned(num_digits)), padding(0) {
+ if (specs.align == align::numeric) {
+ auto width = to_unsigned(specs.width);
+ if (width > size) {
+ padding = width - size;
+ size = width;
+ }
+ } else if (specs.precision > num_digits) {
+ size = prefix.size() + to_unsigned(specs.precision);
+ padding = to_unsigned(specs.precision - num_digits);
+ }
+ }
+};
+
+// Writes an integer in the format
+// <left-padding><prefix><numeric-padding><digits><right-padding>
+// where <digits> are written by f(it).
+template <typename OutputIt, typename Char, typename F>
+OutputIt write_int(OutputIt out, int num_digits, string_view prefix,
+ const basic_format_specs<Char>& specs, F f) {
+ auto data = write_int_data<Char>(num_digits, prefix, specs);
+ using iterator = remove_reference_t<decltype(reserve(out, 0))>;
+ return write_padded<align::right>(out, specs, data.size, [=](iterator it) {
+ if (prefix.size() != 0)
+ it = copy_str<Char>(prefix.begin(), prefix.end(), it);
+ it = std::fill_n(it, data.padding, static_cast<Char>('0'));
+ return f(it);
+ });
+}
+
+template <typename StrChar, typename Char, typename OutputIt>
+OutputIt write(OutputIt out, basic_string_view<StrChar> s,
+ const basic_format_specs<Char>& specs) {
+ auto data = s.data();
+ auto size = s.size();
+ if (specs.precision >= 0 && to_unsigned(specs.precision) < size)
+ size = code_point_index(s, to_unsigned(specs.precision));
+ auto width = specs.width != 0
+ ? count_code_points(basic_string_view<StrChar>(data, size))
+ : 0;
+ using iterator = remove_reference_t<decltype(reserve(out, 0))>;
+ return write_padded(out, specs, size, width, [=](iterator it) {
+ return copy_str<Char>(data, data + size, it);
+ });
+}
+
+// The handle_int_type_spec handler that writes an integer.
+template <typename OutputIt, typename Char, typename UInt> struct int_writer {
+ OutputIt out;
+ locale_ref locale;
+ const basic_format_specs<Char>& specs;
+ UInt abs_value;
+ char prefix[4];
+ unsigned prefix_size;
+
+ using iterator =
+ remove_reference_t<decltype(reserve(std::declval<OutputIt&>(), 0))>;
+
+ string_view get_prefix() const { return string_view(prefix, prefix_size); }
+
+ template <typename Int>
+ int_writer(OutputIt output, locale_ref loc, Int value,
+ const basic_format_specs<Char>& s)
+ : out(output),
+ locale(loc),
+ specs(s),
+ abs_value(static_cast<UInt>(value)),
+ prefix_size(0) {
+ static_assert(std::is_same<uint32_or_64_or_128_t<Int>, UInt>::value, "");
+ if (is_negative(value)) {
+ prefix[0] = '-';
+ ++prefix_size;
+ abs_value = 0 - abs_value;
+ } else if (specs.sign != sign::none && specs.sign != sign::minus) {
+ prefix[0] = specs.sign == sign::plus ? '+' : ' ';
+ ++prefix_size;
+ }
+ }
+
+ void on_dec() {
+ auto num_digits = count_digits(abs_value);
+ out = write_int(
+ out, num_digits, get_prefix(), specs, [this, num_digits](iterator it) {
+ return format_decimal<Char>(it, abs_value, num_digits).end;
+ });
+ }
+
+ void on_hex() {
+ if (specs.alt) {
+ prefix[prefix_size++] = '0';
+ prefix[prefix_size++] = specs.type;
+ }
+ int num_digits = count_digits<4>(abs_value);
+ out = write_int(out, num_digits, get_prefix(), specs,
+ [this, num_digits](iterator it) {
+ return format_uint<4, Char>(it, abs_value, num_digits,
+ specs.type != 'x');
+ });
+ }
+
+ void on_bin() {
+ if (specs.alt) {
+ prefix[prefix_size++] = '0';
+ prefix[prefix_size++] = static_cast<char>(specs.type);
+ }
+ int num_digits = count_digits<1>(abs_value);
+ out = write_int(out, num_digits, get_prefix(), specs,
+ [this, num_digits](iterator it) {
+ return format_uint<1, Char>(it, abs_value, num_digits);
+ });
+ }
+
+ void on_oct() {
+ int num_digits = count_digits<3>(abs_value);
+ if (specs.alt && specs.precision <= num_digits && abs_value != 0) {
+ // Octal prefix '0' is counted as a digit, so only add it if precision
+ // is not greater than the number of digits.
+ prefix[prefix_size++] = '0';
+ }
+ out = write_int(out, num_digits, get_prefix(), specs,
+ [this, num_digits](iterator it) {
+ return format_uint<3, Char>(it, abs_value, num_digits);
+ });
+ }
+
+ enum { sep_size = 1 };
+
+ void on_num() {
+ std::string groups = grouping<Char>(locale);
+ if (groups.empty()) return on_dec();
+ auto sep = thousands_sep<Char>(locale);
+ if (!sep) return on_dec();
+ int num_digits = count_digits(abs_value);
+ int size = num_digits, n = num_digits;
+ std::string::const_iterator group = groups.cbegin();
+ while (group != groups.cend() && n > *group && *group > 0 &&
+ *group != max_value<char>()) {
+ size += sep_size;
+ n -= *group;
+ ++group;
+ }
+ if (group == groups.cend()) size += sep_size * ((n - 1) / groups.back());
+ char digits[40];
+ format_decimal(digits, abs_value, num_digits);
+ basic_memory_buffer<Char> buffer;
+ size += static_cast<int>(prefix_size);
+ const auto usize = to_unsigned(size);
+ buffer.resize(usize);
+ basic_string_view<Char> s(&sep, sep_size);
+ // Index of a decimal digit with the least significant digit having index 0.
+ int digit_index = 0;
+ group = groups.cbegin();
+ auto p = buffer.data() + size - 1;
+ for (int i = num_digits - 1; i > 0; --i) {
+ *p-- = static_cast<Char>(digits[i]);
+ if (*group <= 0 || ++digit_index % *group != 0 ||
+ *group == max_value<char>())
+ continue;
+ if (group + 1 != groups.cend()) {
+ digit_index = 0;
+ ++group;
+ }
+ std::uninitialized_copy(s.data(), s.data() + s.size(),
+ make_checked(p, s.size()));
+ p -= s.size();
+ }
+ *p-- = static_cast<Char>(*digits);
+ if (prefix_size != 0) *p = static_cast<Char>('-');
+ auto data = buffer.data();
+ out = write_padded<align::right>(
+ out, specs, usize, usize,
+ [=](iterator it) { return copy_str<Char>(data, data + size, it); });
+ }
+
+ void on_chr() { *out++ = static_cast<Char>(abs_value); }
+
+ FMT_NORETURN void on_error() {
+ FMT_THROW(format_error("invalid type specifier"));
+ }
+};
+
+template <typename Char, typename OutputIt>
+OutputIt write_nonfinite(OutputIt out, bool isinf,
+ const basic_format_specs<Char>& specs,
+ const float_specs& fspecs) {
+ auto str =
+ isinf ? (fspecs.upper ? "INF" : "inf") : (fspecs.upper ? "NAN" : "nan");
+ constexpr size_t str_size = 3;
+ auto sign = fspecs.sign;
+ auto size = str_size + (sign ? 1 : 0);
+ using iterator = remove_reference_t<decltype(reserve(out, 0))>;
+ return write_padded(out, specs, size, [=](iterator it) {
+ if (sign) *it++ = static_cast<Char>(data::signs[sign]);
+ return copy_str<Char>(str, str + str_size, it);
+ });
+}
+
+// A decimal floating-point number significand * pow(10, exp).
+struct big_decimal_fp {
+ const char* significand;
+ int significand_size;
+ int exponent;
+};
+
+inline int get_significand_size(const big_decimal_fp& fp) {
+ return fp.significand_size;
+}
+template <typename T>
+inline int get_significand_size(const dragonbox::decimal_fp<T>& fp) {
+ return count_digits(fp.significand);
+}
+
+template <typename Char, typename OutputIt>
+inline OutputIt write_significand(OutputIt out, const char* significand,
+ int& significand_size) {
+ return copy_str<Char>(significand, significand + significand_size, out);
+}
+template <typename Char, typename OutputIt, typename UInt>
+inline OutputIt write_significand(OutputIt out, UInt significand,
+ int significand_size) {
+ return format_decimal<Char>(out, significand, significand_size).end;
+}
+
+template <typename Char, typename UInt,
+ FMT_ENABLE_IF(std::is_integral<UInt>::value)>
+inline Char* write_significand(Char* out, UInt significand,
+ int significand_size, int integral_size,
+ Char decimal_point) {
+ if (!decimal_point)
+ return format_decimal(out, significand, significand_size).end;
+ auto end = format_decimal(out + 1, significand, significand_size).end;
+ if (integral_size == 1)
+ out[0] = out[1];
+ else
+ std::copy_n(out + 1, integral_size, out);
+ out[integral_size] = decimal_point;
+ return end;
+}
+
+template <typename OutputIt, typename UInt, typename Char,
+ FMT_ENABLE_IF(!std::is_pointer<remove_cvref_t<OutputIt>>::value)>
+inline OutputIt write_significand(OutputIt out, UInt significand,
+ int significand_size, int integral_size,
+ Char decimal_point) {
+ // Buffer is large enough to hold digits (digits10 + 1) and a decimal point.
+ Char buffer[digits10<UInt>() + 2];
+ auto end = write_significand(buffer, significand, significand_size,
+ integral_size, decimal_point);
+ return detail::copy_str<Char>(buffer, end, out);
+}
+
+template <typename OutputIt, typename Char>
+inline OutputIt write_significand(OutputIt out, const char* significand,
+ int significand_size, int integral_size,
+ Char decimal_point) {
+ out = detail::copy_str<Char>(significand, significand + integral_size, out);
+ if (!decimal_point) return out;
+ *out++ = decimal_point;
+ return detail::copy_str<Char>(significand + integral_size,
+ significand + significand_size, out);
+}
+
+template <typename OutputIt, typename DecimalFP, typename Char>
+OutputIt write_float(OutputIt out, const DecimalFP& fp,
+ const basic_format_specs<Char>& specs, float_specs fspecs,
+ Char decimal_point) {
+ auto significand = fp.significand;
+ int significand_size = get_significand_size(fp);
+ static const Char zero = static_cast<Char>('0');
+ auto sign = fspecs.sign;
+ size_t size = to_unsigned(significand_size) + (sign ? 1 : 0);
+ using iterator = remove_reference_t<decltype(reserve(out, 0))>;
+
+ int output_exp = fp.exponent + significand_size - 1;
+ auto use_exp_format = [=]() {
+ if (fspecs.format == float_format::exp) return true;
+ if (fspecs.format != float_format::general) return false;
+ // Use the fixed notation if the exponent is in [exp_lower, exp_upper),
+ // e.g. 0.0001 instead of 1e-04. Otherwise use the exponent notation.
+ const int exp_lower = -4, exp_upper = 16;
+ return output_exp < exp_lower ||
+ output_exp >= (fspecs.precision > 0 ? fspecs.precision : exp_upper);
+ };
+ if (use_exp_format()) {
+ int num_zeros = 0;
+ if (fspecs.showpoint) {
+ num_zeros = (std::max)(fspecs.precision - significand_size, 0);
+ size += to_unsigned(num_zeros);
+ } else if (significand_size == 1) {
+ decimal_point = Char();
+ }
+ auto abs_output_exp = output_exp >= 0 ? output_exp : -output_exp;
+ int exp_digits = 2;
+ if (abs_output_exp >= 100) exp_digits = abs_output_exp >= 1000 ? 4 : 3;
+
+ size += to_unsigned((decimal_point ? 1 : 0) + 2 + exp_digits);
+ char exp_char = fspecs.upper ? 'E' : 'e';
+ auto write = [=](iterator it) {
+ if (sign) *it++ = static_cast<Char>(data::signs[sign]);
+ // Insert a decimal point after the first digit and add an exponent.
+ it = write_significand(it, significand, significand_size, 1,
+ decimal_point);
+ if (num_zeros > 0) it = std::fill_n(it, num_zeros, zero);
+ *it++ = static_cast<Char>(exp_char);
+ return write_exponent<Char>(output_exp, it);
+ };
+ return specs.width > 0 ? write_padded<align::right>(out, specs, size, write)
+ : base_iterator(out, write(reserve(out, size)));
+ }
+
+ int exp = fp.exponent + significand_size;
+ if (fp.exponent >= 0) {
+ // 1234e5 -> 123400000[.0+]
+ size += to_unsigned(fp.exponent);
+ int num_zeros = fspecs.precision - exp;
+#ifdef FMT_FUZZ
+ if (num_zeros > 5000)
+ throw std::runtime_error("fuzz mode - avoiding excessive cpu use");
+#endif
+ if (fspecs.showpoint) {
+ if (num_zeros <= 0 && fspecs.format != float_format::fixed) num_zeros = 1;
+ if (num_zeros > 0) size += to_unsigned(num_zeros);
+ }
+ return write_padded<align::right>(out, specs, size, [&](iterator it) {
+ if (sign) *it++ = static_cast<Char>(data::signs[sign]);
+ it = write_significand<Char>(it, significand, significand_size);
+ it = std::fill_n(it, fp.exponent, zero);
+ if (!fspecs.showpoint) return it;
+ *it++ = decimal_point;
+ return num_zeros > 0 ? std::fill_n(it, num_zeros, zero) : it;
+ });
+ } else if (exp > 0) {
+ // 1234e-2 -> 12.34[0+]
+ int num_zeros = fspecs.showpoint ? fspecs.precision - significand_size : 0;
+ size += 1 + to_unsigned(num_zeros > 0 ? num_zeros : 0);
+ return write_padded<align::right>(out, specs, size, [&](iterator it) {
+ if (sign) *it++ = static_cast<Char>(data::signs[sign]);
+ it = write_significand(it, significand, significand_size, exp,
+ decimal_point);
+ return num_zeros > 0 ? std::fill_n(it, num_zeros, zero) : it;
+ });
+ }
+ // 1234e-6 -> 0.001234
+ int num_zeros = -exp;
+ if (significand_size == 0 && fspecs.precision >= 0 &&
+ fspecs.precision < num_zeros) {
+ num_zeros = fspecs.precision;
+ }
+ size += 2 + to_unsigned(num_zeros);
+ return write_padded<align::right>(out, specs, size, [&](iterator it) {
+ if (sign) *it++ = static_cast<Char>(data::signs[sign]);
+ *it++ = zero;
+ if (num_zeros == 0 && significand_size == 0 && !fspecs.showpoint) return it;
+ *it++ = decimal_point;
+ it = std::fill_n(it, num_zeros, zero);
+ return write_significand<Char>(it, significand, significand_size);
+ });
+}
+
+template <typename Char, typename OutputIt, typename T,
+ FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+OutputIt write(OutputIt out, T value, basic_format_specs<Char> specs,
+ locale_ref loc = {}) {
+ if (const_check(!is_supported_floating_point(value))) return out;
+ float_specs fspecs = parse_float_type_spec(specs);
+ fspecs.sign = specs.sign;
+ if (std::signbit(value)) { // value < 0 is false for NaN so use signbit.
+ fspecs.sign = sign::minus;
+ value = -value;
+ } else if (fspecs.sign == sign::minus) {
+ fspecs.sign = sign::none;
+ }
+
+ if (!std::isfinite(value))
+ return write_nonfinite(out, std::isinf(value), specs, fspecs);
+
+ if (specs.align == align::numeric && fspecs.sign) {
+ auto it = reserve(out, 1);
+ *it++ = static_cast<Char>(data::signs[fspecs.sign]);
+ out = base_iterator(out, it);
+ fspecs.sign = sign::none;
+ if (specs.width != 0) --specs.width;
+ }
+
+ memory_buffer buffer;
+ if (fspecs.format == float_format::hex) {
+ if (fspecs.sign) buffer.push_back(data::signs[fspecs.sign]);
+ snprintf_float(promote_float(value), specs.precision, fspecs, buffer);
+ return write_bytes(out, {buffer.data(), buffer.size()}, specs);
+ }
+ int precision = specs.precision >= 0 || !specs.type ? specs.precision : 6;
+ if (fspecs.format == float_format::exp) {
+ if (precision == max_value<int>())
+ FMT_THROW(format_error("number is too big"));
+ else
+ ++precision;
+ }
+ if (const_check(std::is_same<T, float>())) fspecs.binary32 = true;
+ fspecs.use_grisu = is_fast_float<T>();
+ int exp = format_float(promote_float(value), precision, fspecs, buffer);
+ fspecs.precision = precision;
+ Char point =
+ fspecs.locale ? decimal_point<Char>(loc) : static_cast<Char>('.');
+ auto fp = big_decimal_fp{buffer.data(), static_cast<int>(buffer.size()), exp};
+ return write_float(out, fp, specs, fspecs, point);
+}
+
+template <typename Char, typename OutputIt, typename T,
+ FMT_ENABLE_IF(is_fast_float<T>::value)>
+OutputIt write(OutputIt out, T value) {
+ if (const_check(!is_supported_floating_point(value))) return out;
+
+ using floaty = conditional_t<std::is_same<T, long double>::value, double, T>;
+ using uint = typename dragonbox::float_info<floaty>::carrier_uint;
+ auto bits = bit_cast<uint>(value);
+
+ auto fspecs = float_specs();
+ auto sign_bit = bits & (uint(1) << (num_bits<uint>() - 1));
+ if (sign_bit != 0) {
+ fspecs.sign = sign::minus;
+ value = -value;
+ }
+
+ static const auto specs = basic_format_specs<Char>();
+ uint mask = exponent_mask<floaty>();
+ if ((bits & mask) == mask)
+ return write_nonfinite(out, std::isinf(value), specs, fspecs);
+
+ auto dec = dragonbox::to_decimal(static_cast<floaty>(value));
+ return write_float(out, dec, specs, fspecs, static_cast<Char>('.'));
+}
+
+template <typename Char, typename OutputIt, typename T,
+ FMT_ENABLE_IF(std::is_floating_point<T>::value &&
+ !is_fast_float<T>::value)>
+inline OutputIt write(OutputIt out, T value) {
+ return write(out, value, basic_format_specs<Char>());
+}
+
+template <typename Char, typename OutputIt>
+OutputIt write_char(OutputIt out, Char value,
+ const basic_format_specs<Char>& specs) {
+ using iterator = remove_reference_t<decltype(reserve(out, 0))>;
+ return write_padded(out, specs, 1, [=](iterator it) {
+ *it++ = value;
+ return it;
+ });
+}
+
+template <typename Char, typename OutputIt, typename UIntPtr>
+OutputIt write_ptr(OutputIt out, UIntPtr value,
+ const basic_format_specs<Char>* specs) {
+ int num_digits = count_digits<4>(value);
+ auto size = to_unsigned(num_digits) + size_t(2);
+ using iterator = remove_reference_t<decltype(reserve(out, 0))>;
+ auto write = [=](iterator it) {
+ *it++ = static_cast<Char>('0');
+ *it++ = static_cast<Char>('x');
+ return format_uint<4, Char>(it, value, num_digits);
+ };
+ return specs ? write_padded<align::right>(out, *specs, size, write)
+ : base_iterator(out, write(reserve(out, size)));
+}
+
+template <typename T> struct is_integral : std::is_integral<T> {};
+template <> struct is_integral<int128_t> : std::true_type {};
+template <> struct is_integral<uint128_t> : std::true_type {};
+
+template <typename Char, typename OutputIt>
+OutputIt write(OutputIt out, monostate) {
+ FMT_ASSERT(false, "");
+ return out;
+}
+
+template <typename Char, typename OutputIt,
+ FMT_ENABLE_IF(!std::is_same<Char, char>::value)>
+OutputIt write(OutputIt out, string_view value) {
+ auto it = reserve(out, value.size());
+ it = copy_str<Char>(value.begin(), value.end(), it);
+ return base_iterator(out, it);
+}
+
+template <typename Char, typename OutputIt>
+OutputIt write(OutputIt out, basic_string_view<Char> value) {
+ auto it = reserve(out, value.size());
+ it = std::copy(value.begin(), value.end(), it);
+ return base_iterator(out, it);
+}
+
+template <typename Char>
+buffer_appender<Char> write(buffer_appender<Char> out,
+ basic_string_view<Char> value) {
+ get_container(out).append(value.begin(), value.end());
+ return out;
+}
+
+template <typename Char, typename OutputIt, typename T,
+ FMT_ENABLE_IF(is_integral<T>::value &&
+ !std::is_same<T, bool>::value &&
+ !std::is_same<T, Char>::value)>
+OutputIt write(OutputIt out, T value) {
+ auto abs_value = static_cast<uint32_or_64_or_128_t<T>>(value);
+ bool negative = is_negative(value);
+ // Don't do -abs_value since it trips unsigned-integer-overflow sanitizer.
+ if (negative) abs_value = ~abs_value + 1;
+ int num_digits = count_digits(abs_value);
+ auto size = (negative ? 1 : 0) + static_cast<size_t>(num_digits);
+ auto it = reserve(out, size);
+ if (auto ptr = to_pointer<Char>(it, size)) {
+ if (negative) *ptr++ = static_cast<Char>('-');
+ format_decimal<Char>(ptr, abs_value, num_digits);
+ return out;
+ }
+ if (negative) *it++ = static_cast<Char>('-');
+ it = format_decimal<Char>(it, abs_value, num_digits).end;
+ return base_iterator(out, it);
+}
+
+template <typename Char, typename OutputIt>
+OutputIt write(OutputIt out, bool value) {
+ return write<Char>(out, string_view(value ? "true" : "false"));
+}
+
+template <typename Char, typename OutputIt>
+OutputIt write(OutputIt out, Char value) {
+ auto it = reserve(out, 1);
+ *it++ = value;
+ return base_iterator(out, it);
+}
+
+template <typename Char, typename OutputIt>
+OutputIt write(OutputIt out, const Char* value) {
+ if (!value) {
+ FMT_THROW(format_error("string pointer is null"));
+ } else {
+ auto length = std::char_traits<Char>::length(value);
+ out = write(out, basic_string_view<Char>(value, length));
+ }
+ return out;
+}
+
+template <typename Char, typename OutputIt>
+OutputIt write(OutputIt out, const void* value) {
+ return write_ptr<Char>(out, to_uintptr(value), nullptr);
+}
+
+template <typename Char, typename OutputIt, typename T>
+auto write(OutputIt out, const T& value) -> typename std::enable_if<
+ mapped_type_constant<T, basic_format_context<OutputIt, Char>>::value ==
+ type::custom_type,
+ OutputIt>::type {
+ using context_type = basic_format_context<OutputIt, Char>;
+ using formatter_type =
+ conditional_t<has_formatter<T, context_type>::value,
+ typename context_type::template formatter_type<T>,
+ fallback_formatter<T, Char>>;
+ context_type ctx(out, {}, {});
+ return formatter_type().format(value, ctx);
+}
+
+// An argument visitor that formats the argument and writes it via the output
+// iterator. It's a class and not a generic lambda for compatibility with C++11.
+template <typename OutputIt, typename Char> struct default_arg_formatter {
+ using context = basic_format_context<OutputIt, Char>;
+
+ OutputIt out;
+ basic_format_args<context> args;
+ locale_ref loc;
+
+ template <typename T> OutputIt operator()(T value) {
+ return write<Char>(out, value);
+ }
+
+ OutputIt operator()(typename basic_format_arg<context>::handle handle) {
+ basic_format_parse_context<Char> parse_ctx({});
+ basic_format_context<OutputIt, Char> format_ctx(out, args, loc);
+ handle.format(parse_ctx, format_ctx);
+ return format_ctx.out();
+ }
+};
+
+template <typename OutputIt, typename Char,
+ typename ErrorHandler = error_handler>
+class arg_formatter_base {
+ public:
+ using iterator = OutputIt;
+ using char_type = Char;
+ using format_specs = basic_format_specs<Char>;
+
+ private:
+ iterator out_;
+ locale_ref locale_;
+ format_specs* specs_;
+
+ // Attempts to reserve space for n extra characters in the output range.
+ // Returns a pointer to the reserved range or a reference to out_.
+ auto reserve(size_t n) -> decltype(detail::reserve(out_, n)) {
+ return detail::reserve(out_, n);
+ }
+
+ using reserve_iterator = remove_reference_t<decltype(
+ detail::reserve(std::declval<iterator&>(), 0))>;
+
+ template <typename T> void write_int(T value, const format_specs& spec) {
+ using uint_type = uint32_or_64_or_128_t<T>;
+ int_writer<iterator, Char, uint_type> w(out_, locale_, value, spec);
+ handle_int_type_spec(spec.type, w);
+ out_ = w.out;
+ }
+
+ void write(char value) {
+ auto&& it = reserve(1);
+ *it++ = value;
+ }
+
+ template <typename Ch, FMT_ENABLE_IF(std::is_same<Ch, Char>::value)>
+ void write(Ch value) {
+ out_ = detail::write<Char>(out_, value);
+ }
+
+ void write(string_view value) {
+ auto&& it = reserve(value.size());
+ it = copy_str<Char>(value.begin(), value.end(), it);
+ }
+ void write(wstring_view value) {
+ static_assert(std::is_same<Char, wchar_t>::value, "");
+ auto&& it = reserve(value.size());
+ it = std::copy(value.begin(), value.end(), it);
+ }
+
+ template <typename Ch>
+ void write(const Ch* s, size_t size, const format_specs& specs) {
+ auto width = specs.width != 0
+ ? count_code_points(basic_string_view<Ch>(s, size))
+ : 0;
+ out_ = write_padded(out_, specs, size, width, [=](reserve_iterator it) {
+ return copy_str<Char>(s, s + size, it);
+ });
+ }
+
+ template <typename Ch>
+ void write(basic_string_view<Ch> s, const format_specs& specs = {}) {
+ out_ = detail::write(out_, s, specs);
+ }
+
+ void write_pointer(const void* p) {
+ out_ = write_ptr<char_type>(out_, to_uintptr(p), specs_);
+ }
+
+ struct char_spec_handler : ErrorHandler {
+ arg_formatter_base& formatter;
+ Char value;
+
+ char_spec_handler(arg_formatter_base& f, Char val)
+ : formatter(f), value(val) {}
+
+ void on_int() {
+ // char is only formatted as int if there are specs.
+ formatter.write_int(static_cast<int>(value), *formatter.specs_);
+ }
+ void on_char() {
+ if (formatter.specs_)
+ formatter.out_ = write_char(formatter.out_, value, *formatter.specs_);
+ else
+ formatter.write(value);
+ }
+ };
+
+ struct cstring_spec_handler : error_handler {
+ arg_formatter_base& formatter;
+ const Char* value;
+
+ cstring_spec_handler(arg_formatter_base& f, const Char* val)
+ : formatter(f), value(val) {}
+
+ void on_string() { formatter.write(value); }
+ void on_pointer() { formatter.write_pointer(value); }
+ };
+
+ protected:
+ iterator out() { return out_; }
+ format_specs* specs() { return specs_; }
+
+ void write(bool value) {
+ if (specs_)
+ write(string_view(value ? "true" : "false"), *specs_);
+ else
+ out_ = detail::write<Char>(out_, value);
+ }
+
+ void write(const Char* value) {
+ if (!value) {
+ FMT_THROW(format_error("string pointer is null"));
+ } else {
+ auto length = std::char_traits<char_type>::length(value);
+ basic_string_view<char_type> sv(value, length);
+ specs_ ? write(sv, *specs_) : write(sv);
+ }
+ }
+
+ public:
+ arg_formatter_base(OutputIt out, format_specs* s, locale_ref loc)
+ : out_(out), locale_(loc), specs_(s) {}
+
+ iterator operator()(monostate) {
+ FMT_ASSERT(false, "invalid argument type");
+ return out_;
+ }
+
+ template <typename T, FMT_ENABLE_IF(is_integral<T>::value)>
+ FMT_INLINE iterator operator()(T value) {
+ if (specs_)
+ write_int(value, *specs_);
+ else
+ out_ = detail::write<Char>(out_, value);
+ return out_;
+ }
+
+ iterator operator()(Char value) {
+ handle_char_specs(specs_,
+ char_spec_handler(*this, static_cast<Char>(value)));
+ return out_;
+ }
+
+ iterator operator()(bool value) {
+ if (specs_ && specs_->type) return (*this)(value ? 1 : 0);
+ write(value != 0);
+ return out_;
+ }
+
+ template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+ iterator operator()(T value) {
+ auto specs = specs_ ? *specs_ : format_specs();
+ if (const_check(is_supported_floating_point(value)))
+ out_ = detail::write(out_, value, specs, locale_);
+ else
+ FMT_ASSERT(false, "unsupported float argument type");
+ return out_;
+ }
+
+ iterator operator()(const Char* value) {
+ if (!specs_) return write(value), out_;
+ handle_cstring_type_spec(specs_->type, cstring_spec_handler(*this, value));
+ return out_;
+ }
+
+ iterator operator()(basic_string_view<Char> value) {
+ if (specs_) {
+ check_string_type_spec(specs_->type, error_handler());
+ write(value, *specs_);
+ } else {
+ write(value);
+ }
+ return out_;
+ }
+
+ iterator operator()(const void* value) {
+ if (specs_) check_pointer_type_spec(specs_->type, error_handler());
+ write_pointer(value);
+ return out_;
+ }
+};
+
+/** The default argument formatter. */
+template <typename OutputIt, typename Char>
+class arg_formatter : public arg_formatter_base<OutputIt, Char> {
+ private:
+ using char_type = Char;
+ using base = arg_formatter_base<OutputIt, Char>;
+ using context_type = basic_format_context<OutputIt, Char>;
+
+ context_type& ctx_;
+ basic_format_parse_context<char_type>* parse_ctx_;
+ const Char* ptr_;
+
+ public:
+ using iterator = typename base::iterator;
+ using format_specs = typename base::format_specs;
+
+ /**
+ \rst
+ Constructs an argument formatter object.
+ *ctx* is a reference to the formatting context,
+ *specs* contains format specifier information for standard argument types.
+ \endrst
+ */
+ explicit arg_formatter(
+ context_type& ctx,
+ basic_format_parse_context<char_type>* parse_ctx = nullptr,
+ format_specs* specs = nullptr, const Char* ptr = nullptr)
+ : base(ctx.out(), specs, ctx.locale()),
+ ctx_(ctx),
+ parse_ctx_(parse_ctx),
+ ptr_(ptr) {}
+
+ using base::operator();
+
+ /** Formats an argument of a user-defined type. */
+ iterator operator()(typename basic_format_arg<context_type>::handle handle) {
+ if (ptr_) advance_to(*parse_ctx_, ptr_);
+ handle.format(*parse_ctx_, ctx_);
+ return ctx_.out();
+ }
+};
+
+template <typename Char> FMT_CONSTEXPR bool is_name_start(Char c) {
+ return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || '_' == c;
+}
+
+// Parses the range [begin, end) as an unsigned integer. This function assumes
+// that the range is non-empty and the first character is a digit.
+template <typename Char, typename ErrorHandler>
+FMT_CONSTEXPR int parse_nonnegative_int(const Char*& begin, const Char* end,
+ ErrorHandler&& eh) {
+ FMT_ASSERT(begin != end && '0' <= *begin && *begin <= '9', "");
+ unsigned value = 0;
+ // Convert to unsigned to prevent a warning.
+ constexpr unsigned max_int = max_value<int>();
+ unsigned big = max_int / 10;
+ do {
+ // Check for overflow.
+ if (value > big) {
+ value = max_int + 1;
+ break;
+ }
+ value = value * 10 + unsigned(*begin - '0');
+ ++begin;
+ } while (begin != end && '0' <= *begin && *begin <= '9');
+ if (value > max_int) eh.on_error("number is too big");
+ return static_cast<int>(value);
+}
+
+template <typename Context> class custom_formatter {
+ private:
+ using char_type = typename Context::char_type;
+
+ basic_format_parse_context<char_type>& parse_ctx_;
+ Context& ctx_;
+
+ public:
+ explicit custom_formatter(basic_format_parse_context<char_type>& parse_ctx,
+ Context& ctx)
+ : parse_ctx_(parse_ctx), ctx_(ctx) {}
+
+ void operator()(typename basic_format_arg<Context>::handle h) const {
+ h.format(parse_ctx_, ctx_);
+ }
+
+ template <typename T> void operator()(T) const {}
+};
+
+template <typename T>
+using is_integer =
+ bool_constant<is_integral<T>::value && !std::is_same<T, bool>::value &&
+ !std::is_same<T, char>::value &&
+ !std::is_same<T, wchar_t>::value>;
+
+template <typename ErrorHandler> class width_checker {
+ public:
+ explicit FMT_CONSTEXPR width_checker(ErrorHandler& eh) : handler_(eh) {}
+
+ template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T value) {
+ if (is_negative(value)) handler_.on_error("negative width");
+ return static_cast<unsigned long long>(value);
+ }
+
+ template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T) {
+ handler_.on_error("width is not integer");
+ return 0;
+ }
+
+ private:
+ ErrorHandler& handler_;
+};
+
+template <typename ErrorHandler> class precision_checker {
+ public:
+ explicit FMT_CONSTEXPR precision_checker(ErrorHandler& eh) : handler_(eh) {}
+
+ template <typename T, FMT_ENABLE_IF(is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T value) {
+ if (is_negative(value)) handler_.on_error("negative precision");
+ return static_cast<unsigned long long>(value);
+ }
+
+ template <typename T, FMT_ENABLE_IF(!is_integer<T>::value)>
+ FMT_CONSTEXPR unsigned long long operator()(T) {
+ handler_.on_error("precision is not integer");
+ return 0;
+ }
+
+ private:
+ ErrorHandler& handler_;
+};
+
+// A format specifier handler that sets fields in basic_format_specs.
+template <typename Char> class specs_setter {
+ public:
+ explicit FMT_CONSTEXPR specs_setter(basic_format_specs<Char>& specs)
+ : specs_(specs) {}
+
+ FMT_CONSTEXPR specs_setter(const specs_setter& other)
+ : specs_(other.specs_) {}
+
+ FMT_CONSTEXPR void on_align(align_t align) { specs_.align = align; }
+ FMT_CONSTEXPR void on_fill(basic_string_view<Char> fill) {
+ specs_.fill = fill;
+ }
+ FMT_CONSTEXPR void on_plus() { specs_.sign = sign::plus; }
+ FMT_CONSTEXPR void on_minus() { specs_.sign = sign::minus; }
+ FMT_CONSTEXPR void on_space() { specs_.sign = sign::space; }
+ FMT_CONSTEXPR void on_hash() { specs_.alt = true; }
+
+ FMT_CONSTEXPR void on_zero() {
+ specs_.align = align::numeric;
+ specs_.fill[0] = Char('0');
+ }
+
+ FMT_CONSTEXPR void on_width(int width) { specs_.width = width; }
+ FMT_CONSTEXPR void on_precision(int precision) {
+ specs_.precision = precision;
+ }
+ FMT_CONSTEXPR void end_precision() {}
+
+ FMT_CONSTEXPR void on_type(Char type) {
+ specs_.type = static_cast<char>(type);
+ }
+
+ protected:
+ basic_format_specs<Char>& specs_;
+};
+
+template <typename ErrorHandler> class numeric_specs_checker {
+ public:
+ FMT_CONSTEXPR numeric_specs_checker(ErrorHandler& eh, detail::type arg_type)
+ : error_handler_(eh), arg_type_(arg_type) {}
+
+ FMT_CONSTEXPR void require_numeric_argument() {
+ if (!is_arithmetic_type(arg_type_))
+ error_handler_.on_error("format specifier requires numeric argument");
+ }
+
+ FMT_CONSTEXPR void check_sign() {
+ require_numeric_argument();
+ if (is_integral_type(arg_type_) && arg_type_ != type::int_type &&
+ arg_type_ != type::long_long_type && arg_type_ != type::char_type) {
+ error_handler_.on_error("format specifier requires signed argument");
+ }
+ }
+
+ FMT_CONSTEXPR void check_precision() {
+ if (is_integral_type(arg_type_) || arg_type_ == type::pointer_type)
+ error_handler_.on_error("precision not allowed for this argument type");
+ }
+
+ private:
+ ErrorHandler& error_handler_;
+ detail::type arg_type_;
+};
+
+// A format specifier handler that checks if specifiers are consistent with the
+// argument type.
+template <typename Handler> class specs_checker : public Handler {
+ private:
+ numeric_specs_checker<Handler> checker_;
+
+ // Suppress an MSVC warning about using this in initializer list.
+ FMT_CONSTEXPR Handler& error_handler() { return *this; }
+
+ public:
+ FMT_CONSTEXPR specs_checker(const Handler& handler, detail::type arg_type)
+ : Handler(handler), checker_(error_handler(), arg_type) {}
+
+ FMT_CONSTEXPR specs_checker(const specs_checker& other)
+ : Handler(other), checker_(error_handler(), other.arg_type_) {}
+
+ FMT_CONSTEXPR void on_align(align_t align) {
+ if (align == align::numeric) checker_.require_numeric_argument();
+ Handler::on_align(align);
+ }
+
+ FMT_CONSTEXPR void on_plus() {
+ checker_.check_sign();
+ Handler::on_plus();
+ }
+
+ FMT_CONSTEXPR void on_minus() {
+ checker_.check_sign();
+ Handler::on_minus();
+ }
+
+ FMT_CONSTEXPR void on_space() {
+ checker_.check_sign();
+ Handler::on_space();
+ }
+
+ FMT_CONSTEXPR void on_hash() {
+ checker_.require_numeric_argument();
+ Handler::on_hash();
+ }
+
+ FMT_CONSTEXPR void on_zero() {
+ checker_.require_numeric_argument();
+ Handler::on_zero();
+ }
+
+ FMT_CONSTEXPR void end_precision() { checker_.check_precision(); }
+};
+
+template <template <typename> class Handler, typename FormatArg,
+ typename ErrorHandler>
+FMT_CONSTEXPR int get_dynamic_spec(FormatArg arg, ErrorHandler eh) {
+ unsigned long long value = visit_format_arg(Handler<ErrorHandler>(eh), arg);
+ if (value > to_unsigned(max_value<int>())) eh.on_error("number is too big");
+ return static_cast<int>(value);
+}
+
+struct auto_id {};
+
+template <typename Context, typename ID>
+FMT_CONSTEXPR typename Context::format_arg get_arg(Context& ctx, ID id) {
+ auto arg = ctx.arg(id);
+ if (!arg) ctx.on_error("argument not found");
+ return arg;
+}
+
+// The standard format specifier handler with checking.
+template <typename ParseContext, typename Context>
+class specs_handler : public specs_setter<typename Context::char_type> {
+ public:
+ using char_type = typename Context::char_type;
+
+ FMT_CONSTEXPR specs_handler(basic_format_specs<char_type>& specs,
+ ParseContext& parse_ctx, Context& ctx)
+ : specs_setter<char_type>(specs),
+ parse_context_(parse_ctx),
+ context_(ctx) {}
+
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
+ this->specs_.width = get_dynamic_spec<width_checker>(
+ get_arg(arg_id), context_.error_handler());
+ }
+
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
+ this->specs_.precision = get_dynamic_spec<precision_checker>(
+ get_arg(arg_id), context_.error_handler());
+ }
+
+ void on_error(const char* message) { context_.on_error(message); }
+
+ private:
+ // This is only needed for compatibility with gcc 4.4.
+ using format_arg = typename Context::format_arg;
+
+ FMT_CONSTEXPR format_arg get_arg(auto_id) {
+ return detail::get_arg(context_, parse_context_.next_arg_id());
+ }
+
+ FMT_CONSTEXPR format_arg get_arg(int arg_id) {
+ parse_context_.check_arg_id(arg_id);
+ return detail::get_arg(context_, arg_id);
+ }
+
+ FMT_CONSTEXPR format_arg get_arg(basic_string_view<char_type> arg_id) {
+ parse_context_.check_arg_id(arg_id);
+ return detail::get_arg(context_, arg_id);
+ }
+
+ ParseContext& parse_context_;
+ Context& context_;
+};
+
+enum class arg_id_kind { none, index, name };
+
+// An argument reference.
+template <typename Char> struct arg_ref {
+ FMT_CONSTEXPR arg_ref() : kind(arg_id_kind::none), val() {}
+
+ FMT_CONSTEXPR explicit arg_ref(int index)
+ : kind(arg_id_kind::index), val(index) {}
+ FMT_CONSTEXPR explicit arg_ref(basic_string_view<Char> name)
+ : kind(arg_id_kind::name), val(name) {}
+
+ FMT_CONSTEXPR arg_ref& operator=(int idx) {
+ kind = arg_id_kind::index;
+ val.index = idx;
+ return *this;
+ }
+
+ arg_id_kind kind;
+ union value {
+ FMT_CONSTEXPR value(int id = 0) : index{id} {}
+ FMT_CONSTEXPR value(basic_string_view<Char> n) : name(n) {}
+
+ int index;
+ basic_string_view<Char> name;
+ } val;
+};
+
+// Format specifiers with width and precision resolved at formatting rather
+// than parsing time to allow re-using the same parsed specifiers with
+// different sets of arguments (precompilation of format strings).
+template <typename Char>
+struct dynamic_format_specs : basic_format_specs<Char> {
+ arg_ref<Char> width_ref;
+ arg_ref<Char> precision_ref;
+};
+
+// Format spec handler that saves references to arguments representing dynamic
+// width and precision to be resolved at formatting time.
+template <typename ParseContext>
+class dynamic_specs_handler
+ : public specs_setter<typename ParseContext::char_type> {
+ public:
+ using char_type = typename ParseContext::char_type;
+
+ FMT_CONSTEXPR dynamic_specs_handler(dynamic_format_specs<char_type>& specs,
+ ParseContext& ctx)
+ : specs_setter<char_type>(specs), specs_(specs), context_(ctx) {}
+
+ FMT_CONSTEXPR dynamic_specs_handler(const dynamic_specs_handler& other)
+ : specs_setter<char_type>(other),
+ specs_(other.specs_),
+ context_(other.context_) {}
+
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_width(Id arg_id) {
+ specs_.width_ref = make_arg_ref(arg_id);
+ }
+
+ template <typename Id> FMT_CONSTEXPR void on_dynamic_precision(Id arg_id) {
+ specs_.precision_ref = make_arg_ref(arg_id);
+ }
+
+ FMT_CONSTEXPR void on_error(const char* message) {
+ context_.on_error(message);
+ }
+
+ private:
+ using arg_ref_type = arg_ref<char_type>;
+
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(int arg_id) {
+ context_.check_arg_id(arg_id);
+ return arg_ref_type(arg_id);
+ }
+
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(auto_id) {
+ return arg_ref_type(context_.next_arg_id());
+ }
+
+ FMT_CONSTEXPR arg_ref_type make_arg_ref(basic_string_view<char_type> arg_id) {
+ context_.check_arg_id(arg_id);
+ basic_string_view<char_type> format_str(
+ context_.begin(), to_unsigned(context_.end() - context_.begin()));
+ return arg_ref_type(arg_id);
+ }
+
+ dynamic_format_specs<char_type>& specs_;
+ ParseContext& context_;
+};
+
+template <typename Char, typename IDHandler>
+FMT_CONSTEXPR const Char* parse_arg_id(const Char* begin, const Char* end,
+ IDHandler&& handler) {
+ FMT_ASSERT(begin != end, "");
+ Char c = *begin;
+ if (c == '}' || c == ':') {
+ handler();
+ return begin;
+ }
+ if (c >= '0' && c <= '9') {
+ int index = 0;
+ if (c != '0')
+ index = parse_nonnegative_int(begin, end, handler);
+ else
+ ++begin;
+ if (begin == end || (*begin != '}' && *begin != ':'))
+ handler.on_error("invalid format string");
+ else
+ handler(index);
+ return begin;
+ }
+ if (!is_name_start(c)) {
+ handler.on_error("invalid format string");
+ return begin;
+ }
+ auto it = begin;
+ do {
+ ++it;
+ } while (it != end && (is_name_start(c = *it) || ('0' <= c && c <= '9')));
+ handler(basic_string_view<Char>(begin, to_unsigned(it - begin)));
+ return it;
+}
+
+// Adapts SpecHandler to IDHandler API for dynamic width.
+template <typename SpecHandler, typename Char> struct width_adapter {
+ explicit FMT_CONSTEXPR width_adapter(SpecHandler& h) : handler(h) {}
+
+ FMT_CONSTEXPR void operator()() { handler.on_dynamic_width(auto_id()); }
+ FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_width(id); }
+ FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
+ handler.on_dynamic_width(id);
+ }
+
+ FMT_CONSTEXPR void on_error(const char* message) {
+ handler.on_error(message);
+ }
+
+ SpecHandler& handler;
+};
+
+// Adapts SpecHandler to IDHandler API for dynamic precision.
+template <typename SpecHandler, typename Char> struct precision_adapter {
+ explicit FMT_CONSTEXPR precision_adapter(SpecHandler& h) : handler(h) {}
+
+ FMT_CONSTEXPR void operator()() { handler.on_dynamic_precision(auto_id()); }
+ FMT_CONSTEXPR void operator()(int id) { handler.on_dynamic_precision(id); }
+ FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
+ handler.on_dynamic_precision(id);
+ }
+
+ FMT_CONSTEXPR void on_error(const char* message) {
+ handler.on_error(message);
+ }
+
+ SpecHandler& handler;
+};
+
+template <typename Char>
+FMT_CONSTEXPR int code_point_length(const Char* begin) {
+ if (const_check(sizeof(Char) != 1)) return 1;
+ constexpr char lengths[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+ 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 2, 2, 3, 3, 4, 0};
+ int len = lengths[static_cast<unsigned char>(*begin) >> 3];
+
+ // Compute the pointer to the next character early so that the next
+ // iteration can start working on the next character. Neither Clang
+ // nor GCC figure out this reordering on their own.
+ return len + !len;
+}
+
+template <typename Char> constexpr bool is_ascii_letter(Char c) {
+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z');
+}
+
+// Converts a character to ASCII. Returns a number > 127 on conversion failure.
+template <typename Char, FMT_ENABLE_IF(std::is_integral<Char>::value)>
+constexpr Char to_ascii(Char value) {
+ return value;
+}
+template <typename Char, FMT_ENABLE_IF(std::is_enum<Char>::value)>
+constexpr typename std::underlying_type<Char>::type to_ascii(Char value) {
+ return value;
+}
+
+// Parses fill and alignment.
+template <typename Char, typename Handler>
+FMT_CONSTEXPR const Char* parse_align(const Char* begin, const Char* end,
+ Handler&& handler) {
+ FMT_ASSERT(begin != end, "");
+ auto align = align::none;
+ auto p = begin + code_point_length(begin);
+ if (p >= end) p = begin;
+ for (;;) {
+ switch (to_ascii(*p)) {
+ case '<':
+ align = align::left;
+ break;
+ case '>':
+ align = align::right;
+ break;
+#if FMT_DEPRECATED_NUMERIC_ALIGN
+ case '=':
+ align = align::numeric;
+ break;
+#endif
+ case '^':
+ align = align::center;
+ break;
+ }
+ if (align != align::none) {
+ if (p != begin) {
+ auto c = *begin;
+ if (c == '{')
+ return handler.on_error("invalid fill character '{'"), begin;
+ handler.on_fill(basic_string_view<Char>(begin, to_unsigned(p - begin)));
+ begin = p + 1;
+ } else
+ ++begin;
+ handler.on_align(align);
+ break;
+ } else if (p == begin) {
+ break;
+ }
+ p = begin;
+ }
+ return begin;
+}
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR const Char* parse_width(const Char* begin, const Char* end,
+ Handler&& handler) {
+ FMT_ASSERT(begin != end, "");
+ if ('0' <= *begin && *begin <= '9') {
+ handler.on_width(parse_nonnegative_int(begin, end, handler));
+ } else if (*begin == '{') {
+ ++begin;
+ if (begin != end)
+ begin = parse_arg_id(begin, end, width_adapter<Handler, Char>(handler));
+ if (begin == end || *begin != '}')
+ return handler.on_error("invalid format string"), begin;
+ ++begin;
+ }
+ return begin;
+}
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR const Char* parse_precision(const Char* begin, const Char* end,
+ Handler&& handler) {
+ ++begin;
+ auto c = begin != end ? *begin : Char();
+ if ('0' <= c && c <= '9') {
+ handler.on_precision(parse_nonnegative_int(begin, end, handler));
+ } else if (c == '{') {
+ ++begin;
+ if (begin != end) {
+ begin =
+ parse_arg_id(begin, end, precision_adapter<Handler, Char>(handler));
+ }
+ if (begin == end || *begin++ != '}')
+ return handler.on_error("invalid format string"), begin;
+ } else {
+ return handler.on_error("missing precision specifier"), begin;
+ }
+ handler.end_precision();
+ return begin;
+}
+
+// Parses standard format specifiers and sends notifications about parsed
+// components to handler.
+template <typename Char, typename SpecHandler>
+FMT_CONSTEXPR const Char* parse_format_specs(const Char* begin, const Char* end,
+ SpecHandler&& handler) {
+ if (begin == end) return begin;
+
+ begin = parse_align(begin, end, handler);
+ if (begin == end) return begin;
+
+ // Parse sign.
+ switch (to_ascii(*begin)) {
+ case '+':
+ handler.on_plus();
+ ++begin;
+ break;
+ case '-':
+ handler.on_minus();
+ ++begin;
+ break;
+ case ' ':
+ handler.on_space();
+ ++begin;
+ break;
+ }
+ if (begin == end) return begin;
+
+ if (*begin == '#') {
+ handler.on_hash();
+ if (++begin == end) return begin;
+ }
+
+ // Parse zero flag.
+ if (*begin == '0') {
+ handler.on_zero();
+ if (++begin == end) return begin;
+ }
+
+ begin = parse_width(begin, end, handler);
+ if (begin == end) return begin;
+
+ // Parse precision.
+ if (*begin == '.') {
+ begin = parse_precision(begin, end, handler);
+ }
+
+ // Parse type.
+ if (begin != end && *begin != '}') handler.on_type(*begin++);
+ return begin;
+}
+
+// Return the result via the out param to workaround gcc bug 77539.
+template <bool IS_CONSTEXPR, typename T, typename Ptr = const T*>
+FMT_CONSTEXPR bool find(Ptr first, Ptr last, T value, Ptr& out) {
+ for (out = first; out != last; ++out) {
+ if (*out == value) return true;
+ }
+ return false;
+}
+
+template <>
+inline bool find<false, char>(const char* first, const char* last, char value,
+ const char*& out) {
+ out = static_cast<const char*>(
+ std::memchr(first, value, detail::to_unsigned(last - first)));
+ return out != nullptr;
+}
+
+template <typename Handler, typename Char> struct id_adapter {
+ Handler& handler;
+ int arg_id;
+
+ FMT_CONSTEXPR void operator()() { arg_id = handler.on_arg_id(); }
+ FMT_CONSTEXPR void operator()(int id) { arg_id = handler.on_arg_id(id); }
+ FMT_CONSTEXPR void operator()(basic_string_view<Char> id) {
+ arg_id = handler.on_arg_id(id);
+ }
+ FMT_CONSTEXPR void on_error(const char* message) {
+ handler.on_error(message);
+ }
+};
+
+template <typename Char, typename Handler>
+FMT_CONSTEXPR const Char* parse_replacement_field(const Char* begin,
+ const Char* end,
+ Handler&& handler) {
+ ++begin;
+ if (begin == end) return handler.on_error("invalid format string"), end;
+ if (*begin == '}') {
+ handler.on_replacement_field(handler.on_arg_id(), begin);
+ } else if (*begin == '{') {
+ handler.on_text(begin, begin + 1);
+ } else {
+ auto adapter = id_adapter<Handler, Char>{handler, 0};
+ begin = parse_arg_id(begin, end, adapter);
+ Char c = begin != end ? *begin : Char();
+ if (c == '}') {
+ handler.on_replacement_field(adapter.arg_id, begin);
+ } else if (c == ':') {
+ begin = handler.on_format_specs(adapter.arg_id, begin + 1, end);
+ if (begin == end || *begin != '}')
+ return handler.on_error("unknown format specifier"), end;
+ } else {
+ return handler.on_error("missing '}' in format string"), end;
+ }
+ }
+ return begin + 1;
+}
+
+template <bool IS_CONSTEXPR, typename Char, typename Handler>
+FMT_CONSTEXPR_DECL FMT_INLINE void parse_format_string(
+ basic_string_view<Char> format_str, Handler&& handler) {
+ auto begin = format_str.data();
+ auto end = begin + format_str.size();
+ if (end - begin < 32) {
+ // Use a simple loop instead of memchr for small strings.
+ const Char* p = begin;
+ while (p != end) {
+ auto c = *p++;
+ if (c == '{') {
+ handler.on_text(begin, p - 1);
+ begin = p = parse_replacement_field(p - 1, end, handler);
+ } else if (c == '}') {
+ if (p == end || *p != '}')
+ return handler.on_error("unmatched '}' in format string");
+ handler.on_text(begin, p);
+ begin = ++p;
+ }
+ }
+ handler.on_text(begin, end);
+ return;
+ }
+ struct writer {
+ FMT_CONSTEXPR void operator()(const Char* pbegin, const Char* pend) {
+ if (pbegin == pend) return;
+ for (;;) {
+ const Char* p = nullptr;
+ if (!find<IS_CONSTEXPR>(pbegin, pend, '}', p))
+ return handler_.on_text(pbegin, pend);
+ ++p;
+ if (p == pend || *p != '}')
+ return handler_.on_error("unmatched '}' in format string");
+ handler_.on_text(pbegin, p);
+ pbegin = p + 1;
+ }
+ }
+ Handler& handler_;
+ } write{handler};
+ while (begin != end) {
+ // Doing two passes with memchr (one for '{' and another for '}') is up to
+ // 2.5x faster than the naive one-pass implementation on big format strings.
+ const Char* p = begin;
+ if (*begin != '{' && !find<IS_CONSTEXPR>(begin + 1, end, '{', p))
+ return write(begin, end);
+ write(begin, p);
+ begin = parse_replacement_field(p, end, handler);
+ }
+}
+
+template <typename T, typename ParseContext>
+FMT_CONSTEXPR const typename ParseContext::char_type* parse_format_specs(
+ ParseContext& ctx) {
+ using char_type = typename ParseContext::char_type;
+ using context = buffer_context<char_type>;
+ using mapped_type =
+ conditional_t<detail::mapped_type_constant<T, context>::value !=
+ type::custom_type,
+ decltype(arg_mapper<context>().map(std::declval<T>())), T>;
+ auto f = conditional_t<has_formatter<mapped_type, context>::value,
+ formatter<mapped_type, char_type>,
+ detail::fallback_formatter<T, char_type>>();
+ return f.parse(ctx);
+}
+
+template <typename OutputIt, typename Char, typename Context>
+struct format_handler : detail::error_handler {
+ basic_format_parse_context<Char> parse_context;
+ Context context;
+
+ format_handler(OutputIt out, basic_string_view<Char> str,
+ basic_format_args<Context> format_args, detail::locale_ref loc)
+ : parse_context(str), context(out, format_args, loc) {}
+
+ void on_text(const Char* begin, const Char* end) {
+ auto size = to_unsigned(end - begin);
+ auto out = context.out();
+ auto&& it = reserve(out, size);
+ it = std::copy_n(begin, size, it);
+ context.advance_to(out);
+ }
+
+ int on_arg_id() { return parse_context.next_arg_id(); }
+ int on_arg_id(int id) { return parse_context.check_arg_id(id), id; }
+ int on_arg_id(basic_string_view<Char> id) {
+ int arg_id = context.arg_id(id);
+ if (arg_id < 0) on_error("argument not found");
+ return arg_id;
+ }
+
+ FMT_INLINE void on_replacement_field(int id, const Char*) {
+ auto arg = get_arg(context, id);
+ context.advance_to(visit_format_arg(
+ default_arg_formatter<OutputIt, Char>{context.out(), context.args(),
+ context.locale()},
+ arg));
+ }
+
+ const Char* on_format_specs(int id, const Char* begin, const Char* end) {
+ auto arg = get_arg(context, id);
+ if (arg.type() == type::custom_type) {
+ advance_to(parse_context, begin);
+ visit_format_arg(custom_formatter<Context>(parse_context, context), arg);
+ return parse_context.begin();
+ }
+ auto specs = basic_format_specs<Char>();
+ if (begin + 1 < end && begin[1] == '}' && is_ascii_letter(*begin)) {
+ specs.type = static_cast<char>(*begin++);
+ } else {
+ using parse_context_t = basic_format_parse_context<Char>;
+ specs_checker<specs_handler<parse_context_t, Context>> handler(
+ specs_handler<parse_context_t, Context>(specs, parse_context,
+ context),
+ arg.type());
+ begin = parse_format_specs(begin, end, handler);
+ if (begin == end || *begin != '}')
+ on_error("missing '}' in format string");
+ }
+ context.advance_to(visit_format_arg(
+ arg_formatter<OutputIt, Char>(context, &parse_context, &specs), arg));
+ return begin;
+ }
+};
+
+// A parse context with extra argument id checks. It is only used at compile
+// time because adding checks at runtime would introduce substantial overhead
+// and would be redundant since argument ids are checked when arguments are
+// retrieved anyway.
+template <typename Char, typename ErrorHandler = error_handler>
+class compile_parse_context
+ : public basic_format_parse_context<Char, ErrorHandler> {
+ private:
+ int num_args_;
+ using base = basic_format_parse_context<Char, ErrorHandler>;
+
+ public:
+ explicit FMT_CONSTEXPR compile_parse_context(
+ basic_string_view<Char> format_str, int num_args = max_value<int>(),
+ ErrorHandler eh = {})
+ : base(format_str, eh), num_args_(num_args) {}
+
+ FMT_CONSTEXPR int next_arg_id() {
+ int id = base::next_arg_id();
+ if (id >= num_args_) this->on_error("argument not found");
+ return id;
+ }
+
+ FMT_CONSTEXPR void check_arg_id(int id) {
+ base::check_arg_id(id);
+ if (id >= num_args_) this->on_error("argument not found");
+ }
+ using base::check_arg_id;
+};
+
+template <typename Char, typename ErrorHandler, typename... Args>
+class format_string_checker {
+ public:
+ explicit FMT_CONSTEXPR format_string_checker(
+ basic_string_view<Char> format_str, ErrorHandler eh)
+ : context_(format_str, num_args, eh),
+ parse_funcs_{&parse_format_specs<Args, parse_context_type>...} {}
+
+ FMT_CONSTEXPR void on_text(const Char*, const Char*) {}
+
+ FMT_CONSTEXPR int on_arg_id() { return context_.next_arg_id(); }
+ FMT_CONSTEXPR int on_arg_id(int id) { return context_.check_arg_id(id), id; }
+ FMT_CONSTEXPR int on_arg_id(basic_string_view<Char>) {
+ on_error("compile-time checks don't support named arguments");
+ return 0;
+ }
+
+ FMT_CONSTEXPR void on_replacement_field(int, const Char*) {}
+
+ FMT_CONSTEXPR const Char* on_format_specs(int id, const Char* begin,
+ const Char*) {
+ advance_to(context_, begin);
+ return id < num_args ? parse_funcs_[id](context_) : begin;
+ }
+
+ FMT_CONSTEXPR void on_error(const char* message) {
+ context_.on_error(message);
+ }
+
+ private:
+ using parse_context_type = compile_parse_context<Char, ErrorHandler>;
+ enum { num_args = sizeof...(Args) };
+
+ // Format specifier parsing function.
+ using parse_func = const Char* (*)(parse_context_type&);
+
+ parse_context_type context_;
+ parse_func parse_funcs_[num_args > 0 ? num_args : 1];
+};
+
+// Converts string literals to basic_string_view.
+template <typename Char, size_t N>
+FMT_CONSTEXPR basic_string_view<Char> compile_string_to_view(
+ const Char (&s)[N]) {
+ // Remove trailing null character if needed. Won't be present if this is used
+ // with raw character array (i.e. not defined as a string).
+ return {s,
+ N - ((std::char_traits<Char>::to_int_type(s[N - 1]) == 0) ? 1 : 0)};
+}
+
+// Converts string_view to basic_string_view.
+template <typename Char>
+FMT_CONSTEXPR basic_string_view<Char> compile_string_to_view(
+ const std_string_view<Char>& s) {
+ return {s.data(), s.size()};
+}
+
+#define FMT_STRING_IMPL(s, base) \
+ [] { \
+ /* Use a macro-like name to avoid shadowing warnings. */ \
+ struct FMT_COMPILE_STRING : base { \
+ using char_type = fmt::remove_cvref_t<decltype(s[0])>; \
+ FMT_MAYBE_UNUSED FMT_CONSTEXPR \
+ operator fmt::basic_string_view<char_type>() const { \
+ return fmt::detail::compile_string_to_view<char_type>(s); \
+ } \
+ }; \
+ return FMT_COMPILE_STRING(); \
+ }()
+
+/**
+ \rst
+ Constructs a compile-time format string from a string literal *s*.
+
+ **Example**::
+
+ // A compile-time error because 'd' is an invalid specifier for strings.
+ std::string s = fmt::format(FMT_STRING("{:d}"), "foo");
+ \endrst
+ */
+#define FMT_STRING(s) FMT_STRING_IMPL(s, fmt::compile_string)
+
+template <typename... Args, typename S,
+ enable_if_t<(is_compile_string<S>::value), int>>
+void check_format_string(S format_str) {
+ FMT_CONSTEXPR_DECL auto s = to_string_view(format_str);
+ using checker = format_string_checker<typename S::char_type, error_handler,
+ remove_cvref_t<Args>...>;
+ FMT_CONSTEXPR_DECL bool invalid_format =
+ (parse_format_string<true>(s, checker(s, {})), true);
+ (void)invalid_format;
+}
+
+template <template <typename> class Handler, typename Context>
+void handle_dynamic_spec(int& value, arg_ref<typename Context::char_type> ref,
+ Context& ctx) {
+ switch (ref.kind) {
+ case arg_id_kind::none:
+ break;
+ case arg_id_kind::index:
+ value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.index),
+ ctx.error_handler());
+ break;
+ case arg_id_kind::name:
+ value = detail::get_dynamic_spec<Handler>(ctx.arg(ref.val.name),
+ ctx.error_handler());
+ break;
+ }
+}
+
+using format_func = void (*)(detail::buffer<char>&, int, string_view);
+
+FMT_API void format_error_code(buffer<char>& out, int error_code,
+ string_view message) FMT_NOEXCEPT;
+
+FMT_API void report_error(format_func func, int error_code,
+ string_view message) FMT_NOEXCEPT;
+} // namespace detail
+
+template <typename OutputIt, typename Char>
+using arg_formatter FMT_DEPRECATED_ALIAS =
+ detail::arg_formatter<OutputIt, Char>;
+
+/**
+ An error returned by an operating system or a language runtime,
+ for example a file opening error.
+*/
+FMT_CLASS_API
+class FMT_API system_error : public std::runtime_error {
+ private:
+ void init(int err_code, string_view format_str, format_args args);
+
+ protected:
+ int error_code_;
+
+ system_error() : std::runtime_error(""), error_code_(0) {}
+
+ public:
+ /**
+ \rst
+ Constructs a :class:`fmt::system_error` object with a description
+ formatted with `fmt::format_system_error`. *message* and additional
+ arguments passed into the constructor are formatted similarly to
+ `fmt::format`.
+
+ **Example**::
+
+ // This throws a system_error with the description
+ // cannot open file 'madeup': No such file or directory
+ // or similar (system message may vary).
+ const char *filename = "madeup";
+ std::FILE *file = std::fopen(filename, "r");
+ if (!file)
+ throw fmt::system_error(errno, "cannot open file '{}'", filename);
+ \endrst
+ */
+ template <typename... Args>
+ system_error(int error_code, string_view message, const Args&... args)
+ : std::runtime_error("") {
+ init(error_code, message, make_format_args(args...));
+ }
+ system_error(const system_error&) = default;
+ system_error& operator=(const system_error&) = default;
+ system_error(system_error&&) = default;
+ system_error& operator=(system_error&&) = default;
+ ~system_error() FMT_NOEXCEPT FMT_OVERRIDE;
+
+ int error_code() const { return error_code_; }
+};
+
+/**
+ \rst
+ Formats an error returned by an operating system or a language runtime,
+ for example a file opening error, and writes it to *out* in the following
+ form:
+
+ .. parsed-literal::
+ *<message>*: *<system-message>*
+
+ where *<message>* is the passed message and *<system-message>* is
+ the system message corresponding to the error code.
+ *error_code* is a system error code as given by ``errno``.
+ If *error_code* is not a valid error code such as -1, the system message
+ may look like "Unknown error -1" and is platform-dependent.
+ \endrst
+ */
+FMT_API void format_system_error(detail::buffer<char>& out, int error_code,
+ string_view message) FMT_NOEXCEPT;
+
+// Reports a system error without throwing an exception.
+// Can be used to report errors from destructors.
+FMT_API void report_system_error(int error_code,
+ string_view message) FMT_NOEXCEPT;
+
+/** Fast integer formatter. */
+class format_int {
+ private:
+ // Buffer should be large enough to hold all digits (digits10 + 1),
+ // a sign and a null character.
+ enum { buffer_size = std::numeric_limits<unsigned long long>::digits10 + 3 };
+ mutable char buffer_[buffer_size];
+ char* str_;
+
+ template <typename UInt> char* format_unsigned(UInt value) {
+ auto n = static_cast<detail::uint32_or_64_or_128_t<UInt>>(value);
+ return detail::format_decimal(buffer_, n, buffer_size - 1).begin;
+ }
+
+ template <typename Int> char* format_signed(Int value) {
+ auto abs_value = static_cast<detail::uint32_or_64_or_128_t<Int>>(value);
+ bool negative = value < 0;
+ if (negative) abs_value = 0 - abs_value;
+ auto begin = format_unsigned(abs_value);
+ if (negative) *--begin = '-';
+ return begin;
+ }
+
+ public:
+ explicit format_int(int value) : str_(format_signed(value)) {}
+ explicit format_int(long value) : str_(format_signed(value)) {}
+ explicit format_int(long long value) : str_(format_signed(value)) {}
+ explicit format_int(unsigned value) : str_(format_unsigned(value)) {}
+ explicit format_int(unsigned long value) : str_(format_unsigned(value)) {}
+ explicit format_int(unsigned long long value)
+ : str_(format_unsigned(value)) {}
+
+ /** Returns the number of characters written to the output buffer. */
+ size_t size() const {
+ return detail::to_unsigned(buffer_ - str_ + buffer_size - 1);
+ }
+
+ /**
+ Returns a pointer to the output buffer content. No terminating null
+ character is appended.
+ */
+ const char* data() const { return str_; }
+
+ /**
+ Returns a pointer to the output buffer content with terminating null
+ character appended.
+ */
+ const char* c_str() const {
+ buffer_[buffer_size - 1] = '\0';
+ return str_;
+ }
+
+ /**
+ \rst
+ Returns the content of the output buffer as an ``std::string``.
+ \endrst
+ */
+ std::string str() const { return std::string(str_, size()); }
+};
+
+// A formatter specialization for the core types corresponding to detail::type
+// constants.
+template <typename T, typename Char>
+struct formatter<T, Char,
+ enable_if_t<detail::type_constant<T, Char>::value !=
+ detail::type::custom_type>> {
+ FMT_CONSTEXPR formatter() = default;
+
+ // Parses format specifiers stopping either at the end of the range or at the
+ // terminating '}'.
+ template <typename ParseContext>
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ using handler_type = detail::dynamic_specs_handler<ParseContext>;
+ auto type = detail::type_constant<T, Char>::value;
+ detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
+ type);
+ auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
+ auto eh = ctx.error_handler();
+ switch (type) {
+ case detail::type::none_type:
+ FMT_ASSERT(false, "invalid argument type");
+ break;
+ case detail::type::int_type:
+ case detail::type::uint_type:
+ case detail::type::long_long_type:
+ case detail::type::ulong_long_type:
+ case detail::type::int128_type:
+ case detail::type::uint128_type:
+ case detail::type::bool_type:
+ handle_int_type_spec(specs_.type,
+ detail::int_type_checker<decltype(eh)>(eh));
+ break;
+ case detail::type::char_type:
+ handle_char_specs(
+ &specs_, detail::char_specs_checker<decltype(eh)>(specs_.type, eh));
+ break;
+ case detail::type::float_type:
+ if (detail::const_check(FMT_USE_FLOAT))
+ detail::parse_float_type_spec(specs_, eh);
+ else
+ FMT_ASSERT(false, "float support disabled");
+ break;
+ case detail::type::double_type:
+ if (detail::const_check(FMT_USE_DOUBLE))
+ detail::parse_float_type_spec(specs_, eh);
+ else
+ FMT_ASSERT(false, "double support disabled");
+ break;
+ case detail::type::long_double_type:
+ if (detail::const_check(FMT_USE_LONG_DOUBLE))
+ detail::parse_float_type_spec(specs_, eh);
+ else
+ FMT_ASSERT(false, "long double support disabled");
+ break;
+ case detail::type::cstring_type:
+ detail::handle_cstring_type_spec(
+ specs_.type, detail::cstring_type_checker<decltype(eh)>(eh));
+ break;
+ case detail::type::string_type:
+ detail::check_string_type_spec(specs_.type, eh);
+ break;
+ case detail::type::pointer_type:
+ detail::check_pointer_type_spec(specs_.type, eh);
+ break;
+ case detail::type::custom_type:
+ // Custom format specifiers should be checked in parse functions of
+ // formatter specializations.
+ break;
+ }
+ return it;
+ }
+
+ template <typename FormatContext>
+ auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
+ detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
+ specs_.width_ref, ctx);
+ detail::handle_dynamic_spec<detail::precision_checker>(
+ specs_.precision, specs_.precision_ref, ctx);
+ using af = detail::arg_formatter<typename FormatContext::iterator,
+ typename FormatContext::char_type>;
+ return visit_format_arg(af(ctx, nullptr, &specs_),
+ detail::make_arg<FormatContext>(val));
+ }
+
+ private:
+ detail::dynamic_format_specs<Char> specs_;
+};
+
+#define FMT_FORMAT_AS(Type, Base) \
+ template <typename Char> \
+ struct formatter<Type, Char> : formatter<Base, Char> { \
+ template <typename FormatContext> \
+ auto format(Type const& val, FormatContext& ctx) -> decltype(ctx.out()) { \
+ return formatter<Base, Char>::format(val, ctx); \
+ } \
+ }
+
+FMT_FORMAT_AS(signed char, int);
+FMT_FORMAT_AS(unsigned char, unsigned);
+FMT_FORMAT_AS(short, int);
+FMT_FORMAT_AS(unsigned short, unsigned);
+FMT_FORMAT_AS(long, long long);
+FMT_FORMAT_AS(unsigned long, unsigned long long);
+FMT_FORMAT_AS(Char*, const Char*);
+FMT_FORMAT_AS(std::basic_string<Char>, basic_string_view<Char>);
+FMT_FORMAT_AS(std::nullptr_t, const void*);
+FMT_FORMAT_AS(detail::std_string_view<Char>, basic_string_view<Char>);
+
+template <typename Char>
+struct formatter<void*, Char> : formatter<const void*, Char> {
+ template <typename FormatContext>
+ auto format(void* val, FormatContext& ctx) -> decltype(ctx.out()) {
+ return formatter<const void*, Char>::format(val, ctx);
+ }
+};
+
+template <typename Char, size_t N>
+struct formatter<Char[N], Char> : formatter<basic_string_view<Char>, Char> {
+ template <typename FormatContext>
+ auto format(const Char* val, FormatContext& ctx) -> decltype(ctx.out()) {
+ return formatter<basic_string_view<Char>, Char>::format(val, ctx);
+ }
+};
+
+// A formatter for types known only at run time such as variant alternatives.
+//
+// Usage:
+// using variant = std::variant<int, std::string>;
+// template <>
+// struct formatter<variant>: dynamic_formatter<> {
+// auto format(const variant& v, format_context& ctx) {
+// return visit([&](const auto& val) {
+// return dynamic_formatter<>::format(val, ctx);
+// }, v);
+// }
+// };
+template <typename Char = char> class dynamic_formatter {
+ private:
+ struct null_handler : detail::error_handler {
+ void on_align(align_t) {}
+ void on_plus() {}
+ void on_minus() {}
+ void on_space() {}
+ void on_hash() {}
+ };
+
+ public:
+ template <typename ParseContext>
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ format_str_ = ctx.begin();
+ // Checks are deferred to formatting time when the argument type is known.
+ detail::dynamic_specs_handler<ParseContext> handler(specs_, ctx);
+ return parse_format_specs(ctx.begin(), ctx.end(), handler);
+ }
+
+ template <typename T, typename FormatContext>
+ auto format(const T& val, FormatContext& ctx) -> decltype(ctx.out()) {
+ handle_specs(ctx);
+ detail::specs_checker<null_handler> checker(
+ null_handler(), detail::mapped_type_constant<T, FormatContext>::value);
+ checker.on_align(specs_.align);
+ switch (specs_.sign) {
+ case sign::none:
+ break;
+ case sign::plus:
+ checker.on_plus();
+ break;
+ case sign::minus:
+ checker.on_minus();
+ break;
+ case sign::space:
+ checker.on_space();
+ break;
+ }
+ if (specs_.alt) checker.on_hash();
+ if (specs_.precision >= 0) checker.end_precision();
+ using af = detail::arg_formatter<typename FormatContext::iterator,
+ typename FormatContext::char_type>;
+ visit_format_arg(af(ctx, nullptr, &specs_),
+ detail::make_arg<FormatContext>(val));
+ return ctx.out();
+ }
+
+ private:
+ template <typename Context> void handle_specs(Context& ctx) {
+ detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
+ specs_.width_ref, ctx);
+ detail::handle_dynamic_spec<detail::precision_checker>(
+ specs_.precision, specs_.precision_ref, ctx);
+ }
+
+ detail::dynamic_format_specs<Char> specs_;
+ const Char* format_str_;
+};
+
+template <typename Char, typename ErrorHandler>
+FMT_CONSTEXPR void advance_to(
+ basic_format_parse_context<Char, ErrorHandler>& ctx, const Char* p) {
+ ctx.advance_to(ctx.begin() + (p - &*ctx.begin()));
+}
+
+/**
+ \rst
+ Converts ``p`` to ``const void*`` for pointer formatting.
+
+ **Example**::
+
+ auto s = fmt::format("{}", fmt::ptr(p));
+ \endrst
+ */
+template <typename T> inline const void* ptr(const T* p) { return p; }
+template <typename T> inline const void* ptr(const std::unique_ptr<T>& p) {
+ return p.get();
+}
+template <typename T> inline const void* ptr(const std::shared_ptr<T>& p) {
+ return p.get();
+}
+
+class bytes {
+ private:
+ string_view data_;
+ friend struct formatter<bytes>;
+
+ public:
+ explicit bytes(string_view data) : data_(data) {}
+};
+
+template <> struct formatter<bytes> {
+ private:
+ detail::dynamic_format_specs<char> specs_;
+
+ public:
+ template <typename ParseContext>
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ using handler_type = detail::dynamic_specs_handler<ParseContext>;
+ detail::specs_checker<handler_type> handler(handler_type(specs_, ctx),
+ detail::type::string_type);
+ auto it = parse_format_specs(ctx.begin(), ctx.end(), handler);
+ detail::check_string_type_spec(specs_.type, ctx.error_handler());
+ return it;
+ }
+
+ template <typename FormatContext>
+ auto format(bytes b, FormatContext& ctx) -> decltype(ctx.out()) {
+ detail::handle_dynamic_spec<detail::width_checker>(specs_.width,
+ specs_.width_ref, ctx);
+ detail::handle_dynamic_spec<detail::precision_checker>(
+ specs_.precision, specs_.precision_ref, ctx);
+ return detail::write_bytes(ctx.out(), b.data_, specs_);
+ }
+};
+
+template <typename It, typename Sentinel, typename Char>
+struct arg_join : detail::view {
+ It begin;
+ Sentinel end;
+ basic_string_view<Char> sep;
+
+ arg_join(It b, Sentinel e, basic_string_view<Char> s)
+ : begin(b), end(e), sep(s) {}
+};
+
+template <typename It, typename Sentinel, typename Char>
+struct formatter<arg_join<It, Sentinel, Char>, Char>
+ : formatter<typename std::iterator_traits<It>::value_type, Char> {
+ template <typename FormatContext>
+ auto format(const arg_join<It, Sentinel, Char>& value, FormatContext& ctx)
+ -> decltype(ctx.out()) {
+ using base = formatter<typename std::iterator_traits<It>::value_type, Char>;
+ auto it = value.begin;
+ auto out = ctx.out();
+ if (it != value.end) {
+ out = base::format(*it++, ctx);
+ while (it != value.end) {
+ out = std::copy(value.sep.begin(), value.sep.end(), out);
+ ctx.advance_to(out);
+ out = base::format(*it++, ctx);
+ }
+ }
+ return out;
+ }
+};
+
+/**
+ Returns an object that formats the iterator range `[begin, end)` with elements
+ separated by `sep`.
+ */
+template <typename It, typename Sentinel>
+arg_join<It, Sentinel, char> join(It begin, Sentinel end, string_view sep) {
+ return {begin, end, sep};
+}
+
+template <typename It, typename Sentinel>
+arg_join<It, Sentinel, wchar_t> join(It begin, Sentinel end, wstring_view sep) {
+ return {begin, end, sep};
+}
+
+/**
+ \rst
+ Returns an object that formats `range` with elements separated by `sep`.
+
+ **Example**::
+
+ std::vector<int> v = {1, 2, 3};
+ fmt::print("{}", fmt::join(v, ", "));
+ // Output: "1, 2, 3"
+
+ ``fmt::join`` applies passed format specifiers to the range elements::
+
+ fmt::print("{:02}", fmt::join(v, ", "));
+ // Output: "01, 02, 03"
+ \endrst
+ */
+template <typename Range>
+arg_join<detail::iterator_t<Range>, detail::sentinel_t<Range>, char> join(
+ Range&& range, string_view sep) {
+ return join(std::begin(range), std::end(range), sep);
+}
+
+template <typename Range>
+arg_join<detail::iterator_t<Range>, detail::sentinel_t<Range>, wchar_t> join(
+ Range&& range, wstring_view sep) {
+ return join(std::begin(range), std::end(range), sep);
+}
+
+/**
+ \rst
+ Converts *value* to ``std::string`` using the default format for type *T*.
+
+ **Example**::
+
+ #include <fmt/format.h>
+
+ std::string answer = fmt::to_string(42);
+ \endrst
+ */
+template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+inline std::string to_string(const T& value) {
+ std::string result;
+ detail::write<char>(std::back_inserter(result), value);
+ return result;
+}
+
+template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+inline std::string to_string(T value) {
+ // The buffer should be large enough to store the number including the sign or
+ // "false" for bool.
+ constexpr int max_size = detail::digits10<T>() + 2;
+ char buffer[max_size > 5 ? static_cast<unsigned>(max_size) : 5];
+ char* begin = buffer;
+ return std::string(begin, detail::write<char>(begin, value));
+}
+
+/**
+ Converts *value* to ``std::wstring`` using the default format for type *T*.
+ */
+template <typename T> inline std::wstring to_wstring(const T& value) {
+ return format(L"{}", value);
+}
+
+template <typename Char, size_t SIZE>
+std::basic_string<Char> to_string(const basic_memory_buffer<Char, SIZE>& buf) {
+ auto size = buf.size();
+ detail::assume(size < std::basic_string<Char>().max_size());
+ return std::basic_string<Char>(buf.data(), size);
+}
+
+template <typename Char>
+void detail::vformat_to(
+ detail::buffer<Char>& buf, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args,
+ detail::locale_ref loc) {
+ using iterator = typename buffer_context<Char>::iterator;
+ auto out = buffer_appender<Char>(buf);
+ if (format_str.size() == 2 && equal2(format_str.data(), "{}")) {
+ auto arg = args.get(0);
+ if (!arg) error_handler().on_error("argument not found");
+ visit_format_arg(default_arg_formatter<iterator, Char>{out, args, loc},
+ arg);
+ return;
+ }
+ format_handler<iterator, Char, buffer_context<Char>> h(out, format_str, args,
+ loc);
+ parse_format_string<false>(format_str, h);
+}
+
+#ifndef FMT_HEADER_ONLY
+extern template void detail::vformat_to(detail::buffer<char>&, string_view,
+ basic_format_args<format_context>,
+ detail::locale_ref);
+namespace detail {
+
+extern template FMT_API std::string grouping_impl<char>(locale_ref loc);
+extern template FMT_API std::string grouping_impl<wchar_t>(locale_ref loc);
+extern template FMT_API char thousands_sep_impl<char>(locale_ref loc);
+extern template FMT_API wchar_t thousands_sep_impl<wchar_t>(locale_ref loc);
+extern template FMT_API char decimal_point_impl(locale_ref loc);
+extern template FMT_API wchar_t decimal_point_impl(locale_ref loc);
+extern template int format_float<double>(double value, int precision,
+ float_specs specs, buffer<char>& buf);
+extern template int format_float<long double>(long double value, int precision,
+ float_specs specs,
+ buffer<char>& buf);
+int snprintf_float(float value, int precision, float_specs specs,
+ buffer<char>& buf) = delete;
+extern template int snprintf_float<double>(double value, int precision,
+ float_specs specs,
+ buffer<char>& buf);
+extern template int snprintf_float<long double>(long double value,
+ int precision,
+ float_specs specs,
+ buffer<char>& buf);
+} // namespace detail
+#endif
+
+template <typename S, typename Char = char_t<S>,
+ FMT_ENABLE_IF(detail::is_string<S>::value)>
+inline void vformat_to(
+ detail::buffer<Char>& buf, const S& format_str,
+ basic_format_args<FMT_BUFFER_CONTEXT(type_identity_t<Char>)> args) {
+ return detail::vformat_to(buf, to_string_view(format_str), args);
+}
+
+template <typename S, typename... Args, size_t SIZE = inline_buffer_size,
+ typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
+inline typename buffer_context<Char>::iterator format_to(
+ basic_memory_buffer<Char, SIZE>& buf, const S& format_str, Args&&... args) {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ detail::vformat_to(buf, to_string_view(format_str), vargs);
+ return detail::buffer_appender<Char>(buf);
+}
+
+template <typename OutputIt, typename Char = char>
+using format_context_t = basic_format_context<OutputIt, Char>;
+
+template <typename OutputIt, typename Char = char>
+using format_args_t = basic_format_args<format_context_t<OutputIt, Char>>;
+
+template <typename OutputIt, typename Char = typename OutputIt::value_type>
+using format_to_n_context FMT_DEPRECATED_ALIAS = buffer_context<Char>;
+
+template <typename OutputIt, typename Char = typename OutputIt::value_type>
+using format_to_n_args FMT_DEPRECATED_ALIAS =
+ basic_format_args<buffer_context<Char>>;
+
+template <typename OutputIt, typename Char, typename... Args>
+FMT_DEPRECATED format_arg_store<buffer_context<Char>, Args...>
+make_format_to_n_args(const Args&... args) {
+ return format_arg_store<buffer_context<Char>, Args...>(args...);
+}
+
+template <typename Char, enable_if_t<(!std::is_same<Char, char>::value), int>>
+std::basic_string<Char> detail::vformat(
+ basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buffer;
+ detail::vformat_to(buffer, format_str, args);
+ return to_string(buffer);
+}
+
+template <typename Char, FMT_ENABLE_IF(std::is_same<Char, wchar_t>::value)>
+void vprint(std::FILE* f, basic_string_view<Char> format_str,
+ wformat_args args) {
+ wmemory_buffer buffer;
+ detail::vformat_to(buffer, format_str, args);
+ buffer.push_back(L'\0');
+ if (std::fputws(buffer.data(), f) == -1)
+ FMT_THROW(system_error(errno, "cannot write to file"));
+}
+
+template <typename Char, FMT_ENABLE_IF(std::is_same<Char, wchar_t>::value)>
+void vprint(basic_string_view<Char> format_str, wformat_args args) {
+ vprint(stdout, format_str, args);
+}
+
+#if FMT_USE_USER_DEFINED_LITERALS
+namespace detail {
+
+# if FMT_USE_UDL_TEMPLATE
+template <typename Char, Char... CHARS> class udl_formatter {
+ public:
+ template <typename... Args>
+ std::basic_string<Char> operator()(Args&&... args) const {
+ static FMT_CONSTEXPR_DECL Char s[] = {CHARS..., '\0'};
+ return format(FMT_STRING(s), std::forward<Args>(args)...);
+ }
+};
+# else
+template <typename Char> struct udl_formatter {
+ basic_string_view<Char> str;
+
+ template <typename... Args>
+ std::basic_string<Char> operator()(Args&&... args) const {
+ return format(str, std::forward<Args>(args)...);
+ }
+};
+# endif // FMT_USE_UDL_TEMPLATE
+
+template <typename Char> struct udl_arg {
+ const Char* str;
+
+ template <typename T> named_arg<Char, T> operator=(T&& value) const {
+ return {str, std::forward<T>(value)};
+ }
+};
+} // namespace detail
+
+inline namespace literals {
+# if FMT_USE_UDL_TEMPLATE
+# pragma GCC diagnostic push
+# pragma GCC diagnostic ignored "-Wpedantic"
+# if FMT_CLANG_VERSION
+# pragma GCC diagnostic ignored "-Wgnu-string-literal-operator-template"
+# endif
+template <typename Char, Char... CHARS>
+FMT_CONSTEXPR detail::udl_formatter<Char, CHARS...> operator""_format() {
+ return {};
+}
+# pragma GCC diagnostic pop
+# else
+/**
+ \rst
+ User-defined literal equivalent of :func:`fmt::format`.
+
+ **Example**::
+
+ using namespace fmt::literals;
+ std::string message = "The answer is {}"_format(42);
+ \endrst
+ */
+FMT_CONSTEXPR detail::udl_formatter<char> operator"" _format(const char* s,
+ size_t n) {
+ return {{s, n}};
+}
+FMT_CONSTEXPR detail::udl_formatter<wchar_t> operator"" _format(
+ const wchar_t* s, size_t n) {
+ return {{s, n}};
+}
+# endif // FMT_USE_UDL_TEMPLATE
+
+/**
+ \rst
+ User-defined literal equivalent of :func:`fmt::arg`.
+
+ **Example**::
+
+ using namespace fmt::literals;
+ fmt::print("Elapsed time: {s:.2f} seconds", "s"_a=1.23);
+ \endrst
+ */
+FMT_CONSTEXPR detail::udl_arg<char> operator"" _a(const char* s, size_t) {
+ return {s};
+}
+FMT_CONSTEXPR detail::udl_arg<wchar_t> operator"" _a(const wchar_t* s, size_t) {
+ return {s};
+}
+} // namespace literals
+#endif // FMT_USE_USER_DEFINED_LITERALS
+FMT_END_NAMESPACE
+
+#ifdef FMT_HEADER_ONLY
+# define FMT_FUNC inline
+# include "format-inl.h"
+#else
+# define FMT_FUNC
+#endif
+
+#endif // FMT_FORMAT_H_
diff --git a/include/spdlog/fmt/bundled/locale.h b/include/spdlog/fmt/bundled/locale.h
new file mode 100644
index 00000000..7301bf92
--- /dev/null
+++ b/include/spdlog/fmt/bundled/locale.h
@@ -0,0 +1,64 @@
+// Formatting library for C++ - std::locale support
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_LOCALE_H_
+#define FMT_LOCALE_H_
+
+#include <locale>
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+
+namespace detail {
+template <typename Char>
+std::basic_string<Char> vformat(
+ const std::locale& loc, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buffer;
+ detail::vformat_to(buffer, format_str, args, detail::locale_ref(loc));
+ return fmt::to_string(buffer);
+}
+} // namespace detail
+
+template <typename S, typename Char = char_t<S>>
+inline std::basic_string<Char> vformat(
+ const std::locale& loc, const S& format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ return detail::vformat(loc, to_string_view(format_str), args);
+}
+
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline std::basic_string<Char> format(const std::locale& loc,
+ const S& format_str, Args&&... args) {
+ return detail::vformat(loc, to_string_view(format_str),
+ fmt::make_args_checked<Args...>(format_str, args...));
+}
+
+template <typename S, typename OutputIt, typename... Args,
+ typename Char = char_t<S>,
+ FMT_ENABLE_IF(detail::is_output_iterator<OutputIt, Char>::value)>
+inline OutputIt vformat_to(
+ OutputIt out, const std::locale& loc, const S& format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ decltype(detail::get_buffer<Char>(out)) buf(detail::get_buffer_init(out));
+ vformat_to(buf, to_string_view(format_str), args, detail::locale_ref(loc));
+ return detail::get_iterator(buf);
+}
+
+template <typename OutputIt, typename S, typename... Args,
+ bool enable = detail::is_output_iterator<OutputIt, char_t<S>>::value>
+inline auto format_to(OutputIt out, const std::locale& loc,
+ const S& format_str, Args&&... args) ->
+ typename std::enable_if<enable, OutputIt>::type {
+ const auto& vargs = fmt::make_args_checked<Args...>(format_str, args...);
+ return vformat_to(out, loc, to_string_view(format_str), vargs);
+}
+
+FMT_END_NAMESPACE
+
+#endif // FMT_LOCALE_H_
diff --git a/include/spdlog/fmt/bundled/os.h b/include/spdlog/fmt/bundled/os.h
new file mode 100644
index 00000000..d44ea0c9
--- /dev/null
+++ b/include/spdlog/fmt/bundled/os.h
@@ -0,0 +1,480 @@
+// Formatting library for C++ - optional OS-specific functionality
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_OS_H_
+#define FMT_OS_H_
+
+#if defined(__MINGW32__) || defined(__CYGWIN__)
+// Workaround MinGW bug https://sourceforge.net/p/mingw/bugs/2024/.
+# undef __STRICT_ANSI__
+#endif
+
+#include <cerrno>
+#include <clocale> // for locale_t
+#include <cstddef>
+#include <cstdio>
+#include <cstdlib> // for strtod_l
+
+#if defined __APPLE__ || defined(__FreeBSD__)
+# include <xlocale.h> // for LC_NUMERIC_MASK on OS X
+#endif
+
+#include "format.h"
+
+// UWP doesn't provide _pipe.
+#if FMT_HAS_INCLUDE("winapifamily.h")
+# include <winapifamily.h>
+#endif
+#if (FMT_HAS_INCLUDE(<fcntl.h>) || defined(__APPLE__) || \
+ defined(__linux__)) && \
+ (!defined(WINAPI_FAMILY) || (WINAPI_FAMILY == WINAPI_FAMILY_DESKTOP_APP))
+# include <fcntl.h> // for O_RDONLY
+# define FMT_USE_FCNTL 1
+#else
+# define FMT_USE_FCNTL 0
+#endif
+
+#ifndef FMT_POSIX
+# if defined(_WIN32) && !defined(__MINGW32__)
+// Fix warnings about deprecated symbols.
+# define FMT_POSIX(call) _##call
+# else
+# define FMT_POSIX(call) call
+# endif
+#endif
+
+// Calls to system functions are wrapped in FMT_SYSTEM for testability.
+#ifdef FMT_SYSTEM
+# define FMT_POSIX_CALL(call) FMT_SYSTEM(call)
+#else
+# define FMT_SYSTEM(call) ::call
+# ifdef _WIN32
+// Fix warnings about deprecated symbols.
+# define FMT_POSIX_CALL(call) ::_##call
+# else
+# define FMT_POSIX_CALL(call) ::call
+# endif
+#endif
+
+// Retries the expression while it evaluates to error_result and errno
+// equals to EINTR.
+#ifndef _WIN32
+# define FMT_RETRY_VAL(result, expression, error_result) \
+ do { \
+ (result) = (expression); \
+ } while ((result) == (error_result) && errno == EINTR)
+#else
+# define FMT_RETRY_VAL(result, expression, error_result) result = (expression)
+#endif
+
+#define FMT_RETRY(result, expression) FMT_RETRY_VAL(result, expression, -1)
+
+FMT_BEGIN_NAMESPACE
+
+/**
+ \rst
+ A reference to a null-terminated string. It can be constructed from a C
+ string or ``std::string``.
+
+ You can use one of the following type aliases for common character types:
+
+ +---------------+-----------------------------+
+ | Type | Definition |
+ +===============+=============================+
+ | cstring_view | basic_cstring_view<char> |
+ +---------------+-----------------------------+
+ | wcstring_view | basic_cstring_view<wchar_t> |
+ +---------------+-----------------------------+
+
+ This class is most useful as a parameter type to allow passing
+ different types of strings to a function, for example::
+
+ template <typename... Args>
+ std::string format(cstring_view format_str, const Args & ... args);
+
+ format("{}", 42);
+ format(std::string("{}"), 42);
+ \endrst
+ */
+template <typename Char> class basic_cstring_view {
+ private:
+ const Char* data_;
+
+ public:
+ /** Constructs a string reference object from a C string. */
+ basic_cstring_view(const Char* s) : data_(s) {}
+
+ /**
+ \rst
+ Constructs a string reference from an ``std::string`` object.
+ \endrst
+ */
+ basic_cstring_view(const std::basic_string<Char>& s) : data_(s.c_str()) {}
+
+ /** Returns the pointer to a C string. */
+ const Char* c_str() const { return data_; }
+};
+
+using cstring_view = basic_cstring_view<char>;
+using wcstring_view = basic_cstring_view<wchar_t>;
+
+// An error code.
+class error_code {
+ private:
+ int value_;
+
+ public:
+ explicit error_code(int value = 0) FMT_NOEXCEPT : value_(value) {}
+
+ int get() const FMT_NOEXCEPT { return value_; }
+};
+
+#ifdef _WIN32
+namespace detail {
+// A converter from UTF-16 to UTF-8.
+// It is only provided for Windows since other systems support UTF-8 natively.
+class utf16_to_utf8 {
+ private:
+ memory_buffer buffer_;
+
+ public:
+ utf16_to_utf8() {}
+ FMT_API explicit utf16_to_utf8(wstring_view s);
+ operator string_view() const { return string_view(&buffer_[0], size()); }
+ size_t size() const { return buffer_.size() - 1; }
+ const char* c_str() const { return &buffer_[0]; }
+ std::string str() const { return std::string(&buffer_[0], size()); }
+
+ // Performs conversion returning a system error code instead of
+ // throwing exception on conversion error. This method may still throw
+ // in case of memory allocation error.
+ FMT_API int convert(wstring_view s);
+};
+
+FMT_API void format_windows_error(buffer<char>& out, int error_code,
+ string_view message) FMT_NOEXCEPT;
+} // namespace detail
+
+/** A Windows error. */
+class windows_error : public system_error {
+ private:
+ FMT_API void init(int error_code, string_view format_str, format_args args);
+
+ public:
+ /**
+ \rst
+ Constructs a :class:`fmt::windows_error` object with the description
+ of the form
+
+ .. parsed-literal::
+ *<message>*: *<system-message>*
+
+ where *<message>* is the formatted message and *<system-message>* is the
+ system message corresponding to the error code.
+ *error_code* is a Windows error code as given by ``GetLastError``.
+ If *error_code* is not a valid error code such as -1, the system message
+ will look like "error -1".
+
+ **Example**::
+
+ // This throws a windows_error with the description
+ // cannot open file 'madeup': The system cannot find the file specified.
+ // or similar (system message may vary).
+ const char *filename = "madeup";
+ LPOFSTRUCT of = LPOFSTRUCT();
+ HFILE file = OpenFile(filename, &of, OF_READ);
+ if (file == HFILE_ERROR) {
+ throw fmt::windows_error(GetLastError(),
+ "cannot open file '{}'", filename);
+ }
+ \endrst
+ */
+ template <typename... Args>
+ windows_error(int error_code, string_view message, const Args&... args) {
+ init(error_code, message, make_format_args(args...));
+ }
+};
+
+// Reports a Windows error without throwing an exception.
+// Can be used to report errors from destructors.
+FMT_API void report_windows_error(int error_code,
+ string_view message) FMT_NOEXCEPT;
+#endif // _WIN32
+
+// A buffered file.
+class buffered_file {
+ private:
+ FILE* file_;
+
+ friend class file;
+
+ explicit buffered_file(FILE* f) : file_(f) {}
+
+ public:
+ buffered_file(const buffered_file&) = delete;
+ void operator=(const buffered_file&) = delete;
+
+ // Constructs a buffered_file object which doesn't represent any file.
+ buffered_file() FMT_NOEXCEPT : file_(nullptr) {}
+
+ // Destroys the object closing the file it represents if any.
+ FMT_API ~buffered_file() FMT_NOEXCEPT;
+
+ public:
+ buffered_file(buffered_file&& other) FMT_NOEXCEPT : file_(other.file_) {
+ other.file_ = nullptr;
+ }
+
+ buffered_file& operator=(buffered_file&& other) {
+ close();
+ file_ = other.file_;
+ other.file_ = nullptr;
+ return *this;
+ }
+
+ // Opens a file.
+ FMT_API buffered_file(cstring_view filename, cstring_view mode);
+
+ // Closes the file.
+ FMT_API void close();
+
+ // Returns the pointer to a FILE object representing this file.
+ FILE* get() const FMT_NOEXCEPT { return file_; }
+
+ // We place parentheses around fileno to workaround a bug in some versions
+ // of MinGW that define fileno as a macro.
+ FMT_API int(fileno)() const;
+
+ void vprint(string_view format_str, format_args args) {
+ fmt::vprint(file_, format_str, args);
+ }
+
+ template <typename... Args>
+ inline void print(string_view format_str, const Args&... args) {
+ vprint(format_str, make_format_args(args...));
+ }
+};
+
+#if FMT_USE_FCNTL
+// A file. Closed file is represented by a file object with descriptor -1.
+// Methods that are not declared with FMT_NOEXCEPT may throw
+// fmt::system_error in case of failure. Note that some errors such as
+// closing the file multiple times will cause a crash on Windows rather
+// than an exception. You can get standard behavior by overriding the
+// invalid parameter handler with _set_invalid_parameter_handler.
+class file {
+ private:
+ int fd_; // File descriptor.
+
+ // Constructs a file object with a given descriptor.
+ explicit file(int fd) : fd_(fd) {}
+
+ public:
+ // Possible values for the oflag argument to the constructor.
+ enum {
+ RDONLY = FMT_POSIX(O_RDONLY), // Open for reading only.
+ WRONLY = FMT_POSIX(O_WRONLY), // Open for writing only.
+ RDWR = FMT_POSIX(O_RDWR), // Open for reading and writing.
+ CREATE = FMT_POSIX(O_CREAT), // Create if the file doesn't exist.
+ APPEND = FMT_POSIX(O_APPEND) // Open in append mode.
+ };
+
+ // Constructs a file object which doesn't represent any file.
+ file() FMT_NOEXCEPT : fd_(-1) {}
+
+ // Opens a file and constructs a file object representing this file.
+ FMT_API file(cstring_view path, int oflag);
+
+ public:
+ file(const file&) = delete;
+ void operator=(const file&) = delete;
+
+ file(file&& other) FMT_NOEXCEPT : fd_(other.fd_) { other.fd_ = -1; }
+
+ file& operator=(file&& other) FMT_NOEXCEPT {
+ close();
+ fd_ = other.fd_;
+ other.fd_ = -1;
+ return *this;
+ }
+
+ // Destroys the object closing the file it represents if any.
+ FMT_API ~file() FMT_NOEXCEPT;
+
+ // Returns the file descriptor.
+ int descriptor() const FMT_NOEXCEPT { return fd_; }
+
+ // Closes the file.
+ FMT_API void close();
+
+ // Returns the file size. The size has signed type for consistency with
+ // stat::st_size.
+ FMT_API long long size() const;
+
+ // Attempts to read count bytes from the file into the specified buffer.
+ FMT_API size_t read(void* buffer, size_t count);
+
+ // Attempts to write count bytes from the specified buffer to the file.
+ FMT_API size_t write(const void* buffer, size_t count);
+
+ // Duplicates a file descriptor with the dup function and returns
+ // the duplicate as a file object.
+ FMT_API static file dup(int fd);
+
+ // Makes fd be the copy of this file descriptor, closing fd first if
+ // necessary.
+ FMT_API void dup2(int fd);
+
+ // Makes fd be the copy of this file descriptor, closing fd first if
+ // necessary.
+ FMT_API void dup2(int fd, error_code& ec) FMT_NOEXCEPT;
+
+ // Creates a pipe setting up read_end and write_end file objects for reading
+ // and writing respectively.
+ FMT_API static void pipe(file& read_end, file& write_end);
+
+ // Creates a buffered_file object associated with this file and detaches
+ // this file object from the file.
+ FMT_API buffered_file fdopen(const char* mode);
+};
+
+// Returns the memory page size.
+long getpagesize();
+
+namespace detail {
+
+struct buffer_size {
+ size_t value = 0;
+ buffer_size operator=(size_t val) const {
+ auto bs = buffer_size();
+ bs.value = val;
+ return bs;
+ }
+};
+
+struct ostream_params {
+ int oflag = file::WRONLY | file::CREATE;
+ size_t buffer_size = BUFSIZ > 32768 ? BUFSIZ : 32768;
+
+ ostream_params() {}
+
+ template <typename... T>
+ ostream_params(T... params, int oflag) : ostream_params(params...) {
+ this->oflag = oflag;
+ }
+
+ template <typename... T>
+ ostream_params(T... params, detail::buffer_size bs)
+ : ostream_params(params...) {
+ this->buffer_size = bs.value;
+ }
+};
+} // namespace detail
+
+static constexpr detail::buffer_size buffer_size;
+
+// A fast output stream which is not thread-safe.
+class ostream final : private detail::buffer<char> {
+ private:
+ file file_;
+
+ void flush() {
+ if (size() == 0) return;
+ file_.write(data(), size());
+ clear();
+ }
+
+ FMT_API void grow(size_t) override final;
+
+ ostream(cstring_view path, const detail::ostream_params& params)
+ : file_(path, params.oflag) {
+ set(new char[params.buffer_size], params.buffer_size);
+ }
+
+ public:
+ ostream(ostream&& other)
+ : detail::buffer<char>(other.data(), other.size(), other.capacity()),
+ file_(std::move(other.file_)) {
+ other.set(nullptr, 0);
+ }
+ ~ostream() {
+ flush();
+ delete[] data();
+ }
+
+ template <typename... T>
+ friend ostream output_file(cstring_view path, T... params);
+
+ void close() {
+ flush();
+ file_.close();
+ }
+
+ template <typename S, typename... Args>
+ void print(const S& format_str, const Args&... args) {
+ format_to(detail::buffer_appender<char>(*this), format_str, args...);
+ }
+};
+
+/**
+ Opens a file for writing. Supported parameters passed in `params`:
+ * ``<integer>``: Output flags (``file::WRONLY | file::CREATE`` by default)
+ * ``buffer_size=<integer>``: Output buffer size
+ */
+template <typename... T>
+inline ostream output_file(cstring_view path, T... params) {
+ return {path, detail::ostream_params(params...)};
+}
+#endif // FMT_USE_FCNTL
+
+#ifdef FMT_LOCALE
+// A "C" numeric locale.
+class locale {
+ private:
+# ifdef _WIN32
+ using locale_t = _locale_t;
+
+ static void freelocale(locale_t loc) { _free_locale(loc); }
+
+ static double strtod_l(const char* nptr, char** endptr, _locale_t loc) {
+ return _strtod_l(nptr, endptr, loc);
+ }
+# endif
+
+ locale_t locale_;
+
+ public:
+ using type = locale_t;
+ locale(const locale&) = delete;
+ void operator=(const locale&) = delete;
+
+ locale() {
+# ifndef _WIN32
+ locale_ = FMT_SYSTEM(newlocale(LC_NUMERIC_MASK, "C", nullptr));
+# else
+ locale_ = _create_locale(LC_NUMERIC, "C");
+# endif
+ if (!locale_) FMT_THROW(system_error(errno, "cannot create locale"));
+ }
+ ~locale() { freelocale(locale_); }
+
+ type get() const { return locale_; }
+
+ // Converts string to floating-point number and advances str past the end
+ // of the parsed input.
+ double strtod(const char*& str) const {
+ char* end = nullptr;
+ double result = strtod_l(str, &end, locale_);
+ str = end;
+ return result;
+ }
+};
+using Locale FMT_DEPRECATED_ALIAS = locale;
+#endif // FMT_LOCALE
+FMT_END_NAMESPACE
+
+#endif // FMT_OS_H_
diff --git a/include/spdlog/fmt/bundled/ostream.h b/include/spdlog/fmt/bundled/ostream.h
new file mode 100644
index 00000000..29c58ec1
--- /dev/null
+++ b/include/spdlog/fmt/bundled/ostream.h
@@ -0,0 +1,177 @@
+// Formatting library for C++ - std::ostream support
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_OSTREAM_H_
+#define FMT_OSTREAM_H_
+
+#include <ostream>
+
+#include "format.h"
+
+FMT_BEGIN_NAMESPACE
+
+template <typename Char> class basic_printf_parse_context;
+template <typename OutputIt, typename Char> class basic_printf_context;
+
+namespace detail {
+
+template <class Char> class formatbuf : public std::basic_streambuf<Char> {
+ private:
+ using int_type = typename std::basic_streambuf<Char>::int_type;
+ using traits_type = typename std::basic_streambuf<Char>::traits_type;
+
+ buffer<Char>& buffer_;
+
+ public:
+ formatbuf(buffer<Char>& buf) : buffer_(buf) {}
+
+ protected:
+ // The put-area is actually always empty. This makes the implementation
+ // simpler and has the advantage that the streambuf and the buffer are always
+ // in sync and sputc never writes into uninitialized memory. The obvious
+ // disadvantage is that each call to sputc always results in a (virtual) call
+ // to overflow. There is no disadvantage here for sputn since this always
+ // results in a call to xsputn.
+
+ int_type overflow(int_type ch = traits_type::eof()) FMT_OVERRIDE {
+ if (!traits_type::eq_int_type(ch, traits_type::eof()))
+ buffer_.push_back(static_cast<Char>(ch));
+ return ch;
+ }
+
+ std::streamsize xsputn(const Char* s, std::streamsize count) FMT_OVERRIDE {
+ buffer_.append(s, s + count);
+ return count;
+ }
+};
+
+struct converter {
+ template <typename T, FMT_ENABLE_IF(is_integral<T>::value)> converter(T);
+};
+
+template <typename Char> struct test_stream : std::basic_ostream<Char> {
+ private:
+ void_t<> operator<<(converter);
+};
+
+// Hide insertion operators for built-in types.
+template <typename Char, typename Traits>
+void_t<> operator<<(std::basic_ostream<Char, Traits>&, Char);
+template <typename Char, typename Traits>
+void_t<> operator<<(std::basic_ostream<Char, Traits>&, char);
+template <typename Traits>
+void_t<> operator<<(std::basic_ostream<char, Traits>&, char);
+template <typename Traits>
+void_t<> operator<<(std::basic_ostream<char, Traits>&, signed char);
+template <typename Traits>
+void_t<> operator<<(std::basic_ostream<char, Traits>&, unsigned char);
+
+// Checks if T has a user-defined operator<< (e.g. not a member of
+// std::ostream).
+template <typename T, typename Char> class is_streamable {
+ private:
+ template <typename U>
+ static bool_constant<!std::is_same<decltype(std::declval<test_stream<Char>&>()
+ << std::declval<U>()),
+ void_t<>>::value>
+ test(int);
+
+ template <typename> static std::false_type test(...);
+
+ using result = decltype(test<T>(0));
+
+ public:
+ static const bool value = result::value;
+};
+
+// Write the content of buf to os.
+template <typename Char>
+void write_buffer(std::basic_ostream<Char>& os, buffer<Char>& buf) {
+ const Char* buf_data = buf.data();
+ using unsigned_streamsize = std::make_unsigned<std::streamsize>::type;
+ unsigned_streamsize size = buf.size();
+ unsigned_streamsize max_size = to_unsigned(max_value<std::streamsize>());
+ do {
+ unsigned_streamsize n = size <= max_size ? size : max_size;
+ os.write(buf_data, static_cast<std::streamsize>(n));
+ buf_data += n;
+ size -= n;
+ } while (size != 0);
+}
+
+template <typename Char, typename T>
+void format_value(buffer<Char>& buf, const T& value,
+ locale_ref loc = locale_ref()) {
+ formatbuf<Char> format_buf(buf);
+ std::basic_ostream<Char> output(&format_buf);
+#if !defined(FMT_STATIC_THOUSANDS_SEPARATOR)
+ if (loc) output.imbue(loc.get<std::locale>());
+#endif
+ output << value;
+ output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
+ buf.try_resize(buf.size());
+}
+
+// Formats an object of type T that has an overloaded ostream operator<<.
+template <typename T, typename Char>
+struct fallback_formatter<T, Char, enable_if_t<is_streamable<T, Char>::value>>
+ : private formatter<basic_string_view<Char>, Char> {
+ FMT_CONSTEXPR auto parse(basic_format_parse_context<Char>& ctx)
+ -> decltype(ctx.begin()) {
+ return formatter<basic_string_view<Char>, Char>::parse(ctx);
+ }
+ template <typename ParseCtx,
+ FMT_ENABLE_IF(std::is_same<
+ ParseCtx, basic_printf_parse_context<Char>>::value)>
+ auto parse(ParseCtx& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
+
+ template <typename OutputIt>
+ auto format(const T& value, basic_format_context<OutputIt, Char>& ctx)
+ -> OutputIt {
+ basic_memory_buffer<Char> buffer;
+ format_value(buffer, value, ctx.locale());
+ basic_string_view<Char> str(buffer.data(), buffer.size());
+ return formatter<basic_string_view<Char>, Char>::format(str, ctx);
+ }
+ template <typename OutputIt>
+ auto format(const T& value, basic_printf_context<OutputIt, Char>& ctx)
+ -> OutputIt {
+ basic_memory_buffer<Char> buffer;
+ format_value(buffer, value, ctx.locale());
+ return std::copy(buffer.begin(), buffer.end(), ctx.out());
+ }
+};
+} // namespace detail
+
+template <typename Char>
+void vprint(std::basic_ostream<Char>& os, basic_string_view<Char> format_str,
+ basic_format_args<buffer_context<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buffer;
+ detail::vformat_to(buffer, format_str, args);
+ detail::write_buffer(os, buffer);
+}
+
+/**
+ \rst
+ Prints formatted data to the stream *os*.
+
+ **Example**::
+
+ fmt::print(cerr, "Don't {}!", "panic");
+ \endrst
+ */
+template <typename S, typename... Args,
+ typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
+void print(std::basic_ostream<Char>& os, const S& format_str, Args&&... args) {
+ vprint(os, to_string_view(format_str),
+ fmt::make_args_checked<Args...>(format_str, args...));
+}
+FMT_END_NAMESPACE
+
+#endif // FMT_OSTREAM_H_
diff --git a/include/spdlog/fmt/bundled/posix.h b/include/spdlog/fmt/bundled/posix.h
new file mode 100644
index 00000000..da19e9d5
--- /dev/null
+++ b/include/spdlog/fmt/bundled/posix.h
@@ -0,0 +1,2 @@
+#include "os.h"
+#warning "fmt/posix.h is deprecated; use fmt/os.h instead"
diff --git a/include/spdlog/fmt/bundled/printf.h b/include/spdlog/fmt/bundled/printf.h
new file mode 100644
index 00000000..8c28ac23
--- /dev/null
+++ b/include/spdlog/fmt/bundled/printf.h
@@ -0,0 +1,751 @@
+// Formatting library for C++ - legacy printf implementation
+//
+// Copyright (c) 2012 - 2016, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+
+#ifndef FMT_PRINTF_H_
+#define FMT_PRINTF_H_
+
+#include <algorithm> // std::max
+#include <limits> // std::numeric_limits
+
+#include "ostream.h"
+
+FMT_BEGIN_NAMESPACE
+namespace detail {
+
+// Checks if a value fits in int - used to avoid warnings about comparing
+// signed and unsigned integers.
+template <bool IsSigned> struct int_checker {
+ template <typename T> static bool fits_in_int(T value) {
+ unsigned max = max_value<int>();
+ return value <= max;
+ }
+ static bool fits_in_int(bool) { return true; }
+};
+
+template <> struct int_checker<true> {
+ template <typename T> static bool fits_in_int(T value) {
+ return value >= (std::numeric_limits<int>::min)() &&
+ value <= max_value<int>();
+ }
+ static bool fits_in_int(int) { return true; }
+};
+
+class printf_precision_handler {
+ public:
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ int operator()(T value) {
+ if (!int_checker<std::numeric_limits<T>::is_signed>::fits_in_int(value))
+ FMT_THROW(format_error("number is too big"));
+ return (std::max)(static_cast<int>(value), 0);
+ }
+
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ int operator()(T) {
+ FMT_THROW(format_error("precision is not integer"));
+ return 0;
+ }
+};
+
+// An argument visitor that returns true iff arg is a zero integer.
+class is_zero_int {
+ public:
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ bool operator()(T value) {
+ return value == 0;
+ }
+
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ bool operator()(T) {
+ return false;
+ }
+};
+
+template <typename T> struct make_unsigned_or_bool : std::make_unsigned<T> {};
+
+template <> struct make_unsigned_or_bool<bool> { using type = bool; };
+
+template <typename T, typename Context> class arg_converter {
+ private:
+ using char_type = typename Context::char_type;
+
+ basic_format_arg<Context>& arg_;
+ char_type type_;
+
+ public:
+ arg_converter(basic_format_arg<Context>& arg, char_type type)
+ : arg_(arg), type_(type) {}
+
+ void operator()(bool value) {
+ if (type_ != 's') operator()<bool>(value);
+ }
+
+ template <typename U, FMT_ENABLE_IF(std::is_integral<U>::value)>
+ void operator()(U value) {
+ bool is_signed = type_ == 'd' || type_ == 'i';
+ using target_type = conditional_t<std::is_same<T, void>::value, U, T>;
+ if (const_check(sizeof(target_type) <= sizeof(int))) {
+ // Extra casts are used to silence warnings.
+ if (is_signed) {
+ arg_ = detail::make_arg<Context>(
+ static_cast<int>(static_cast<target_type>(value)));
+ } else {
+ using unsigned_type = typename make_unsigned_or_bool<target_type>::type;
+ arg_ = detail::make_arg<Context>(
+ static_cast<unsigned>(static_cast<unsigned_type>(value)));
+ }
+ } else {
+ if (is_signed) {
+ // glibc's printf doesn't sign extend arguments of smaller types:
+ // std::printf("%lld", -42); // prints "4294967254"
+ // but we don't have to do the same because it's a UB.
+ arg_ = detail::make_arg<Context>(static_cast<long long>(value));
+ } else {
+ arg_ = detail::make_arg<Context>(
+ static_cast<typename make_unsigned_or_bool<U>::type>(value));
+ }
+ }
+ }
+
+ template <typename U, FMT_ENABLE_IF(!std::is_integral<U>::value)>
+ void operator()(U) {} // No conversion needed for non-integral types.
+};
+
+// Converts an integer argument to T for printf, if T is an integral type.
+// If T is void, the argument is converted to corresponding signed or unsigned
+// type depending on the type specifier: 'd' and 'i' - signed, other -
+// unsigned).
+template <typename T, typename Context, typename Char>
+void convert_arg(basic_format_arg<Context>& arg, Char type) {
+ visit_format_arg(arg_converter<T, Context>(arg, type), arg);
+}
+
+// Converts an integer argument to char for printf.
+template <typename Context> class char_converter {
+ private:
+ basic_format_arg<Context>& arg_;
+
+ public:
+ explicit char_converter(basic_format_arg<Context>& arg) : arg_(arg) {}
+
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ void operator()(T value) {
+ arg_ = detail::make_arg<Context>(
+ static_cast<typename Context::char_type>(value));
+ }
+
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ void operator()(T) {} // No conversion needed for non-integral types.
+};
+
+// An argument visitor that return a pointer to a C string if argument is a
+// string or null otherwise.
+template <typename Char> struct get_cstring {
+ template <typename T> const Char* operator()(T) { return nullptr; }
+ const Char* operator()(const Char* s) { return s; }
+};
+
+// Checks if an argument is a valid printf width specifier and sets
+// left alignment if it is negative.
+template <typename Char> class printf_width_handler {
+ private:
+ using format_specs = basic_format_specs<Char>;
+
+ format_specs& specs_;
+
+ public:
+ explicit printf_width_handler(format_specs& specs) : specs_(specs) {}
+
+ template <typename T, FMT_ENABLE_IF(std::is_integral<T>::value)>
+ unsigned operator()(T value) {
+ auto width = static_cast<uint32_or_64_or_128_t<T>>(value);
+ if (detail::is_negative(value)) {
+ specs_.align = align::left;
+ width = 0 - width;
+ }
+ unsigned int_max = max_value<int>();
+ if (width > int_max) FMT_THROW(format_error("number is too big"));
+ return static_cast<unsigned>(width);
+ }
+
+ template <typename T, FMT_ENABLE_IF(!std::is_integral<T>::value)>
+ unsigned operator()(T) {
+ FMT_THROW(format_error("width is not integer"));
+ return 0;
+ }
+};
+
+template <typename Char, typename Context>
+void vprintf(buffer<Char>& buf, basic_string_view<Char> format,
+ basic_format_args<Context> args) {
+ Context(buffer_appender<Char>(buf), format, args).format();
+}
+} // namespace detail
+
+// For printing into memory_buffer.
+template <typename Char, typename Context>
+FMT_DEPRECATED void printf(detail::buffer<Char>& buf,
+ basic_string_view<Char> format,
+ basic_format_args<Context> args) {
+ return detail::vprintf(buf, format, args);
+}
+using detail::vprintf;
+
+template <typename Char>
+class basic_printf_parse_context : public basic_format_parse_context<Char> {
+ using basic_format_parse_context<Char>::basic_format_parse_context;
+};
+template <typename OutputIt, typename Char> class basic_printf_context;
+
+/**
+ \rst
+ The ``printf`` argument formatter.
+ \endrst
+ */
+template <typename OutputIt, typename Char>
+class printf_arg_formatter : public detail::arg_formatter_base<OutputIt, Char> {
+ public:
+ using iterator = OutputIt;
+
+ private:
+ using char_type = Char;
+ using base = detail::arg_formatter_base<OutputIt, Char>;
+ using context_type = basic_printf_context<OutputIt, Char>;
+
+ context_type& context_;
+
+ void write_null_pointer(char) {
+ this->specs()->type = 0;
+ this->write("(nil)");
+ }
+
+ void write_null_pointer(wchar_t) {
+ this->specs()->type = 0;
+ this->write(L"(nil)");
+ }
+
+ public:
+ using format_specs = typename base::format_specs;
+
+ /**
+ \rst
+ Constructs an argument formatter object.
+ *buffer* is a reference to the output buffer and *specs* contains format
+ specifier information for standard argument types.
+ \endrst
+ */
+ printf_arg_formatter(iterator iter, format_specs& specs, context_type& ctx)
+ : base(iter, &specs, detail::locale_ref()), context_(ctx) {}
+
+ template <typename T, FMT_ENABLE_IF(fmt::detail::is_integral<T>::value)>
+ iterator operator()(T value) {
+ // MSVC2013 fails to compile separate overloads for bool and char_type so
+ // use std::is_same instead.
+ if (std::is_same<T, bool>::value) {
+ format_specs& fmt_specs = *this->specs();
+ if (fmt_specs.type != 's') return base::operator()(value ? 1 : 0);
+ fmt_specs.type = 0;
+ this->write(value != 0);
+ } else if (std::is_same<T, char_type>::value) {
+ format_specs& fmt_specs = *this->specs();
+ if (fmt_specs.type && fmt_specs.type != 'c')
+ return (*this)(static_cast<int>(value));
+ fmt_specs.sign = sign::none;
+ fmt_specs.alt = false;
+ fmt_specs.fill[0] = ' '; // Ignore '0' flag for char types.
+ // align::numeric needs to be overwritten here since the '0' flag is
+ // ignored for non-numeric types
+ if (fmt_specs.align == align::none || fmt_specs.align == align::numeric)
+ fmt_specs.align = align::right;
+ return base::operator()(value);
+ } else {
+ return base::operator()(value);
+ }
+ return this->out();
+ }
+
+ template <typename T, FMT_ENABLE_IF(std::is_floating_point<T>::value)>
+ iterator operator()(T value) {
+ return base::operator()(value);
+ }
+
+ /** Formats a null-terminated C string. */
+ iterator operator()(const char* value) {
+ if (value)
+ base::operator()(value);
+ else if (this->specs()->type == 'p')
+ write_null_pointer(char_type());
+ else
+ this->write("(null)");
+ return this->out();
+ }
+
+ /** Formats a null-terminated wide C string. */
+ iterator operator()(const wchar_t* value) {
+ if (value)
+ base::operator()(value);
+ else if (this->specs()->type == 'p')
+ write_null_pointer(char_type());
+ else
+ this->write(L"(null)");
+ return this->out();
+ }
+
+ iterator operator()(basic_string_view<char_type> value) {
+ return base::operator()(value);
+ }
+
+ iterator operator()(monostate value) { return base::operator()(value); }
+
+ /** Formats a pointer. */
+ iterator operator()(const void* value) {
+ if (value) return base::operator()(value);
+ this->specs()->type = 0;
+ write_null_pointer(char_type());
+ return this->out();
+ }
+
+ /** Formats an argument of a custom (user-defined) type. */
+ iterator operator()(typename basic_format_arg<context_type>::handle handle) {
+ handle.format(context_.parse_context(), context_);
+ return this->out();
+ }
+};
+
+template <typename T> struct printf_formatter {
+ printf_formatter() = delete;
+
+ template <typename ParseContext>
+ auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
+
+ template <typename FormatContext>
+ auto format(const T& value, FormatContext& ctx) -> decltype(ctx.out()) {
+ detail::format_value(detail::get_container(ctx.out()), value);
+ return ctx.out();
+ }
+};
+
+/**
+ This template formats data and writes the output through an output iterator.
+ */
+template <typename OutputIt, typename Char> class basic_printf_context {
+ public:
+ /** The character type for the output. */
+ using char_type = Char;
+ using iterator = OutputIt;
+ using format_arg = basic_format_arg<basic_printf_context>;
+ using parse_context_type = basic_printf_parse_context<Char>;
+ template <typename T> using formatter_type = printf_formatter<T>;
+
+ private:
+ using format_specs = basic_format_specs<char_type>;
+
+ OutputIt out_;
+ basic_format_args<basic_printf_context> args_;
+ parse_context_type parse_ctx_;
+
+ static void parse_flags(format_specs& specs, const Char*& it,
+ const Char* end);
+
+ // Returns the argument with specified index or, if arg_index is -1, the next
+ // argument.
+ format_arg get_arg(int arg_index = -1);
+
+ // Parses argument index, flags and width and returns the argument index.
+ int parse_header(const Char*& it, const Char* end, format_specs& specs);
+
+ public:
+ /**
+ \rst
+ Constructs a ``printf_context`` object. References to the arguments are
+ stored in the context object so make sure they have appropriate lifetimes.
+ \endrst
+ */
+ basic_printf_context(OutputIt out, basic_string_view<char_type> format_str,
+ basic_format_args<basic_printf_context> args)
+ : out_(out), args_(args), parse_ctx_(format_str) {}
+
+ OutputIt out() { return out_; }
+ void advance_to(OutputIt it) { out_ = it; }
+
+ detail::locale_ref locale() { return {}; }
+
+ format_arg arg(int id) const { return args_.get(id); }
+
+ parse_context_type& parse_context() { return parse_ctx_; }
+
+ FMT_CONSTEXPR void on_error(const char* message) {
+ parse_ctx_.on_error(message);
+ }
+
+ /** Formats stored arguments and writes the output to the range. */
+ template <typename ArgFormatter = printf_arg_formatter<OutputIt, Char>>
+ OutputIt format();
+};
+
+template <typename OutputIt, typename Char>
+void basic_printf_context<OutputIt, Char>::parse_flags(format_specs& specs,
+ const Char*& it,
+ const Char* end) {
+ for (; it != end; ++it) {
+ switch (*it) {
+ case '-':
+ specs.align = align::left;
+ break;
+ case '+':
+ specs.sign = sign::plus;
+ break;
+ case '0':
+ specs.fill[0] = '0';
+ break;
+ case ' ':
+ if (specs.sign != sign::plus) {
+ specs.sign = sign::space;
+ }
+ break;
+ case '#':
+ specs.alt = true;
+ break;
+ default:
+ return;
+ }
+ }
+}
+
+template <typename OutputIt, typename Char>
+typename basic_printf_context<OutputIt, Char>::format_arg
+basic_printf_context<OutputIt, Char>::get_arg(int arg_index) {
+ if (arg_index < 0)
+ arg_index = parse_ctx_.next_arg_id();
+ else
+ parse_ctx_.check_arg_id(--arg_index);
+ return detail::get_arg(*this, arg_index);
+}
+
+template <typename OutputIt, typename Char>
+int basic_printf_context<OutputIt, Char>::parse_header(const Char*& it,
+ const Char* end,
+ format_specs& specs) {
+ int arg_index = -1;
+ char_type c = *it;
+ if (c >= '0' && c <= '9') {
+ // Parse an argument index (if followed by '$') or a width possibly
+ // preceded with '0' flag(s).
+ detail::error_handler eh;
+ int value = parse_nonnegative_int(it, end, eh);
+ if (it != end && *it == '$') { // value is an argument index
+ ++it;
+ arg_index = value;
+ } else {
+ if (c == '0') specs.fill[0] = '0';
+ if (value != 0) {
+ // Nonzero value means that we parsed width and don't need to
+ // parse it or flags again, so return now.
+ specs.width = value;
+ return arg_index;
+ }
+ }
+ }
+ parse_flags(specs, it, end);
+ // Parse width.
+ if (it != end) {
+ if (*it >= '0' && *it <= '9') {
+ detail::error_handler eh;
+ specs.width = parse_nonnegative_int(it, end, eh);
+ } else if (*it == '*') {
+ ++it;
+ specs.width = static_cast<int>(visit_format_arg(
+ detail::printf_width_handler<char_type>(specs), get_arg()));
+ }
+ }
+ return arg_index;
+}
+
+template <typename OutputIt, typename Char>
+template <typename ArgFormatter>
+OutputIt basic_printf_context<OutputIt, Char>::format() {
+ auto out = this->out();
+ const Char* start = parse_ctx_.begin();
+ const Char* end = parse_ctx_.end();
+ auto it = start;
+ while (it != end) {
+ char_type c = *it++;
+ if (c != '%') continue;
+ if (it != end && *it == c) {
+ out = std::copy(start, it, out);
+ start = ++it;
+ continue;
+ }
+ out = std::copy(start, it - 1, out);
+
+ format_specs specs;
+ specs.align = align::right;
+
+ // Parse argument index, flags and width.
+ int arg_index = parse_header(it, end, specs);
+ if (arg_index == 0) on_error("argument not found");
+
+ // Parse precision.
+ if (it != end && *it == '.') {
+ ++it;
+ c = it != end ? *it : 0;
+ if ('0' <= c && c <= '9') {
+ detail::error_handler eh;
+ specs.precision = parse_nonnegative_int(it, end, eh);
+ } else if (c == '*') {
+ ++it;
+ specs.precision = static_cast<int>(
+ visit_format_arg(detail::printf_precision_handler(), get_arg()));
+ } else {
+ specs.precision = 0;
+ }
+ }
+
+ format_arg arg = get_arg(arg_index);
+ // For d, i, o, u, x, and X conversion specifiers, if a precision is
+ // specified, the '0' flag is ignored
+ if (specs.precision >= 0 && arg.is_integral())
+ specs.fill[0] =
+ ' '; // Ignore '0' flag for non-numeric types or if '-' present.
+ if (specs.precision >= 0 && arg.type() == detail::type::cstring_type) {
+ auto str = visit_format_arg(detail::get_cstring<Char>(), arg);
+ auto str_end = str + specs.precision;
+ auto nul = std::find(str, str_end, Char());
+ arg = detail::make_arg<basic_printf_context>(basic_string_view<Char>(
+ str,
+ detail::to_unsigned(nul != str_end ? nul - str : specs.precision)));
+ }
+ if (specs.alt && visit_format_arg(detail::is_zero_int(), arg))
+ specs.alt = false;
+ if (specs.fill[0] == '0') {
+ if (arg.is_arithmetic() && specs.align != align::left)
+ specs.align = align::numeric;
+ else
+ specs.fill[0] = ' '; // Ignore '0' flag for non-numeric types or if '-'
+ // flag is also present.
+ }
+
+ // Parse length and convert the argument to the required type.
+ c = it != end ? *it++ : 0;
+ char_type t = it != end ? *it : 0;
+ using detail::convert_arg;
+ switch (c) {
+ case 'h':
+ if (t == 'h') {
+ ++it;
+ t = it != end ? *it : 0;
+ convert_arg<signed char>(arg, t);
+ } else {
+ convert_arg<short>(arg, t);
+ }
+ break;
+ case 'l':
+ if (t == 'l') {
+ ++it;
+ t = it != end ? *it : 0;
+ convert_arg<long long>(arg, t);
+ } else {
+ convert_arg<long>(arg, t);
+ }
+ break;
+ case 'j':
+ convert_arg<intmax_t>(arg, t);
+ break;
+ case 'z':
+ convert_arg<size_t>(arg, t);
+ break;
+ case 't':
+ convert_arg<std::ptrdiff_t>(arg, t);
+ break;
+ case 'L':
+ // printf produces garbage when 'L' is omitted for long double, no
+ // need to do the same.
+ break;
+ default:
+ --it;
+ convert_arg<void>(arg, c);
+ }
+
+ // Parse type.
+ if (it == end) FMT_THROW(format_error("invalid format string"));
+ specs.type = static_cast<char>(*it++);
+ if (arg.is_integral()) {
+ // Normalize type.
+ switch (specs.type) {
+ case 'i':
+ case 'u':
+ specs.type = 'd';
+ break;
+ case 'c':
+ visit_format_arg(detail::char_converter<basic_printf_context>(arg),
+ arg);
+ break;
+ }
+ }
+
+ start = it;
+
+ // Format argument.
+ out = visit_format_arg(ArgFormatter(out, specs, *this), arg);
+ }
+ return std::copy(start, it, out);
+}
+
+template <typename Char>
+using basic_printf_context_t =
+ basic_printf_context<detail::buffer_appender<Char>, Char>;
+
+using printf_context = basic_printf_context_t<char>;
+using wprintf_context = basic_printf_context_t<wchar_t>;
+
+using printf_args = basic_format_args<printf_context>;
+using wprintf_args = basic_format_args<wprintf_context>;
+
+/**
+ \rst
+ Constructs an `~fmt::format_arg_store` object that contains references to
+ arguments and can be implicitly converted to `~fmt::printf_args`.
+ \endrst
+ */
+template <typename... Args>
+inline format_arg_store<printf_context, Args...> make_printf_args(
+ const Args&... args) {
+ return {args...};
+}
+
+/**
+ \rst
+ Constructs an `~fmt::format_arg_store` object that contains references to
+ arguments and can be implicitly converted to `~fmt::wprintf_args`.
+ \endrst
+ */
+template <typename... Args>
+inline format_arg_store<wprintf_context, Args...> make_wprintf_args(
+ const Args&... args) {
+ return {args...};
+}
+
+template <typename S, typename Char = char_t<S>>
+inline std::basic_string<Char> vsprintf(
+ const S& format,
+ basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buffer;
+ vprintf(buffer, to_string_view(format), args);
+ return to_string(buffer);
+}
+
+/**
+ \rst
+ Formats arguments and returns the result as a string.
+
+ **Example**::
+
+ std::string message = fmt::sprintf("The answer is %d", 42);
+ \endrst
+*/
+template <typename S, typename... Args,
+ typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
+inline std::basic_string<Char> sprintf(const S& format, const Args&... args) {
+ using context = basic_printf_context_t<Char>;
+ return vsprintf(to_string_view(format), make_format_args<context>(args...));
+}
+
+template <typename S, typename Char = char_t<S>>
+inline int vfprintf(
+ std::FILE* f, const S& format,
+ basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buffer;
+ vprintf(buffer, to_string_view(format), args);
+ size_t size = buffer.size();
+ return std::fwrite(buffer.data(), sizeof(Char), size, f) < size
+ ? -1
+ : static_cast<int>(size);
+}
+
+/**
+ \rst
+ Prints formatted data to the file *f*.
+
+ **Example**::
+
+ fmt::fprintf(stderr, "Don't %s!", "panic");
+ \endrst
+ */
+template <typename S, typename... Args,
+ typename Char = enable_if_t<detail::is_string<S>::value, char_t<S>>>
+inline int fprintf(std::FILE* f, const S& format, const Args&... args) {
+ using context = basic_printf_context_t<Char>;
+ return vfprintf(f, to_string_view(format),
+ make_format_args<context>(args...));
+}
+
+template <typename S, typename Char = char_t<S>>
+inline int vprintf(
+ const S& format,
+ basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
+ return vfprintf(stdout, to_string_view(format), args);
+}
+
+/**
+ \rst
+ Prints formatted data to ``stdout``.
+
+ **Example**::
+
+ fmt::printf("Elapsed time: %.2f seconds", 1.23);
+ \endrst
+ */
+template <typename S, typename... Args,
+ FMT_ENABLE_IF(detail::is_string<S>::value)>
+inline int printf(const S& format_str, const Args&... args) {
+ using context = basic_printf_context_t<char_t<S>>;
+ return vprintf(to_string_view(format_str),
+ make_format_args<context>(args...));
+}
+
+template <typename S, typename Char = char_t<S>>
+inline int vfprintf(
+ std::basic_ostream<Char>& os, const S& format,
+ basic_format_args<basic_printf_context_t<type_identity_t<Char>>> args) {
+ basic_memory_buffer<Char> buffer;
+ vprintf(buffer, to_string_view(format), args);
+ detail::write_buffer(os, buffer);
+ return static_cast<int>(buffer.size());
+}
+
+/** Formats arguments and writes the output to the range. */
+template <typename ArgFormatter, typename Char,
+ typename Context =
+ basic_printf_context<typename ArgFormatter::iterator, Char>>
+typename ArgFormatter::iterator vprintf(
+ detail::buffer<Char>& out, basic_string_view<Char> format_str,
+ basic_format_args<type_identity_t<Context>> args) {
+ typename ArgFormatter::iterator iter(out);
+ Context(iter, format_str, args).template format<ArgFormatter>();
+ return iter;
+}
+
+/**
+ \rst
+ Prints formatted data to the stream *os*.
+
+ **Example**::
+
+ fmt::fprintf(cerr, "Don't %s!", "panic");
+ \endrst
+ */
+template <typename S, typename... Args, typename Char = char_t<S>>
+inline int fprintf(std::basic_ostream<Char>& os, const S& format_str,
+ const Args&... args) {
+ using context = basic_printf_context_t<Char>;
+ return vfprintf(os, to_string_view(format_str),
+ make_format_args<context>(args...));
+}
+FMT_END_NAMESPACE
+
+#endif // FMT_PRINTF_H_
diff --git a/include/spdlog/fmt/bundled/ranges.h b/include/spdlog/fmt/bundled/ranges.h
new file mode 100644
index 00000000..632f0494
--- /dev/null
+++ b/include/spdlog/fmt/bundled/ranges.h
@@ -0,0 +1,396 @@
+// Formatting library for C++ - experimental range support
+//
+// Copyright (c) 2012 - present, Victor Zverovich
+// All rights reserved.
+//
+// For the license information refer to format.h.
+//
+// Copyright (c) 2018 - present, Remotion (Igor Schulz)
+// All Rights Reserved
+// {fmt} support for ranges, containers and types tuple interface.
+
+#ifndef FMT_RANGES_H_
+#define FMT_RANGES_H_
+
+#include <initializer_list>
+#include <type_traits>
+
+#include "format.h"
+
+// output only up to N items from the range.
+#ifndef FMT_RANGE_OUTPUT_LENGTH_LIMIT
+# define FMT_RANGE_OUTPUT_LENGTH_LIMIT 256
+#endif
+
+FMT_BEGIN_NAMESPACE
+
+template <typename Char> struct formatting_base {
+ template <typename ParseContext>
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
+};
+
+template <typename Char, typename Enable = void>
+struct formatting_range : formatting_base<Char> {
+ static FMT_CONSTEXPR_DECL const size_t range_length_limit =
+ FMT_RANGE_OUTPUT_LENGTH_LIMIT; // output only up to N items from the
+ // range.
+ Char prefix;
+ Char delimiter;
+ Char postfix;
+ formatting_range() : prefix('{'), delimiter(','), postfix('}') {}
+ static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true;
+ static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false;
+};
+
+template <typename Char, typename Enable = void>
+struct formatting_tuple : formatting_base<Char> {
+ Char prefix;
+ Char delimiter;
+ Char postfix;
+ formatting_tuple() : prefix('('), delimiter(','), postfix(')') {}
+ static FMT_CONSTEXPR_DECL const bool add_delimiter_spaces = true;
+ static FMT_CONSTEXPR_DECL const bool add_prepostfix_space = false;
+};
+
+namespace detail {
+
+template <typename RangeT, typename OutputIterator>
+OutputIterator copy(const RangeT& range, OutputIterator out) {
+ for (auto it = range.begin(), end = range.end(); it != end; ++it)
+ *out++ = *it;
+ return out;
+}
+
+template <typename OutputIterator>
+OutputIterator copy(const char* str, OutputIterator out) {
+ while (*str) *out++ = *str++;
+ return out;
+}
+
+template <typename OutputIterator>
+OutputIterator copy(char ch, OutputIterator out) {
+ *out++ = ch;
+ return out;
+}
+
+/// Return true value if T has std::string interface, like std::string_view.
+template <typename T> class is_like_std_string {
+ template <typename U>
+ static auto check(U* p)
+ -> decltype((void)p->find('a'), p->length(), (void)p->data(), int());
+ template <typename> static void check(...);
+
+ public:
+ static FMT_CONSTEXPR_DECL const bool value =
+ is_string<T>::value || !std::is_void<decltype(check<T>(nullptr))>::value;
+};
+
+template <typename Char>
+struct is_like_std_string<fmt::basic_string_view<Char>> : std::true_type {};
+
+template <typename... Ts> struct conditional_helper {};
+
+template <typename T, typename _ = void> struct is_range_ : std::false_type {};
+
+#if !FMT_MSC_VER || FMT_MSC_VER > 1800
+template <typename T>
+struct is_range_<
+ T, conditional_t<false,
+ conditional_helper<decltype(std::declval<T>().begin()),
+ decltype(std::declval<T>().end())>,
+ void>> : std::true_type {};
+#endif
+
+/// tuple_size and tuple_element check.
+template <typename T> class is_tuple_like_ {
+ template <typename U>
+ static auto check(U* p) -> decltype(std::tuple_size<U>::value, int());
+ template <typename> static void check(...);
+
+ public:
+ static FMT_CONSTEXPR_DECL const bool value =
+ !std::is_void<decltype(check<T>(nullptr))>::value;
+};
+
+// Check for integer_sequence
+#if defined(__cpp_lib_integer_sequence) || FMT_MSC_VER >= 1900
+template <typename T, T... N>
+using integer_sequence = std::integer_sequence<T, N...>;
+template <size_t... N> using index_sequence = std::index_sequence<N...>;
+template <size_t N> using make_index_sequence = std::make_index_sequence<N>;
+#else
+template <typename T, T... N> struct integer_sequence {
+ using value_type = T;
+
+ static FMT_CONSTEXPR size_t size() { return sizeof...(N); }
+};
+
+template <size_t... N> using index_sequence = integer_sequence<size_t, N...>;
+
+template <typename T, size_t N, T... Ns>
+struct make_integer_sequence : make_integer_sequence<T, N - 1, N - 1, Ns...> {};
+template <typename T, T... Ns>
+struct make_integer_sequence<T, 0, Ns...> : integer_sequence<T, Ns...> {};
+
+template <size_t N>
+using make_index_sequence = make_integer_sequence<size_t, N>;
+#endif
+
+template <class Tuple, class F, size_t... Is>
+void for_each(index_sequence<Is...>, Tuple&& tup, F&& f) FMT_NOEXCEPT {
+ using std::get;
+ // using free function get<I>(T) now.
+ const int _[] = {0, ((void)f(get<Is>(tup)), 0)...};
+ (void)_; // blocks warnings
+}
+
+template <class T>
+FMT_CONSTEXPR make_index_sequence<std::tuple_size<T>::value> get_indexes(
+ T const&) {
+ return {};
+}
+
+template <class Tuple, class F> void for_each(Tuple&& tup, F&& f) {
+ const auto indexes = get_indexes(tup);
+ for_each(indexes, std::forward<Tuple>(tup), std::forward<F>(f));
+}
+
+template <typename Range>
+using value_type = remove_cvref_t<decltype(*std::declval<Range>().begin())>;
+
+template <typename Arg, FMT_ENABLE_IF(!is_like_std_string<
+ typename std::decay<Arg>::type>::value)>
+FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
+ return add_space ? " {}" : "{}";
+}
+
+template <typename Arg, FMT_ENABLE_IF(is_like_std_string<
+ typename std::decay<Arg>::type>::value)>
+FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const Arg&) {
+ return add_space ? " \"{}\"" : "\"{}\"";
+}
+
+FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char*) {
+ return add_space ? " \"{}\"" : "\"{}\"";
+}
+FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t*) {
+ return add_space ? L" \"{}\"" : L"\"{}\"";
+}
+
+FMT_CONSTEXPR const char* format_str_quoted(bool add_space, const char) {
+ return add_space ? " '{}'" : "'{}'";
+}
+FMT_CONSTEXPR const wchar_t* format_str_quoted(bool add_space, const wchar_t) {
+ return add_space ? L" '{}'" : L"'{}'";
+}
+} // namespace detail
+
+template <typename T> struct is_tuple_like {
+ static FMT_CONSTEXPR_DECL const bool value =
+ detail::is_tuple_like_<T>::value && !detail::is_range_<T>::value;
+};
+
+template <typename TupleT, typename Char>
+struct formatter<TupleT, Char, enable_if_t<fmt::is_tuple_like<TupleT>::value>> {
+ private:
+ // C++11 generic lambda for format()
+ template <typename FormatContext> struct format_each {
+ template <typename T> void operator()(const T& v) {
+ if (i > 0) {
+ if (formatting.add_prepostfix_space) {
+ *out++ = ' ';
+ }
+ out = detail::copy(formatting.delimiter, out);
+ }
+ out = format_to(out,
+ detail::format_str_quoted(
+ (formatting.add_delimiter_spaces && i > 0), v),
+ v);
+ ++i;
+ }
+
+ formatting_tuple<Char>& formatting;
+ size_t& i;
+ typename std::add_lvalue_reference<decltype(
+ std::declval<FormatContext>().out())>::type out;
+ };
+
+ public:
+ formatting_tuple<Char> formatting;
+
+ template <typename ParseContext>
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ return formatting.parse(ctx);
+ }
+
+ template <typename FormatContext = format_context>
+ auto format(const TupleT& values, FormatContext& ctx) -> decltype(ctx.out()) {
+ auto out = ctx.out();
+ size_t i = 0;
+ detail::copy(formatting.prefix, out);
+
+ detail::for_each(values, format_each<FormatContext>{formatting, i, out});
+ if (formatting.add_prepostfix_space) {
+ *out++ = ' ';
+ }
+ detail::copy(formatting.postfix, out);
+
+ return ctx.out();
+ }
+};
+
+template <typename T, typename Char> struct is_range {
+ static FMT_CONSTEXPR_DECL const bool value =
+ detail::is_range_<T>::value && !detail::is_like_std_string<T>::value &&
+ !std::is_convertible<T, std::basic_string<Char>>::value &&
+ !std::is_constructible<detail::std_string_view<Char>, T>::value;
+};
+
+template <typename T, typename Char>
+struct formatter<
+ T, Char,
+ enable_if_t<fmt::is_range<T, Char>::value
+// Workaround a bug in MSVC 2017 and earlier.
+#if !FMT_MSC_VER || FMT_MSC_VER >= 1927
+ &&
+ (has_formatter<detail::value_type<T>, format_context>::value ||
+ detail::has_fallback_formatter<detail::value_type<T>,
+ format_context>::value)
+#endif
+ >> {
+ formatting_range<Char> formatting;
+
+ template <typename ParseContext>
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ return formatting.parse(ctx);
+ }
+
+ template <typename FormatContext>
+ typename FormatContext::iterator format(const T& values, FormatContext& ctx) {
+ auto out = detail::copy(formatting.prefix, ctx.out());
+ size_t i = 0;
+ auto it = values.begin();
+ auto end = values.end();
+ for (; it != end; ++it) {
+ if (i > 0) {
+ if (formatting.add_prepostfix_space) *out++ = ' ';
+ out = detail::copy(formatting.delimiter, out);
+ }
+ out = format_to(out,
+ detail::format_str_quoted(
+ (formatting.add_delimiter_spaces && i > 0), *it),
+ *it);
+ if (++i > formatting.range_length_limit) {
+ out = format_to(out, " ... <other elements>");
+ break;
+ }
+ }
+ if (formatting.add_prepostfix_space) *out++ = ' ';
+ return detail::copy(formatting.postfix, out);
+ }
+};
+
+template <typename Char, typename... T> struct tuple_arg_join : detail::view {
+ const std::tuple<T...>& tuple;
+ basic_string_view<Char> sep;
+
+ tuple_arg_join(const std::tuple<T...>& t, basic_string_view<Char> s)
+ : tuple{t}, sep{s} {}
+};
+
+template <typename Char, typename... T>
+struct formatter<tuple_arg_join<Char, T...>, Char> {
+ template <typename ParseContext>
+ FMT_CONSTEXPR auto parse(ParseContext& ctx) -> decltype(ctx.begin()) {
+ return ctx.begin();
+ }
+
+ template <typename FormatContext>
+ typename FormatContext::iterator format(
+ const tuple_arg_join<Char, T...>& value, FormatContext& ctx) {
+ return format(value, ctx, detail::make_index_sequence<sizeof...(T)>{});
+ }
+
+ private:
+ template <typename FormatContext, size_t... N>
+ typename FormatContext::iterator format(
+ const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
+ detail::index_sequence<N...>) {
+ return format_args(value, ctx, std::get<N>(value.tuple)...);
+ }
+
+ template <typename FormatContext>
+ typename FormatContext::iterator format_args(
+ const tuple_arg_join<Char, T...>&, FormatContext& ctx) {
+ // NOTE: for compilers that support C++17, this empty function instantiation
+ // can be replaced with a constexpr branch in the variadic overload.
+ return ctx.out();
+ }
+
+ template <typename FormatContext, typename Arg, typename... Args>
+ typename FormatContext::iterator format_args(
+ const tuple_arg_join<Char, T...>& value, FormatContext& ctx,
+ const Arg& arg, const Args&... args) {
+ using base = formatter<typename std::decay<Arg>::type, Char>;
+ auto out = ctx.out();
+ out = base{}.format(arg, ctx);
+ if (sizeof...(Args) > 0) {
+ out = std::copy(value.sep.begin(), value.sep.end(), out);
+ ctx.advance_to(out);
+ return format_args(value, ctx, args...);
+ }
+ return out;
+ }
+};
+
+/**
+ \rst
+ Returns an object that formats `tuple` with elements separated by `sep`.
+
+ **Example**::
+
+ std::tuple<int, char> t = {1, 'a'};
+ fmt::print("{}", fmt::join(t, ", "));
+ // Output: "1, a"
+ \endrst
+ */
+template <typename... T>
+FMT_CONSTEXPR tuple_arg_join<char, T...> join(const std::tuple<T...>& tuple,
+ string_view sep) {
+ return {tuple, sep};
+}
+
+template <typename... T>
+FMT_CONSTEXPR tuple_arg_join<wchar_t, T...> join(const std::tuple<T...>& tuple,
+ wstring_view sep) {
+ return {tuple, sep};
+}
+
+/**
+ \rst
+ Returns an object that formats `initializer_list` with elements separated by
+ `sep`.
+
+ **Example**::
+
+ fmt::print("{}", fmt::join({1, 2, 3}, ", "));
+ // Output: "1, 2, 3"
+ \endrst
+ */
+template <typename T>
+arg_join<const T*, const T*, char> join(std::initializer_list<T> list,
+ string_view sep) {
+ return join(std::begin(list), std::end(list), sep);
+}
+
+template <typename T>
+arg_join<const T*, const T*, wchar_t> join(std::initializer_list<T> list,
+ wstring_view sep) {
+ return join(std::begin(list), std::end(list), sep);
+}
+
+FMT_END_NAMESPACE
+
+#endif // FMT_RANGES_H_
diff --git a/include/spdlog/fmt/chrono.h b/include/spdlog/fmt/chrono.h
new file mode 100644
index 00000000..e1fb7a06
--- /dev/null
+++ b/include/spdlog/fmt/chrono.h
@@ -0,0 +1,20 @@
+//
+// Copyright(c) 2016 Gabi Melman.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+//
+
+#pragma once
+//
+// include bundled or external copy of fmtlib's chrono support
+//
+
+#if !defined(SPDLOG_FMT_EXTERNAL)
+#ifdef SPDLOG_HEADER_ONLY
+#ifndef FMT_HEADER_ONLY
+#define FMT_HEADER_ONLY
+#endif
+#endif
+#include <spdlog/fmt/bundled/chrono.h>
+#else
+#include <fmt/chrono.h>
+#endif
diff --git a/include/spdlog/fmt/fmt.h b/include/spdlog/fmt/fmt.h
new file mode 100644
index 00000000..ec10ac33
--- /dev/null
+++ b/include/spdlog/fmt/fmt.h
@@ -0,0 +1,27 @@
+//
+// Copyright(c) 2016-2018 Gabi Melman.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+//
+
+#pragma once
+
+//
+// Include a bundled header-only copy of fmtlib or an external one.
+// By default spdlog include its own copy.
+//
+
+#if !defined(SPDLOG_FMT_EXTERNAL)
+#if !defined(SPDLOG_COMPILED_LIB) && !defined(FMT_HEADER_ONLY)
+#define FMT_HEADER_ONLY
+#endif
+#ifndef FMT_USE_WINDOWS_H
+#define FMT_USE_WINDOWS_H 0
+#endif
+// enable the 'n' flag in for backward compatibility with fmt 6.x
+#define FMT_DEPRECATED_N_SPECIFIER
+#include <spdlog/fmt/bundled/core.h>
+#include <spdlog/fmt/bundled/format.h>
+#else // SPDLOG_FMT_EXTERNAL is defined - use external fmtlib
+#include <fmt/core.h>
+#include <fmt/format.h>
+#endif
diff --git a/include/spdlog/fmt/ostr.h b/include/spdlog/fmt/ostr.h
new file mode 100644
index 00000000..f82eb679
--- /dev/null
+++ b/include/spdlog/fmt/ostr.h
@@ -0,0 +1,20 @@
+//
+// Copyright(c) 2016 Gabi Melman.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+//
+
+#pragma once
+//
+// include bundled or external copy of fmtlib's ostream support
+//
+
+#if !defined(SPDLOG_FMT_EXTERNAL)
+#ifdef SPDLOG_HEADER_ONLY
+#ifndef FMT_HEADER_ONLY
+#define FMT_HEADER_ONLY
+#endif
+#endif
+#include <spdlog/fmt/bundled/ostream.h>
+#else
+#include <fmt/ostream.h>
+#endif
diff --git a/include/spdlog/formatter.h b/include/spdlog/formatter.h
new file mode 100644
index 00000000..5086fb21
--- /dev/null
+++ b/include/spdlog/formatter.h
@@ -0,0 +1,18 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/fmt/fmt.h>
+#include <spdlog/details/log_msg.h>
+
+namespace spdlog {
+
+class formatter
+{
+public:
+ virtual ~formatter() = default;
+ virtual void format(const details::log_msg &msg, memory_buf_t &dest) = 0;
+ virtual std::unique_ptr<formatter> clone() const = 0;
+};
+} // namespace spdlog
diff --git a/include/spdlog/fwd.h b/include/spdlog/fwd.h
new file mode 100644
index 00000000..cc05ddd4
--- /dev/null
+++ b/include/spdlog/fwd.h
@@ -0,0 +1,14 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+namespace spdlog {
+class logger;
+class formatter;
+
+namespace sinks {
+class sink;
+}
+
+} // namespace spdlog
diff --git a/include/spdlog/logger-inl.h b/include/spdlog/logger-inl.h
new file mode 100644
index 00000000..d01c08da
--- /dev/null
+++ b/include/spdlog/logger-inl.h
@@ -0,0 +1,257 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/logger.h>
+#endif
+
+#include <spdlog/sinks/sink.h>
+#include <spdlog/details/backtracer.h>
+#include <spdlog/pattern_formatter.h>
+
+#include <cstdio>
+
+namespace spdlog {
+
+// public methods
+SPDLOG_INLINE logger::logger(const logger &other)
+ : name_(other.name_)
+ , sinks_(other.sinks_)
+ , level_(other.level_.load(std::memory_order_relaxed))
+ , flush_level_(other.flush_level_.load(std::memory_order_relaxed))
+ , custom_err_handler_(other.custom_err_handler_)
+ , tracer_(other.tracer_)
+{}
+
+SPDLOG_INLINE logger::logger(logger &&other) SPDLOG_NOEXCEPT : name_(std::move(other.name_)),
+ sinks_(std::move(other.sinks_)),
+ level_(other.level_.load(std::memory_order_relaxed)),
+ flush_level_(other.flush_level_.load(std::memory_order_relaxed)),
+ custom_err_handler_(std::move(other.custom_err_handler_)),
+ tracer_(std::move(other.tracer_))
+
+{}
+
+SPDLOG_INLINE logger &logger::operator=(logger other) SPDLOG_NOEXCEPT
+{
+ this->swap(other);
+ return *this;
+}
+
+SPDLOG_INLINE void logger::swap(spdlog::logger &other) SPDLOG_NOEXCEPT
+{
+ name_.swap(other.name_);
+ sinks_.swap(other.sinks_);
+
+ // swap level_
+ auto other_level = other.level_.load();
+ auto my_level = level_.exchange(other_level);
+ other.level_.store(my_level);
+
+ // swap flush level_
+ other_level = other.flush_level_.load();
+ my_level = flush_level_.exchange(other_level);
+ other.flush_level_.store(my_level);
+
+ custom_err_handler_.swap(other.custom_err_handler_);
+ std::swap(tracer_, other.tracer_);
+}
+
+SPDLOG_INLINE void swap(logger &a, logger &b)
+{
+ a.swap(b);
+}
+
+SPDLOG_INLINE void logger::set_level(level::level_enum log_level)
+{
+ level_.store(log_level);
+}
+
+SPDLOG_INLINE level::level_enum logger::level() const
+{
+ return static_cast<level::level_enum>(level_.load(std::memory_order_relaxed));
+}
+
+SPDLOG_INLINE const std::string &logger::name() const
+{
+ return name_;
+}
+
+// set formatting for the sinks in this logger.
+// each sink will get a separate instance of the formatter object.
+SPDLOG_INLINE void logger::set_formatter(std::unique_ptr<formatter> f)
+{
+ for (auto it = sinks_.begin(); it != sinks_.end(); ++it)
+ {
+ if (std::next(it) == sinks_.end())
+ {
+ // last element - we can be move it.
+ (*it)->set_formatter(std::move(f));
+ break; // to prevent clang-tidy warning
+ }
+ else
+ {
+ (*it)->set_formatter(f->clone());
+ }
+ }
+}
+
+SPDLOG_INLINE void logger::set_pattern(std::string pattern, pattern_time_type time_type)
+{
+ auto new_formatter = details::make_unique<pattern_formatter>(std::move(pattern), time_type);
+ set_formatter(std::move(new_formatter));
+}
+
+// create new backtrace sink and move to it all our child sinks
+SPDLOG_INLINE void logger::enable_backtrace(size_t n_messages)
+{
+ tracer_.enable(n_messages);
+}
+
+// restore orig sinks and level and delete the backtrace sink
+SPDLOG_INLINE void logger::disable_backtrace()
+{
+ tracer_.disable();
+}
+
+SPDLOG_INLINE void logger::dump_backtrace()
+{
+ dump_backtrace_();
+}
+
+// flush functions
+SPDLOG_INLINE void logger::flush()
+{
+ flush_();
+}
+
+SPDLOG_INLINE void logger::flush_on(level::level_enum log_level)
+{
+ flush_level_.store(log_level);
+}
+
+SPDLOG_INLINE level::level_enum logger::flush_level() const
+{
+ return static_cast<level::level_enum>(flush_level_.load(std::memory_order_relaxed));
+}
+
+// sinks
+SPDLOG_INLINE const std::vector<sink_ptr> &logger::sinks() const
+{
+ return sinks_;
+}
+
+SPDLOG_INLINE std::vector<sink_ptr> &logger::sinks()
+{
+ return sinks_;
+}
+
+// error handler
+SPDLOG_INLINE void logger::set_error_handler(err_handler handler)
+{
+ custom_err_handler_ = std::move(handler);
+}
+
+// create new logger with same sinks and configuration.
+SPDLOG_INLINE std::shared_ptr<logger> logger::clone(std::string logger_name)
+{
+ auto cloned = std::make_shared<logger>(*this);
+ cloned->name_ = std::move(logger_name);
+ return cloned;
+}
+
+// protected methods
+SPDLOG_INLINE void logger::log_it_(const spdlog::details::log_msg &log_msg, bool log_enabled, bool traceback_enabled)
+{
+ if (log_enabled)
+ {
+ sink_it_(log_msg);
+ }
+ if (traceback_enabled)
+ {
+ tracer_.push_back(log_msg);
+ }
+}
+
+SPDLOG_INLINE void logger::sink_it_(const details::log_msg &msg)
+{
+ for (auto &sink : sinks_)
+ {
+ if (sink->should_log(msg.level))
+ {
+ SPDLOG_TRY
+ {
+ sink->log(msg);
+ }
+ SPDLOG_LOGGER_CATCH()
+ }
+ }
+
+ if (should_flush_(msg))
+ {
+ flush_();
+ }
+}
+
+SPDLOG_INLINE void logger::flush_()
+{
+ for (auto &sink : sinks_)
+ {
+ SPDLOG_TRY
+ {
+ sink->flush();
+ }
+ SPDLOG_LOGGER_CATCH()
+ }
+}
+
+SPDLOG_INLINE void logger::dump_backtrace_()
+{
+ using details::log_msg;
+ if (tracer_.enabled())
+ {
+ sink_it_(log_msg{name(), level::info, "****************** Backtrace Start ******************"});
+ tracer_.foreach_pop([this](const log_msg &msg) { this->sink_it_(msg); });
+ sink_it_(log_msg{name(), level::info, "****************** Backtrace End ********************"});
+ }
+}
+
+SPDLOG_INLINE bool logger::should_flush_(const details::log_msg &msg)
+{
+ auto flush_level = flush_level_.load(std::memory_order_relaxed);
+ return (msg.level >= flush_level) && (msg.level != level::off);
+}
+
+SPDLOG_INLINE void logger::err_handler_(const std::string &msg)
+{
+ if (custom_err_handler_)
+ {
+ custom_err_handler_(msg);
+ }
+ else
+ {
+ using std::chrono::system_clock;
+ static std::mutex mutex;
+ static std::chrono::system_clock::time_point last_report_time;
+ static size_t err_counter = 0;
+ std::lock_guard<std::mutex> lk{mutex};
+ auto now = system_clock::now();
+ err_counter++;
+ if (now - last_report_time < std::chrono::seconds(1))
+ {
+ return;
+ }
+ last_report_time = now;
+ auto tm_time = details::os::localtime(system_clock::to_time_t(now));
+ char date_buf[64];
+ std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time);
+#if defined(USING_R) && defined(R_R_H) // if in R environment
+ REprintf("[*** LOG ERROR #%04zu ***] [%s] [%s] {%s}\n", err_counter, date_buf, name().c_str(), msg.c_str());
+#else
+ std::fprintf(stderr, "[*** LOG ERROR #%04zu ***] [%s] [%s] {%s}\n", err_counter, date_buf, name().c_str(), msg.c_str());
+#endif
+ }
+}
+} // namespace spdlog
diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h
new file mode 100644
index 00000000..a34c5221
--- /dev/null
+++ b/include/spdlog/logger.h
@@ -0,0 +1,366 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+// Thread safe logger (except for set_error_handler())
+// Has name, log level, vector of std::shared sink pointers and formatter
+// Upon each log write the logger:
+// 1. Checks if its log level is enough to log the message and if yes:
+// 2. Call the underlying sinks to do the job.
+// 3. Each sink use its own private copy of a formatter to format the message
+// and send to its destination.
+//
+// The use of private formatter per sink provides the opportunity to cache some
+// formatted data, and support for different format per sink.
+
+#include <spdlog/common.h>
+#include <spdlog/details/log_msg.h>
+#include <spdlog/details/backtracer.h>
+
+#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
+#include <spdlog/details/os.h>
+#endif
+
+#include <vector>
+#ifndef SPDLOG_NO_EXCEPTIONS
+#define SPDLOG_LOGGER_CATCH() \
+ catch (const std::exception &ex) \
+ { \
+ err_handler_(ex.what()); \
+ } \
+ catch (...) \
+ { \
+ err_handler_("Unknown exception in logger"); \
+ }
+#else
+#define SPDLOG_LOGGER_CATCH()
+#endif
+
+namespace spdlog {
+
+class SPDLOG_API logger
+{
+public:
+ // Empty logger
+ explicit logger(std::string name)
+ : name_(std::move(name))
+ , sinks_()
+ {}
+
+ // Logger with range on sinks
+ template<typename It>
+ logger(std::string name, It begin, It end)
+ : name_(std::move(name))
+ , sinks_(begin, end)
+ {}
+
+ // Logger with single sink
+ logger(std::string name, sink_ptr single_sink)
+ : logger(std::move(name), {std::move(single_sink)})
+ {}
+
+ // Logger with sinks init list
+ logger(std::string name, sinks_init_list sinks)
+ : logger(std::move(name), sinks.begin(), sinks.end())
+ {}
+
+ virtual ~logger() = default;
+
+ logger(const logger &other);
+ logger(logger &&other) SPDLOG_NOEXCEPT;
+ logger &operator=(logger other) SPDLOG_NOEXCEPT;
+
+ void swap(spdlog::logger &other) SPDLOG_NOEXCEPT;
+
+ // FormatString is a type derived from fmt::compile_string
+ template<typename FormatString, typename std::enable_if<fmt::is_compile_string<FormatString>::value, int>::type = 0, typename... Args>
+ void log(source_loc loc, level::level_enum lvl, const FormatString &fmt, Args&&...args)
+ {
+ log_(loc, lvl, fmt, std::forward<Args>(args)...);
+ }
+
+ // FormatString is NOT a type derived from fmt::compile_string but is a string_view_t or can be implicitly converted to one
+ template<typename... Args>
+ void log(source_loc loc, level::level_enum lvl, string_view_t fmt, Args&&...args)
+ {
+ log_(loc, lvl, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename FormatString, typename... Args>
+ void log(level::level_enum lvl, const FormatString &fmt, Args&&...args)
+ {
+ log(source_loc{}, lvl, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename FormatString, typename... Args>
+ void trace(const FormatString &fmt, Args&&...args)
+ {
+ log(level::trace, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename FormatString, typename... Args>
+ void debug(const FormatString &fmt, Args&&...args)
+ {
+ log(level::debug, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename FormatString, typename... Args>
+ void info(const FormatString &fmt, Args&&...args)
+ {
+ log(level::info, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename FormatString, typename... Args>
+ void warn(const FormatString &fmt, Args&&...args)
+ {
+ log(level::warn, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename FormatString, typename... Args>
+ void error(const FormatString &fmt, Args&&...args)
+ {
+ log(level::err, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename FormatString, typename... Args>
+ void critical(const FormatString &fmt, Args&&...args)
+ {
+ log(level::critical, fmt, std::forward<Args>(args)...);
+ }
+
+ template<typename T>
+ void log(level::level_enum lvl, const T &msg)
+ {
+ log(source_loc{}, lvl, msg);
+ }
+
+ // T can be statically converted to string_view and isn't a fmt::compile_string
+ template<class T, typename std::enable_if<
+ std::is_convertible<const T &, spdlog::string_view_t>::value && !fmt::is_compile_string<T>::value, int>::type = 0>
+ void log(source_loc loc, level::level_enum lvl, const T &msg)
+ {
+ log(loc, lvl, string_view_t{msg});
+ }
+
+ void log(log_clock::time_point log_time, source_loc loc, level::level_enum lvl, string_view_t msg)
+ {
+ bool log_enabled = should_log(lvl);
+ bool traceback_enabled = tracer_.enabled();
+ if (!log_enabled && !traceback_enabled)
+ {
+ return;
+ }
+
+ details::log_msg log_msg(log_time, loc, name_, lvl, msg);
+ log_it_(log_msg, log_enabled, traceback_enabled);
+ }
+
+ void log(source_loc loc, level::level_enum lvl, string_view_t msg)
+ {
+ bool log_enabled = should_log(lvl);
+ bool traceback_enabled = tracer_.enabled();
+ if (!log_enabled && !traceback_enabled)
+ {
+ return;
+ }
+
+ details::log_msg log_msg(loc, name_, lvl, msg);
+ log_it_(log_msg, log_enabled, traceback_enabled);
+ }
+
+ void log(level::level_enum lvl, string_view_t msg)
+ {
+ log(source_loc{}, lvl, msg);
+ }
+
+ // T cannot be statically converted to string_view or wstring_view
+ template<class T, typename std::enable_if<!std::is_convertible<const T &, spdlog::string_view_t>::value &&
+ !is_convertible_to_wstring_view<const T &>::value,
+ int>::type = 0>
+ void log(source_loc loc, level::level_enum lvl, const T &msg)
+ {
+ log(loc, lvl, "{}", msg);
+ }
+
+ template<typename T>
+ void trace(const T &msg)
+ {
+ log(level::trace, msg);
+ }
+
+ template<typename T>
+ void debug(const T &msg)
+ {
+ log(level::debug, msg);
+ }
+
+ template<typename T>
+ void info(const T &msg)
+ {
+ log(level::info, msg);
+ }
+
+ template<typename T>
+ void warn(const T &msg)
+ {
+ log(level::warn, msg);
+ }
+
+ template<typename T>
+ void error(const T &msg)
+ {
+ log(level::err, msg);
+ }
+
+ template<typename T>
+ void critical(const T &msg)
+ {
+ log(level::critical, msg);
+ }
+
+#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
+#ifndef _WIN32
+#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
+#else
+
+ template<typename... Args>
+ void log(source_loc loc, level::level_enum lvl, wstring_view_t fmt, Args&&...args)
+ {
+ bool log_enabled = should_log(lvl);
+ bool traceback_enabled = tracer_.enabled();
+ if (!log_enabled && !traceback_enabled)
+ {
+ return;
+ }
+ SPDLOG_TRY
+ {
+ // format to wmemory_buffer and convert to utf8
+ fmt::wmemory_buffer wbuf;
+ fmt::format_to(wbuf, fmt, std::forward<Args>(args)...);
+
+ memory_buf_t buf;
+ details::os::wstr_to_utf8buf(wstring_view_t(wbuf.data(), wbuf.size()), buf);
+ details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
+ log_it_(log_msg, log_enabled, traceback_enabled);
+ }
+ SPDLOG_LOGGER_CATCH()
+ }
+
+ // T can be statically converted to wstring_view
+ template<class T, typename std::enable_if<is_convertible_to_wstring_view<const T &>::value, int>::type = 0>
+ void log(source_loc loc, level::level_enum lvl, const T &msg)
+ {
+ bool log_enabled = should_log(lvl);
+ bool traceback_enabled = tracer_.enabled();
+ if (!log_enabled && !traceback_enabled)
+ {
+ return;
+ }
+
+ SPDLOG_TRY
+ {
+ memory_buf_t buf;
+ details::os::wstr_to_utf8buf(msg, buf);
+ details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
+ log_it_(log_msg, log_enabled, traceback_enabled);
+ }
+ SPDLOG_LOGGER_CATCH()
+ }
+#endif // _WIN32
+#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
+
+ // return true logging is enabled for the given level.
+ bool should_log(level::level_enum msg_level) const
+ {
+ return msg_level >= level_.load(std::memory_order_relaxed);
+ }
+
+ // return true if backtrace logging is enabled.
+ bool should_backtrace() const
+ {
+ return tracer_.enabled();
+ }
+
+ void set_level(level::level_enum log_level);
+
+ level::level_enum level() const;
+
+ const std::string &name() const;
+
+ // set formatting for the sinks in this logger.
+ // each sink will get a separate instance of the formatter object.
+ void set_formatter(std::unique_ptr<formatter> f);
+
+ void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);
+
+ // backtrace support.
+ // efficiently store all debug/trace messages in a circular buffer until needed for debugging.
+ void enable_backtrace(size_t n_messages);
+ void disable_backtrace();
+ void dump_backtrace();
+
+ // flush functions
+ void flush();
+ void flush_on(level::level_enum log_level);
+ level::level_enum flush_level() const;
+
+ // sinks
+ const std::vector<sink_ptr> &sinks() const;
+
+ std::vector<sink_ptr> &sinks();
+
+ // error handler
+ void set_error_handler(err_handler);
+
+ // create new logger with same sinks and configuration.
+ virtual std::shared_ptr<logger> clone(std::string logger_name);
+
+protected:
+ std::string name_;
+ std::vector<sink_ptr> sinks_;
+ spdlog::level_t level_{level::info};
+ spdlog::level_t flush_level_{level::off};
+ err_handler custom_err_handler_{nullptr};
+ details::backtracer tracer_;
+
+ // common implementation for after templated public api has been resolved
+ template<typename FormatString, typename... Args>
+ void log_(source_loc loc, level::level_enum lvl, const FormatString &fmt, Args&&...args)
+ {
+ bool log_enabled = should_log(lvl);
+ bool traceback_enabled = tracer_.enabled();
+ if (!log_enabled && !traceback_enabled)
+ {
+ return;
+ }
+ SPDLOG_TRY
+ {
+ memory_buf_t buf;
+ fmt::format_to(buf, fmt, std::forward<Args>(args)...);
+ details::log_msg log_msg(loc, name_, lvl, string_view_t(buf.data(), buf.size()));
+ log_it_(log_msg, log_enabled, traceback_enabled);
+ }
+ SPDLOG_LOGGER_CATCH()
+ }
+
+ // log the given message (if the given log level is high enough),
+ // and save backtrace (if backtrace is enabled).
+ void log_it_(const details::log_msg &log_msg, bool log_enabled, bool traceback_enabled);
+ virtual void sink_it_(const details::log_msg &msg);
+ virtual void flush_();
+ void dump_backtrace_();
+ bool should_flush_(const details::log_msg &msg);
+
+ // handle errors during logging.
+ // default handler prints the error to stderr at max rate of 1 message/sec.
+ void err_handler_(const std::string &msg);
+};
+
+void swap(logger &a, logger &b);
+
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "logger-inl.h"
+#endif
diff --git a/include/spdlog/pattern_formatter-inl.h b/include/spdlog/pattern_formatter-inl.h
new file mode 100644
index 00000000..54346e1e
--- /dev/null
+++ b/include/spdlog/pattern_formatter-inl.h
@@ -0,0 +1,1395 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/pattern_formatter.h>
+#endif
+
+#include <spdlog/details/fmt_helper.h>
+#include <spdlog/details/log_msg.h>
+#include <spdlog/details/os.h>
+#include <spdlog/fmt/fmt.h>
+#include <spdlog/formatter.h>
+
+#include <algorithm>
+#include <array>
+#include <chrono>
+#include <ctime>
+#include <cctype>
+#include <cstring>
+#include <iterator>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <utility>
+#include <vector>
+
+namespace spdlog {
+namespace details {
+
+///////////////////////////////////////////////////////////////////////
+// name & level pattern appender
+///////////////////////////////////////////////////////////////////////
+
+class scoped_padder
+{
+public:
+ scoped_padder(size_t wrapped_size, const padding_info &padinfo, memory_buf_t &dest)
+ : padinfo_(padinfo)
+ , dest_(dest)
+ {
+ remaining_pad_ = static_cast<long>(padinfo.width_) - static_cast<long>(wrapped_size);
+ if (remaining_pad_ <= 0)
+ {
+ return;
+ }
+
+ if (padinfo_.side_ == padding_info::pad_side::left)
+ {
+ pad_it(remaining_pad_);
+ remaining_pad_ = 0;
+ }
+ else if (padinfo_.side_ == padding_info::pad_side::center)
+ {
+ auto half_pad = remaining_pad_ / 2;
+ auto reminder = remaining_pad_ & 1;
+ pad_it(half_pad);
+ remaining_pad_ = half_pad + reminder; // for the right side
+ }
+ }
+
+ template<typename T>
+ static unsigned int count_digits(T n)
+ {
+ return fmt_helper::count_digits(n);
+ }
+
+ ~scoped_padder()
+ {
+ if (remaining_pad_ >= 0)
+ {
+ pad_it(remaining_pad_);
+ }
+ else if (padinfo_.truncate_)
+ {
+ long new_size = static_cast<long>(dest_.size()) + remaining_pad_;
+ dest_.resize(static_cast<size_t>(new_size));
+ }
+ }
+
+private:
+ void pad_it(long count)
+ {
+ fmt_helper::append_string_view(string_view_t(spaces_.data(), static_cast<size_t>(count)), dest_);
+ }
+
+ const padding_info &padinfo_;
+ memory_buf_t &dest_;
+ long remaining_pad_;
+ string_view_t spaces_{" ", 64};
+};
+
+struct null_scoped_padder
+{
+ null_scoped_padder(size_t /*wrapped_size*/, const padding_info & /*padinfo*/, memory_buf_t & /*dest*/) {}
+
+ template<typename T>
+ static unsigned int count_digits(T /* number */)
+ {
+ return 0;
+ }
+};
+
+template<typename ScopedPadder>
+class name_formatter final : public flag_formatter
+{
+public:
+ explicit name_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ ScopedPadder p(msg.logger_name.size(), padinfo_, dest);
+ fmt_helper::append_string_view(msg.logger_name, dest);
+ }
+};
+
+// log level appender
+template<typename ScopedPadder>
+class level_formatter final : public flag_formatter
+{
+public:
+ explicit level_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ const string_view_t &level_name = level::to_string_view(msg.level);
+ ScopedPadder p(level_name.size(), padinfo_, dest);
+ fmt_helper::append_string_view(level_name, dest);
+ }
+};
+
+// short log level appender
+template<typename ScopedPadder>
+class short_level_formatter final : public flag_formatter
+{
+public:
+ explicit short_level_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ string_view_t level_name{level::to_short_c_str(msg.level)};
+ ScopedPadder p(level_name.size(), padinfo_, dest);
+ fmt_helper::append_string_view(level_name, dest);
+ }
+};
+
+///////////////////////////////////////////////////////////////////////
+// Date time pattern appenders
+///////////////////////////////////////////////////////////////////////
+
+static const char *ampm(const tm &t)
+{
+ return t.tm_hour >= 12 ? "PM" : "AM";
+}
+
+static int to12h(const tm &t)
+{
+ return t.tm_hour > 12 ? t.tm_hour - 12 : t.tm_hour;
+}
+
+// Abbreviated weekday name
+static std::array<const char *, 7> days{{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}};
+
+template<typename ScopedPadder>
+class a_formatter final : public flag_formatter
+{
+public:
+ explicit a_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ string_view_t field_value{days[static_cast<size_t>(tm_time.tm_wday)]};
+ ScopedPadder p(field_value.size(), padinfo_, dest);
+ fmt_helper::append_string_view(field_value, dest);
+ }
+};
+
+// Full weekday name
+static std::array<const char *, 7> full_days{{"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}};
+
+template<typename ScopedPadder>
+class A_formatter : public flag_formatter
+{
+public:
+ explicit A_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ string_view_t field_value{full_days[static_cast<size_t>(tm_time.tm_wday)]};
+ ScopedPadder p(field_value.size(), padinfo_, dest);
+ fmt_helper::append_string_view(field_value, dest);
+ }
+};
+
+// Abbreviated month
+static const std::array<const char *, 12> months{{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sept", "Oct", "Nov", "Dec"}};
+
+template<typename ScopedPadder>
+class b_formatter final : public flag_formatter
+{
+public:
+ explicit b_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ string_view_t field_value{months[static_cast<size_t>(tm_time.tm_mon)]};
+ ScopedPadder p(field_value.size(), padinfo_, dest);
+ fmt_helper::append_string_view(field_value, dest);
+ }
+};
+
+// Full month name
+static const std::array<const char *, 12> full_months{
+ {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}};
+
+template<typename ScopedPadder>
+class B_formatter final : public flag_formatter
+{
+public:
+ explicit B_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ string_view_t field_value{full_months[static_cast<size_t>(tm_time.tm_mon)]};
+ ScopedPadder p(field_value.size(), padinfo_, dest);
+ fmt_helper::append_string_view(field_value, dest);
+ }
+};
+
+// Date and time representation (Thu Aug 23 15:35:46 2014)
+template<typename ScopedPadder>
+class c_formatter final : public flag_formatter
+{
+public:
+ explicit c_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 24;
+ ScopedPadder p(field_size, padinfo_, dest);
+
+ fmt_helper::append_string_view(days[static_cast<size_t>(tm_time.tm_wday)], dest);
+ dest.push_back(' ');
+ fmt_helper::append_string_view(months[static_cast<size_t>(tm_time.tm_mon)], dest);
+ dest.push_back(' ');
+ fmt_helper::append_int(tm_time.tm_mday, dest);
+ dest.push_back(' ');
+ // time
+
+ fmt_helper::pad2(tm_time.tm_hour, dest);
+ dest.push_back(':');
+ fmt_helper::pad2(tm_time.tm_min, dest);
+ dest.push_back(':');
+ fmt_helper::pad2(tm_time.tm_sec, dest);
+ dest.push_back(' ');
+ fmt_helper::append_int(tm_time.tm_year + 1900, dest);
+ }
+};
+
+// year - 2 digit
+template<typename ScopedPadder>
+class C_formatter final : public flag_formatter
+{
+public:
+ explicit C_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad2(tm_time.tm_year % 100, dest);
+ }
+};
+
+// Short MM/DD/YY date, equivalent to %m/%d/%y 08/23/01
+template<typename ScopedPadder>
+class D_formatter final : public flag_formatter
+{
+public:
+ explicit D_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 10;
+ ScopedPadder p(field_size, padinfo_, dest);
+
+ fmt_helper::pad2(tm_time.tm_mon + 1, dest);
+ dest.push_back('/');
+ fmt_helper::pad2(tm_time.tm_mday, dest);
+ dest.push_back('/');
+ fmt_helper::pad2(tm_time.tm_year % 100, dest);
+ }
+};
+
+// year - 4 digit
+template<typename ScopedPadder>
+class Y_formatter final : public flag_formatter
+{
+public:
+ explicit Y_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 4;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::append_int(tm_time.tm_year + 1900, dest);
+ }
+};
+
+// month 1-12
+template<typename ScopedPadder>
+class m_formatter final : public flag_formatter
+{
+public:
+ explicit m_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad2(tm_time.tm_mon + 1, dest);
+ }
+};
+
+// day of month 1-31
+template<typename ScopedPadder>
+class d_formatter final : public flag_formatter
+{
+public:
+ explicit d_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad2(tm_time.tm_mday, dest);
+ }
+};
+
+// hours in 24 format 0-23
+template<typename ScopedPadder>
+class H_formatter final : public flag_formatter
+{
+public:
+ explicit H_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad2(tm_time.tm_hour, dest);
+ }
+};
+
+// hours in 12 format 1-12
+template<typename ScopedPadder>
+class I_formatter final : public flag_formatter
+{
+public:
+ explicit I_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad2(to12h(tm_time), dest);
+ }
+};
+
+// minutes 0-59
+template<typename ScopedPadder>
+class M_formatter final : public flag_formatter
+{
+public:
+ explicit M_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad2(tm_time.tm_min, dest);
+ }
+};
+
+// seconds 0-59
+template<typename ScopedPadder>
+class S_formatter final : public flag_formatter
+{
+public:
+ explicit S_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad2(tm_time.tm_sec, dest);
+ }
+};
+
+// milliseconds
+template<typename ScopedPadder>
+class e_formatter final : public flag_formatter
+{
+public:
+ explicit e_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ auto millis = fmt_helper::time_fraction<std::chrono::milliseconds>(msg.time);
+ const size_t field_size = 3;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad3(static_cast<uint32_t>(millis.count()), dest);
+ }
+};
+
+// microseconds
+template<typename ScopedPadder>
+class f_formatter final : public flag_formatter
+{
+public:
+ explicit f_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ auto micros = fmt_helper::time_fraction<std::chrono::microseconds>(msg.time);
+
+ const size_t field_size = 6;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad6(static_cast<size_t>(micros.count()), dest);
+ }
+};
+
+// nanoseconds
+template<typename ScopedPadder>
+class F_formatter final : public flag_formatter
+{
+public:
+ explicit F_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ auto ns = fmt_helper::time_fraction<std::chrono::nanoseconds>(msg.time);
+ const size_t field_size = 9;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::pad9(static_cast<size_t>(ns.count()), dest);
+ }
+};
+
+// seconds since epoch
+template<typename ScopedPadder>
+class E_formatter final : public flag_formatter
+{
+public:
+ explicit E_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ const size_t field_size = 10;
+ ScopedPadder p(field_size, padinfo_, dest);
+ auto duration = msg.time.time_since_epoch();
+ auto seconds = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
+ fmt_helper::append_int(seconds, dest);
+ }
+};
+
+// AM/PM
+template<typename ScopedPadder>
+class p_formatter final : public flag_formatter
+{
+public:
+ explicit p_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 2;
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::append_string_view(ampm(tm_time), dest);
+ }
+};
+
+// 12 hour clock 02:55:02 pm
+template<typename ScopedPadder>
+class r_formatter final : public flag_formatter
+{
+public:
+ explicit r_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 11;
+ ScopedPadder p(field_size, padinfo_, dest);
+
+ fmt_helper::pad2(to12h(tm_time), dest);
+ dest.push_back(':');
+ fmt_helper::pad2(tm_time.tm_min, dest);
+ dest.push_back(':');
+ fmt_helper::pad2(tm_time.tm_sec, dest);
+ dest.push_back(' ');
+ fmt_helper::append_string_view(ampm(tm_time), dest);
+ }
+};
+
+// 24-hour HH:MM time, equivalent to %H:%M
+template<typename ScopedPadder>
+class R_formatter final : public flag_formatter
+{
+public:
+ explicit R_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 5;
+ ScopedPadder p(field_size, padinfo_, dest);
+
+ fmt_helper::pad2(tm_time.tm_hour, dest);
+ dest.push_back(':');
+ fmt_helper::pad2(tm_time.tm_min, dest);
+ }
+};
+
+// ISO 8601 time format (HH:MM:SS), equivalent to %H:%M:%S
+template<typename ScopedPadder>
+class T_formatter final : public flag_formatter
+{
+public:
+ explicit T_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 8;
+ ScopedPadder p(field_size, padinfo_, dest);
+
+ fmt_helper::pad2(tm_time.tm_hour, dest);
+ dest.push_back(':');
+ fmt_helper::pad2(tm_time.tm_min, dest);
+ dest.push_back(':');
+ fmt_helper::pad2(tm_time.tm_sec, dest);
+ }
+};
+
+// ISO 8601 offset from UTC in timezone (+-HH:MM)
+template<typename ScopedPadder>
+class z_formatter final : public flag_formatter
+{
+public:
+ explicit z_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ z_formatter() = default;
+ z_formatter(const z_formatter &) = delete;
+ z_formatter &operator=(const z_formatter &) = delete;
+
+ void format(const details::log_msg &msg, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ const size_t field_size = 6;
+ ScopedPadder p(field_size, padinfo_, dest);
+
+ auto total_minutes = get_cached_offset(msg, tm_time);
+ bool is_negative = total_minutes < 0;
+ if (is_negative)
+ {
+ total_minutes = -total_minutes;
+ dest.push_back('-');
+ }
+ else
+ {
+ dest.push_back('+');
+ }
+
+ fmt_helper::pad2(total_minutes / 60, dest); // hours
+ dest.push_back(':');
+ fmt_helper::pad2(total_minutes % 60, dest); // minutes
+ }
+
+private:
+ log_clock::time_point last_update_{std::chrono::seconds(0)};
+ int offset_minutes_{0};
+
+ int get_cached_offset(const log_msg &msg, const std::tm &tm_time)
+ {
+ // refresh every 10 seconds
+ if (msg.time - last_update_ >= std::chrono::seconds(10))
+ {
+ offset_minutes_ = os::utc_minutes_offset(tm_time);
+ last_update_ = msg.time;
+ }
+ return offset_minutes_;
+ }
+};
+
+// Thread id
+template<typename ScopedPadder>
+class t_formatter final : public flag_formatter
+{
+public:
+ explicit t_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ const auto field_size = ScopedPadder::count_digits(msg.thread_id);
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::append_int(msg.thread_id, dest);
+ }
+};
+
+// Current pid
+template<typename ScopedPadder>
+class pid_formatter final : public flag_formatter
+{
+public:
+ explicit pid_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &, const std::tm &, memory_buf_t &dest) override
+ {
+ const auto pid = static_cast<uint32_t>(details::os::pid());
+ auto field_size = ScopedPadder::count_digits(pid);
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::append_int(pid, dest);
+ }
+};
+
+template<typename ScopedPadder>
+class v_formatter final : public flag_formatter
+{
+public:
+ explicit v_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ ScopedPadder p(msg.payload.size(), padinfo_, dest);
+ fmt_helper::append_string_view(msg.payload, dest);
+ }
+};
+
+class ch_formatter final : public flag_formatter
+{
+public:
+ explicit ch_formatter(char ch)
+ : ch_(ch)
+ {}
+
+ void format(const details::log_msg &, const std::tm &, memory_buf_t &dest) override
+ {
+ dest.push_back(ch_);
+ }
+
+private:
+ char ch_;
+};
+
+// aggregate user chars to display as is
+class aggregate_formatter final : public flag_formatter
+{
+public:
+ aggregate_formatter() = default;
+
+ void add_ch(char ch)
+ {
+ str_ += ch;
+ }
+ void format(const details::log_msg &, const std::tm &, memory_buf_t &dest) override
+ {
+ fmt_helper::append_string_view(str_, dest);
+ }
+
+private:
+ std::string str_;
+};
+
+// mark the color range. expect it to be in the form of "%^colored text%$"
+class color_start_formatter final : public flag_formatter
+{
+public:
+ explicit color_start_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ msg.color_range_start = dest.size();
+ }
+};
+
+class color_stop_formatter final : public flag_formatter
+{
+public:
+ explicit color_stop_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ msg.color_range_end = dest.size();
+ }
+};
+
+// print source location
+template<typename ScopedPadder>
+class source_location_formatter final : public flag_formatter
+{
+public:
+ explicit source_location_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ if (msg.source.empty())
+ {
+ return;
+ }
+
+ size_t text_size;
+ if (padinfo_.enabled())
+ {
+ // calc text size for padding based on "filename:line"
+ text_size = std::char_traits<char>::length(msg.source.filename) + ScopedPadder::count_digits(msg.source.line) + 1;
+ }
+ else
+ {
+ text_size = 0;
+ }
+
+ ScopedPadder p(text_size, padinfo_, dest);
+ fmt_helper::append_string_view(msg.source.filename, dest);
+ dest.push_back(':');
+ fmt_helper::append_int(msg.source.line, dest);
+ }
+};
+
+// print source filename
+template<typename ScopedPadder>
+class source_filename_formatter final : public flag_formatter
+{
+public:
+ explicit source_filename_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ if (msg.source.empty())
+ {
+ return;
+ }
+ size_t text_size = padinfo_.enabled() ? std::char_traits<char>::length(msg.source.filename) : 0;
+ ScopedPadder p(text_size, padinfo_, dest);
+ fmt_helper::append_string_view(msg.source.filename, dest);
+ }
+};
+
+template<typename ScopedPadder>
+class short_filename_formatter final : public flag_formatter
+{
+public:
+ explicit short_filename_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+#ifdef _MSC_VER
+#pragma warning(push)
+#pragma warning(disable : 4127) // consider using 'if constexpr' instead
+#endif // _MSC_VER
+ static const char *basename(const char *filename)
+ {
+ // if the size is 2 (1 character + null terminator) we can use the more efficient strrchr
+ // the branch will be elided by optimizations
+ if (sizeof(os::folder_seps) == 2)
+ {
+ const char *rv = std::strrchr(filename, os::folder_seps[0]);
+ return rv != nullptr ? rv + 1 : filename;
+ }
+ else
+ {
+ const std::reverse_iterator<const char*> begin(filename + std::strlen(filename));
+ const std::reverse_iterator<const char*> end(filename);
+
+ const auto it = std::find_first_of(begin, end, std::begin(os::folder_seps), std::end(os::folder_seps) - 1);
+ return it != end ? it.base() : filename;
+ }
+ }
+#ifdef _MSC_VER
+#pragma warning(pop)
+#endif // _MSC_VER
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ if (msg.source.empty())
+ {
+ return;
+ }
+ auto filename = basename(msg.source.filename);
+ size_t text_size = padinfo_.enabled() ? std::char_traits<char>::length(filename) : 0;
+ ScopedPadder p(text_size, padinfo_, dest);
+ fmt_helper::append_string_view(filename, dest);
+ }
+};
+
+template<typename ScopedPadder>
+class source_linenum_formatter final : public flag_formatter
+{
+public:
+ explicit source_linenum_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ if (msg.source.empty())
+ {
+ return;
+ }
+
+ auto field_size = ScopedPadder::count_digits(msg.source.line);
+ ScopedPadder p(field_size, padinfo_, dest);
+ fmt_helper::append_int(msg.source.line, dest);
+ }
+};
+
+// print source funcname
+template<typename ScopedPadder>
+class source_funcname_formatter final : public flag_formatter
+{
+public:
+ explicit source_funcname_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ if (msg.source.empty())
+ {
+ return;
+ }
+ size_t text_size = padinfo_.enabled() ? std::char_traits<char>::length(msg.source.funcname) : 0;
+ ScopedPadder p(text_size, padinfo_, dest);
+ fmt_helper::append_string_view(msg.source.funcname, dest);
+ }
+};
+
+// print elapsed time since last message
+template<typename ScopedPadder, typename Units>
+class elapsed_formatter final : public flag_formatter
+{
+public:
+ using DurationUnits = Units;
+
+ explicit elapsed_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ , last_message_time_(log_clock::now())
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &, memory_buf_t &dest) override
+ {
+ auto delta = (std::max)(msg.time - last_message_time_, log_clock::duration::zero());
+ auto delta_units = std::chrono::duration_cast<DurationUnits>(delta);
+ last_message_time_ = msg.time;
+ auto delta_count = static_cast<size_t>(delta_units.count());
+ auto n_digits = static_cast<size_t>(ScopedPadder::count_digits(delta_count));
+ ScopedPadder p(n_digits, padinfo_, dest);
+ fmt_helper::append_int(delta_count, dest);
+ }
+
+private:
+ log_clock::time_point last_message_time_;
+};
+
+// Full info formatter
+// pattern: [%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v
+class full_formatter final : public flag_formatter
+{
+public:
+ explicit full_formatter(padding_info padinfo)
+ : flag_formatter(padinfo)
+ {}
+
+ void format(const details::log_msg &msg, const std::tm &tm_time, memory_buf_t &dest) override
+ {
+ using std::chrono::duration_cast;
+ using std::chrono::milliseconds;
+ using std::chrono::seconds;
+
+ // cache the date/time part for the next second.
+ auto duration = msg.time.time_since_epoch();
+ auto secs = duration_cast<seconds>(duration);
+
+ if (cache_timestamp_ != secs || cached_datetime_.size() == 0)
+ {
+ cached_datetime_.clear();
+ cached_datetime_.push_back('[');
+ fmt_helper::append_int(tm_time.tm_year + 1900, cached_datetime_);
+ cached_datetime_.push_back('-');
+
+ fmt_helper::pad2(tm_time.tm_mon + 1, cached_datetime_);
+ cached_datetime_.push_back('-');
+
+ fmt_helper::pad2(tm_time.tm_mday, cached_datetime_);
+ cached_datetime_.push_back(' ');
+
+ fmt_helper::pad2(tm_time.tm_hour, cached_datetime_);
+ cached_datetime_.push_back(':');
+
+ fmt_helper::pad2(tm_time.tm_min, cached_datetime_);
+ cached_datetime_.push_back(':');
+
+ fmt_helper::pad2(tm_time.tm_sec, cached_datetime_);
+ cached_datetime_.push_back('.');
+
+ cache_timestamp_ = secs;
+ }
+ dest.append(cached_datetime_.begin(), cached_datetime_.end());
+
+ auto millis = fmt_helper::time_fraction<milliseconds>(msg.time);
+ fmt_helper::pad3(static_cast<uint32_t>(millis.count()), dest);
+ dest.push_back(']');
+ dest.push_back(' ');
+
+ // append logger name if exists
+ if (msg.logger_name.size() > 0)
+ {
+ dest.push_back('[');
+ fmt_helper::append_string_view(msg.logger_name, dest);
+ dest.push_back(']');
+ dest.push_back(' ');
+ }
+
+ dest.push_back('[');
+ // wrap the level name with color
+ msg.color_range_start = dest.size();
+ // fmt_helper::append_string_view(level::to_c_str(msg.level), dest);
+ fmt_helper::append_string_view(level::to_string_view(msg.level), dest);
+ msg.color_range_end = dest.size();
+ dest.push_back(']');
+ dest.push_back(' ');
+
+ // add source location if present
+ if (!msg.source.empty())
+ {
+ dest.push_back('[');
+ const char *filename = details::short_filename_formatter<details::null_scoped_padder>::basename(msg.source.filename);
+ fmt_helper::append_string_view(filename, dest);
+ dest.push_back(':');
+ fmt_helper::append_int(msg.source.line, dest);
+ dest.push_back(']');
+ dest.push_back(' ');
+ }
+ // fmt_helper::append_string_view(msg.msg(), dest);
+ fmt_helper::append_string_view(msg.payload, dest);
+ }
+
+private:
+ std::chrono::seconds cache_timestamp_{0};
+ memory_buf_t cached_datetime_;
+};
+
+} // namespace details
+
+SPDLOG_INLINE pattern_formatter::pattern_formatter(
+ std::string pattern, pattern_time_type time_type, std::string eol, custom_flags custom_user_flags)
+ : pattern_(std::move(pattern))
+ , eol_(std::move(eol))
+ , pattern_time_type_(time_type)
+ , last_log_secs_(0)
+ , custom_handlers_(std::move(custom_user_flags))
+{
+ std::memset(&cached_tm_, 0, sizeof(cached_tm_));
+ compile_pattern_(pattern_);
+}
+
+// use by default full formatter for if pattern is not given
+SPDLOG_INLINE pattern_formatter::pattern_formatter(pattern_time_type time_type, std::string eol)
+ : pattern_("%+")
+ , eol_(std::move(eol))
+ , pattern_time_type_(time_type)
+ , last_log_secs_(0)
+{
+ std::memset(&cached_tm_, 0, sizeof(cached_tm_));
+ formatters_.push_back(details::make_unique<details::full_formatter>(details::padding_info{}));
+}
+
+SPDLOG_INLINE std::unique_ptr<formatter> pattern_formatter::clone() const
+{
+ custom_flags cloned_custom_formatters;
+ for (auto &it : custom_handlers_)
+ {
+ cloned_custom_formatters[it.first] = it.second->clone();
+ }
+ return details::make_unique<pattern_formatter>(pattern_, pattern_time_type_, eol_, std::move(cloned_custom_formatters));
+}
+
+SPDLOG_INLINE void pattern_formatter::format(const details::log_msg &msg, memory_buf_t &dest)
+{
+ auto secs = std::chrono::duration_cast<std::chrono::seconds>(msg.time.time_since_epoch());
+ if (secs != last_log_secs_)
+ {
+ cached_tm_ = get_time_(msg);
+ last_log_secs_ = secs;
+ }
+
+ for (auto &f : formatters_)
+ {
+ f->format(msg, cached_tm_, dest);
+ }
+ // write eol
+ details::fmt_helper::append_string_view(eol_, dest);
+}
+
+SPDLOG_INLINE void pattern_formatter::set_pattern(std::string pattern)
+{
+ pattern_ = std::move(pattern);
+ compile_pattern_(pattern_);
+}
+
+SPDLOG_INLINE std::tm pattern_formatter::get_time_(const details::log_msg &msg)
+{
+ if (pattern_time_type_ == pattern_time_type::local)
+ {
+ return details::os::localtime(log_clock::to_time_t(msg.time));
+ }
+ return details::os::gmtime(log_clock::to_time_t(msg.time));
+}
+
+template<typename Padder>
+SPDLOG_INLINE void pattern_formatter::handle_flag_(char flag, details::padding_info padding)
+{
+ // process custom flags
+ auto it = custom_handlers_.find(flag);
+ if (it != custom_handlers_.end())
+ {
+ auto custom_handler = it->second->clone();
+ custom_handler->set_padding_info(padding);
+ formatters_.push_back(std::move(custom_handler));
+ return;
+ }
+
+ // process built-in flags
+ switch (flag)
+ {
+ case ('+'): // default formatter
+ formatters_.push_back(details::make_unique<details::full_formatter>(padding));
+ break;
+
+ case 'n': // logger name
+ formatters_.push_back(details::make_unique<details::name_formatter<Padder>>(padding));
+ break;
+
+ case 'l': // level
+ formatters_.push_back(details::make_unique<details::level_formatter<Padder>>(padding));
+ break;
+
+ case 'L': // short level
+ formatters_.push_back(details::make_unique<details::short_level_formatter<Padder>>(padding));
+ break;
+
+ case ('t'): // thread id
+ formatters_.push_back(details::make_unique<details::t_formatter<Padder>>(padding));
+ break;
+
+ case ('v'): // the message text
+ formatters_.push_back(details::make_unique<details::v_formatter<Padder>>(padding));
+ break;
+
+ case ('a'): // weekday
+ formatters_.push_back(details::make_unique<details::a_formatter<Padder>>(padding));
+ break;
+
+ case ('A'): // short weekday
+ formatters_.push_back(details::make_unique<details::A_formatter<Padder>>(padding));
+ break;
+
+ case ('b'):
+ case ('h'): // month
+ formatters_.push_back(details::make_unique<details::b_formatter<Padder>>(padding));
+ break;
+
+ case ('B'): // short month
+ formatters_.push_back(details::make_unique<details::B_formatter<Padder>>(padding));
+ break;
+
+ case ('c'): // datetime
+ formatters_.push_back(details::make_unique<details::c_formatter<Padder>>(padding));
+ break;
+
+ case ('C'): // year 2 digits
+ formatters_.push_back(details::make_unique<details::C_formatter<Padder>>(padding));
+ break;
+
+ case ('Y'): // year 4 digits
+ formatters_.push_back(details::make_unique<details::Y_formatter<Padder>>(padding));
+ break;
+
+ case ('D'):
+ case ('x'): // datetime MM/DD/YY
+ formatters_.push_back(details::make_unique<details::D_formatter<Padder>>(padding));
+ break;
+
+ case ('m'): // month 1-12
+ formatters_.push_back(details::make_unique<details::m_formatter<Padder>>(padding));
+ break;
+
+ case ('d'): // day of month 1-31
+ formatters_.push_back(details::make_unique<details::d_formatter<Padder>>(padding));
+ break;
+
+ case ('H'): // hours 24
+ formatters_.push_back(details::make_unique<details::H_formatter<Padder>>(padding));
+ break;
+
+ case ('I'): // hours 12
+ formatters_.push_back(details::make_unique<details::I_formatter<Padder>>(padding));
+ break;
+
+ case ('M'): // minutes
+ formatters_.push_back(details::make_unique<details::M_formatter<Padder>>(padding));
+ break;
+
+ case ('S'): // seconds
+ formatters_.push_back(details::make_unique<details::S_formatter<Padder>>(padding));
+ break;
+
+ case ('e'): // milliseconds
+ formatters_.push_back(details::make_unique<details::e_formatter<Padder>>(padding));
+ break;
+
+ case ('f'): // microseconds
+ formatters_.push_back(details::make_unique<details::f_formatter<Padder>>(padding));
+ break;
+
+ case ('F'): // nanoseconds
+ formatters_.push_back(details::make_unique<details::F_formatter<Padder>>(padding));
+ break;
+
+ case ('E'): // seconds since epoch
+ formatters_.push_back(details::make_unique<details::E_formatter<Padder>>(padding));
+ break;
+
+ case ('p'): // am/pm
+ formatters_.push_back(details::make_unique<details::p_formatter<Padder>>(padding));
+ break;
+
+ case ('r'): // 12 hour clock 02:55:02 pm
+ formatters_.push_back(details::make_unique<details::r_formatter<Padder>>(padding));
+ break;
+
+ case ('R'): // 24-hour HH:MM time
+ formatters_.push_back(details::make_unique<details::R_formatter<Padder>>(padding));
+ break;
+
+ case ('T'):
+ case ('X'): // ISO 8601 time format (HH:MM:SS)
+ formatters_.push_back(details::make_unique<details::T_formatter<Padder>>(padding));
+ break;
+
+ case ('z'): // timezone
+ formatters_.push_back(details::make_unique<details::z_formatter<Padder>>(padding));
+ break;
+
+ case ('P'): // pid
+ formatters_.push_back(details::make_unique<details::pid_formatter<Padder>>(padding));
+ break;
+
+ case ('^'): // color range start
+ formatters_.push_back(details::make_unique<details::color_start_formatter>(padding));
+ break;
+
+ case ('$'): // color range end
+ formatters_.push_back(details::make_unique<details::color_stop_formatter>(padding));
+ break;
+
+ case ('@'): // source location (filename:filenumber)
+ formatters_.push_back(details::make_unique<details::source_location_formatter<Padder>>(padding));
+ break;
+
+ case ('s'): // short source filename - without directory name
+ formatters_.push_back(details::make_unique<details::short_filename_formatter<Padder>>(padding));
+ break;
+
+ case ('g'): // full source filename
+ formatters_.push_back(details::make_unique<details::source_filename_formatter<Padder>>(padding));
+ break;
+
+ case ('#'): // source line number
+ formatters_.push_back(details::make_unique<details::source_linenum_formatter<Padder>>(padding));
+ break;
+
+ case ('!'): // source funcname
+ formatters_.push_back(details::make_unique<details::source_funcname_formatter<Padder>>(padding));
+ break;
+
+ case ('%'): // % char
+ formatters_.push_back(details::make_unique<details::ch_formatter>('%'));
+ break;
+
+ case ('u'): // elapsed time since last log message in nanos
+ formatters_.push_back(details::make_unique<details::elapsed_formatter<Padder, std::chrono::nanoseconds>>(padding));
+ break;
+
+ case ('i'): // elapsed time since last log message in micros
+ formatters_.push_back(details::make_unique<details::elapsed_formatter<Padder, std::chrono::microseconds>>(padding));
+ break;
+
+ case ('o'): // elapsed time since last log message in millis
+ formatters_.push_back(details::make_unique<details::elapsed_formatter<Padder, std::chrono::milliseconds>>(padding));
+ break;
+
+ case ('O'): // elapsed time since last log message in seconds
+ formatters_.push_back(details::make_unique<details::elapsed_formatter<Padder, std::chrono::seconds>>(padding));
+ break;
+
+ default: // Unknown flag appears as is
+ auto unknown_flag = details::make_unique<details::aggregate_formatter>();
+
+ if (!padding.truncate_)
+ {
+ unknown_flag->add_ch('%');
+ unknown_flag->add_ch(flag);
+ formatters_.push_back((std::move(unknown_flag)));
+ }
+ // fix issue #1617 (prev char was '!' and should have been treated as funcname flag instead of truncating flag)
+ // spdlog::set_pattern("[%10!] %v") => "[ main] some message"
+ // spdlog::set_pattern("[%3!!] %v") => "[mai] some message"
+ else
+ {
+ padding.truncate_ = false;
+ formatters_.push_back(details::make_unique<details::source_funcname_formatter<Padder>>(padding));
+ unknown_flag->add_ch(flag);
+ formatters_.push_back((std::move(unknown_flag)));
+ }
+
+ break;
+ }
+}
+
+// Extract given pad spec (e.g. %8X, %=8X, %-8!X, %8!X, %=8!X, %-8!X, %+8!X)
+// Advance the given it pass the end of the padding spec found (if any)
+// Return padding.
+SPDLOG_INLINE details::padding_info pattern_formatter::handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end)
+{
+ using details::padding_info;
+ using details::scoped_padder;
+ const size_t max_width = 64;
+ if (it == end)
+ {
+ return padding_info{};
+ }
+
+ padding_info::pad_side side;
+ switch (*it)
+ {
+ case '-':
+ side = padding_info::pad_side::right;
+ ++it;
+ break;
+ case '=':
+ side = padding_info::pad_side::center;
+ ++it;
+ break;
+ default:
+ side = details::padding_info::pad_side::left;
+ break;
+ }
+
+ if (it == end || !std::isdigit(static_cast<unsigned char>(*it)))
+ {
+ return padding_info{}; // no padding if no digit found here
+ }
+
+ auto width = static_cast<size_t>(*it) - '0';
+ for (++it; it != end && std::isdigit(static_cast<unsigned char>(*it)); ++it)
+ {
+ auto digit = static_cast<size_t>(*it) - '0';
+ width = width * 10 + digit;
+ }
+
+ // search for the optional truncate marker '!'
+ bool truncate;
+ if (it != end && *it == '!')
+ {
+ truncate = true;
+ ++it;
+ }
+ else
+ {
+ truncate = false;
+ }
+
+ return details::padding_info{std::min<size_t>(width, max_width), side, truncate};
+}
+
+SPDLOG_INLINE void pattern_formatter::compile_pattern_(const std::string &pattern)
+{
+ auto end = pattern.end();
+ std::unique_ptr<details::aggregate_formatter> user_chars;
+ formatters_.clear();
+ for (auto it = pattern.begin(); it != end; ++it)
+ {
+ if (*it == '%')
+ {
+ if (user_chars) // append user chars found so far
+ {
+ formatters_.push_back(std::move(user_chars));
+ }
+
+ auto padding = handle_padspec_(++it, end);
+
+ if (it != end)
+ {
+ if (padding.enabled())
+ {
+ handle_flag_<details::scoped_padder>(*it, padding);
+ }
+ else
+ {
+ handle_flag_<details::null_scoped_padder>(*it, padding);
+ }
+ }
+ else
+ {
+ break;
+ }
+ }
+ else // chars not following the % sign should be displayed as is
+ {
+ if (!user_chars)
+ {
+ user_chars = details::make_unique<details::aggregate_formatter>();
+ }
+ user_chars->add_ch(*it);
+ }
+ }
+ if (user_chars) // append raw chars found so far
+ {
+ formatters_.push_back(std::move(user_chars));
+ }
+}
+} // namespace spdlog
diff --git a/include/spdlog/pattern_formatter.h b/include/spdlog/pattern_formatter.h
new file mode 100644
index 00000000..bc13ae10
--- /dev/null
+++ b/include/spdlog/pattern_formatter.h
@@ -0,0 +1,126 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <spdlog/details/log_msg.h>
+#include <spdlog/details/os.h>
+#include <spdlog/formatter.h>
+
+#include <chrono>
+#include <ctime>
+#include <memory>
+
+#include <string>
+#include <vector>
+#include <unordered_map>
+
+namespace spdlog {
+namespace details {
+
+// padding information.
+struct padding_info
+{
+ enum class pad_side
+ {
+ left,
+ right,
+ center
+ };
+
+ padding_info() = default;
+ padding_info(size_t width, padding_info::pad_side side, bool truncate)
+ : width_(width)
+ , side_(side)
+ , truncate_(truncate)
+ , enabled_(true)
+ {}
+
+ bool enabled() const
+ {
+ return enabled_;
+ }
+ size_t width_ = 0;
+ pad_side side_ = pad_side::left;
+ bool truncate_ = false;
+ bool enabled_ = false;
+};
+
+class SPDLOG_API flag_formatter
+{
+public:
+ explicit flag_formatter(padding_info padinfo)
+ : padinfo_(padinfo)
+ {}
+ flag_formatter() = default;
+ virtual ~flag_formatter() = default;
+ virtual void format(const details::log_msg &msg, const std::tm &tm_time, memory_buf_t &dest) = 0;
+
+protected:
+ padding_info padinfo_;
+};
+
+} // namespace details
+
+class SPDLOG_API custom_flag_formatter : public details::flag_formatter
+{
+public:
+ virtual std::unique_ptr<custom_flag_formatter> clone() const = 0;
+
+ void set_padding_info(details::padding_info padding)
+ {
+ flag_formatter::padinfo_ = padding;
+ }
+};
+
+class SPDLOG_API pattern_formatter final : public formatter
+{
+public:
+ using custom_flags = std::unordered_map<char, std::unique_ptr<custom_flag_formatter>>;
+
+ explicit pattern_formatter(std::string pattern, pattern_time_type time_type = pattern_time_type::local,
+ std::string eol = spdlog::details::os::default_eol, custom_flags custom_user_flags = custom_flags());
+
+ // use default pattern is not given
+ explicit pattern_formatter(pattern_time_type time_type = pattern_time_type::local, std::string eol = spdlog::details::os::default_eol);
+
+ pattern_formatter(const pattern_formatter &other) = delete;
+ pattern_formatter &operator=(const pattern_formatter &other) = delete;
+
+ std::unique_ptr<formatter> clone() const override;
+ void format(const details::log_msg &msg, memory_buf_t &dest) override;
+
+ template<typename T, typename... Args>
+ pattern_formatter &add_flag(char flag, Args&&...args)
+ {
+ custom_handlers_[flag] = details::make_unique<T>(std::forward<Args>(args)...);
+ return *this;
+ }
+ void set_pattern(std::string pattern);
+
+private:
+ std::string pattern_;
+ std::string eol_;
+ pattern_time_type pattern_time_type_;
+ std::tm cached_tm_;
+ std::chrono::seconds last_log_secs_;
+ std::vector<std::unique_ptr<details::flag_formatter>> formatters_;
+ custom_flags custom_handlers_;
+
+ std::tm get_time_(const details::log_msg &msg);
+ template<typename Padder>
+ void handle_flag_(char flag, details::padding_info padding);
+
+ // Extract given pad spec (e.g. %8X)
+ // Advance the given it pass the end of the padding spec found (if any)
+ // Return padding.
+ static details::padding_info handle_padspec_(std::string::const_iterator &it, std::string::const_iterator end);
+
+ void compile_pattern_(const std::string &pattern);
+};
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "pattern_formatter-inl.h"
+#endif
diff --git a/include/spdlog/sinks/android_sink.h b/include/spdlog/sinks/android_sink.h
new file mode 100644
index 00000000..659beabb
--- /dev/null
+++ b/include/spdlog/sinks/android_sink.h
@@ -0,0 +1,119 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifdef __ANDROID__
+
+#include <spdlog/details/fmt_helper.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/details/os.h>
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <android/log.h>
+#include <chrono>
+#include <mutex>
+#include <string>
+#include <thread>
+
+#if !defined(SPDLOG_ANDROID_RETRIES)
+#define SPDLOG_ANDROID_RETRIES 2
+#endif
+
+namespace spdlog {
+namespace sinks {
+
+/*
+ * Android sink (logging using __android_log_write)
+ */
+template<typename Mutex>
+class android_sink final : public base_sink<Mutex>
+{
+public:
+ explicit android_sink(std::string tag = "spdlog", bool use_raw_msg = false)
+ : tag_(std::move(tag))
+ , use_raw_msg_(use_raw_msg)
+ {}
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ const android_LogPriority priority = convert_to_android_(msg.level);
+ memory_buf_t formatted;
+ if (use_raw_msg_)
+ {
+ details::fmt_helper::append_string_view(msg.payload, formatted);
+ }
+ else
+ {
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ }
+ formatted.push_back('\0');
+ const char *msg_output = formatted.data();
+
+ // See system/core/liblog/logger_write.c for explanation of return value
+ int ret = __android_log_write(priority, tag_.c_str(), msg_output);
+ int retry_count = 0;
+ while ((ret == -11 /*EAGAIN*/) && (retry_count < SPDLOG_ANDROID_RETRIES))
+ {
+ details::os::sleep_for_millis(5);
+ ret = __android_log_write(priority, tag_.c_str(), msg_output);
+ retry_count++;
+ }
+
+ if (ret < 0)
+ {
+ throw_spdlog_ex("__android_log_write() failed", ret);
+ }
+ }
+
+ void flush_() override {}
+
+private:
+ static android_LogPriority convert_to_android_(spdlog::level::level_enum level)
+ {
+ switch (level)
+ {
+ case spdlog::level::trace:
+ return ANDROID_LOG_VERBOSE;
+ case spdlog::level::debug:
+ return ANDROID_LOG_DEBUG;
+ case spdlog::level::info:
+ return ANDROID_LOG_INFO;
+ case spdlog::level::warn:
+ return ANDROID_LOG_WARN;
+ case spdlog::level::err:
+ return ANDROID_LOG_ERROR;
+ case spdlog::level::critical:
+ return ANDROID_LOG_FATAL;
+ default:
+ return ANDROID_LOG_DEFAULT;
+ }
+ }
+
+ std::string tag_;
+ bool use_raw_msg_;
+};
+
+using android_sink_mt = android_sink<std::mutex>;
+using android_sink_st = android_sink<details::null_mutex>;
+} // namespace sinks
+
+// Create and register android syslog logger
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> android_logger_mt(const std::string &logger_name, const std::string &tag = "spdlog")
+{
+ return Factory::template create<sinks::android_sink_mt>(logger_name, tag);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> android_logger_st(const std::string &logger_name, const std::string &tag = "spdlog")
+{
+ return Factory::template create<sinks::android_sink_st>(logger_name, tag);
+}
+
+} // namespace spdlog
+
+#endif // __ANDROID__
diff --git a/include/spdlog/sinks/ansicolor_sink-inl.h b/include/spdlog/sinks/ansicolor_sink-inl.h
new file mode 100644
index 00000000..61c0a719
--- /dev/null
+++ b/include/spdlog/sinks/ansicolor_sink-inl.h
@@ -0,0 +1,145 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/ansicolor_sink.h>
+#endif
+
+#include <spdlog/pattern_formatter.h>
+#include <spdlog/details/os.h>
+
+namespace spdlog {
+namespace sinks {
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE ansicolor_sink<ConsoleMutex>::ansicolor_sink(FILE *target_file, color_mode mode)
+ : target_file_(target_file)
+ , mutex_(ConsoleMutex::mutex())
+ , formatter_(details::make_unique<spdlog::pattern_formatter>())
+
+{
+ set_color_mode(mode);
+ colors_[level::trace] = to_string_(white);
+ colors_[level::debug] = to_string_(cyan);
+ colors_[level::info] = to_string_(green);
+ colors_[level::warn] = to_string_(yellow_bold);
+ colors_[level::err] = to_string_(red_bold);
+ colors_[level::critical] = to_string_(bold_on_red);
+ colors_[level::off] = to_string_(reset);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color(level::level_enum color_level, string_view_t color)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ colors_[color_level] = to_string_(color);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::log(const details::log_msg &msg)
+{
+ // Wrap the originally formatted message in color codes.
+ // If color is not supported in the terminal, log as is instead.
+ std::lock_guard<mutex_t> lock(mutex_);
+ msg.color_range_start = 0;
+ msg.color_range_end = 0;
+ memory_buf_t formatted;
+ formatter_->format(msg, formatted);
+ if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
+ {
+ // before color range
+ print_range_(formatted, 0, msg.color_range_start);
+ // in color range
+ print_ccode_(colors_[msg.level]);
+ print_range_(formatted, msg.color_range_start, msg.color_range_end);
+ print_ccode_(reset);
+ // after color range
+ print_range_(formatted, msg.color_range_end, formatted.size());
+ }
+ else // no color
+ {
+ print_range_(formatted, 0, formatted.size());
+ }
+ fflush(target_file_);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::flush()
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ fflush(target_file_);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_pattern(const std::string &pattern)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ formatter_ = std::move(sink_formatter);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE bool ansicolor_sink<ConsoleMutex>::should_color()
+{
+ return should_do_colors_;
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::set_color_mode(color_mode mode)
+{
+ switch (mode)
+ {
+ case color_mode::always:
+ should_do_colors_ = true;
+ return;
+ case color_mode::automatic:
+ should_do_colors_ = details::os::in_terminal(target_file_) && details::os::is_color_terminal();
+ return;
+ case color_mode::never:
+ should_do_colors_ = false;
+ return;
+ default:
+ should_do_colors_ = false;
+ }
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::print_ccode_(const string_view_t &color_code)
+{
+ fwrite(color_code.data(), sizeof(char), color_code.size(), target_file_);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void ansicolor_sink<ConsoleMutex>::print_range_(const memory_buf_t &formatted, size_t start, size_t end)
+{
+ fwrite(formatted.data() + start, sizeof(char), end - start, target_file_);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE std::string ansicolor_sink<ConsoleMutex>::to_string_(const string_view_t &sv)
+{
+ return std::string(sv.data(), sv.size());
+}
+
+// ansicolor_stdout_sink
+template<typename ConsoleMutex>
+SPDLOG_INLINE ansicolor_stdout_sink<ConsoleMutex>::ansicolor_stdout_sink(color_mode mode)
+ : ansicolor_sink<ConsoleMutex>(stdout, mode)
+{}
+
+// ansicolor_stderr_sink
+template<typename ConsoleMutex>
+SPDLOG_INLINE ansicolor_stderr_sink<ConsoleMutex>::ansicolor_stderr_sink(color_mode mode)
+ : ansicolor_sink<ConsoleMutex>(stderr, mode)
+{}
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/ansicolor_sink.h b/include/spdlog/sinks/ansicolor_sink.h
new file mode 100644
index 00000000..4438f706
--- /dev/null
+++ b/include/spdlog/sinks/ansicolor_sink.h
@@ -0,0 +1,118 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/console_globals.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/sinks/sink.h>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <array>
+
+namespace spdlog {
+namespace sinks {
+
+/**
+ * This sink prefixes the output with an ANSI escape sequence color code
+ * depending on the severity
+ * of the message.
+ * If no color terminal detected, omit the escape codes.
+ */
+
+template<typename ConsoleMutex>
+class ansicolor_sink : public sink
+{
+public:
+ using mutex_t = typename ConsoleMutex::mutex_t;
+ ansicolor_sink(FILE *target_file, color_mode mode);
+ ~ansicolor_sink() override = default;
+
+ ansicolor_sink(const ansicolor_sink &other) = delete;
+ ansicolor_sink(ansicolor_sink &&other) = delete;
+
+ ansicolor_sink &operator=(const ansicolor_sink &other) = delete;
+ ansicolor_sink &operator=(ansicolor_sink &&other) = delete;
+
+ void set_color(level::level_enum color_level, string_view_t color);
+ void set_color_mode(color_mode mode);
+ bool should_color();
+
+ void log(const details::log_msg &msg) override;
+ void flush() override;
+ void set_pattern(const std::string &pattern) final;
+ void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override;
+
+ // Formatting codes
+ const string_view_t reset = "\033[m";
+ const string_view_t bold = "\033[1m";
+ const string_view_t dark = "\033[2m";
+ const string_view_t underline = "\033[4m";
+ const string_view_t blink = "\033[5m";
+ const string_view_t reverse = "\033[7m";
+ const string_view_t concealed = "\033[8m";
+ const string_view_t clear_line = "\033[K";
+
+ // Foreground colors
+ const string_view_t black = "\033[30m";
+ const string_view_t red = "\033[31m";
+ const string_view_t green = "\033[32m";
+ const string_view_t yellow = "\033[33m";
+ const string_view_t blue = "\033[34m";
+ const string_view_t magenta = "\033[35m";
+ const string_view_t cyan = "\033[36m";
+ const string_view_t white = "\033[37m";
+
+ /// Background colors
+ const string_view_t on_black = "\033[40m";
+ const string_view_t on_red = "\033[41m";
+ const string_view_t on_green = "\033[42m";
+ const string_view_t on_yellow = "\033[43m";
+ const string_view_t on_blue = "\033[44m";
+ const string_view_t on_magenta = "\033[45m";
+ const string_view_t on_cyan = "\033[46m";
+ const string_view_t on_white = "\033[47m";
+
+ /// Bold colors
+ const string_view_t yellow_bold = "\033[33m\033[1m";
+ const string_view_t red_bold = "\033[31m\033[1m";
+ const string_view_t bold_on_red = "\033[1m\033[41m";
+
+private:
+ FILE *target_file_;
+ mutex_t &mutex_;
+ bool should_do_colors_;
+ std::unique_ptr<spdlog::formatter> formatter_;
+ std::array<std::string, level::n_levels> colors_;
+ void print_ccode_(const string_view_t &color_code);
+ void print_range_(const memory_buf_t &formatted, size_t start, size_t end);
+ static std::string to_string_(const string_view_t &sv);
+};
+
+template<typename ConsoleMutex>
+class ansicolor_stdout_sink : public ansicolor_sink<ConsoleMutex>
+{
+public:
+ explicit ansicolor_stdout_sink(color_mode mode = color_mode::automatic);
+};
+
+template<typename ConsoleMutex>
+class ansicolor_stderr_sink : public ansicolor_sink<ConsoleMutex>
+{
+public:
+ explicit ansicolor_stderr_sink(color_mode mode = color_mode::automatic);
+};
+
+using ansicolor_stdout_sink_mt = ansicolor_stdout_sink<details::console_mutex>;
+using ansicolor_stdout_sink_st = ansicolor_stdout_sink<details::console_nullmutex>;
+
+using ansicolor_stderr_sink_mt = ansicolor_stderr_sink<details::console_mutex>;
+using ansicolor_stderr_sink_st = ansicolor_stderr_sink<details::console_nullmutex>;
+
+} // namespace sinks
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "ansicolor_sink-inl.h"
+#endif
diff --git a/include/spdlog/sinks/base_sink-inl.h b/include/spdlog/sinks/base_sink-inl.h
new file mode 100644
index 00000000..b15fb0e6
--- /dev/null
+++ b/include/spdlog/sinks/base_sink-inl.h
@@ -0,0 +1,63 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/base_sink.h>
+#endif
+
+#include <spdlog/common.h>
+#include <spdlog/pattern_formatter.h>
+
+#include <memory>
+
+template<typename Mutex>
+SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::base_sink()
+ : formatter_{details::make_unique<spdlog::pattern_formatter>()}
+{}
+
+template<typename Mutex>
+SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::base_sink(std::unique_ptr<spdlog::formatter> formatter)
+ : formatter_{std::move(formatter)}
+{}
+
+template<typename Mutex>
+void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::log(const details::log_msg &msg)
+{
+ std::lock_guard<Mutex> lock(mutex_);
+ sink_it_(msg);
+}
+
+template<typename Mutex>
+void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::flush()
+{
+ std::lock_guard<Mutex> lock(mutex_);
+ flush_();
+}
+
+template<typename Mutex>
+void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_pattern(const std::string &pattern)
+{
+ std::lock_guard<Mutex> lock(mutex_);
+ set_pattern_(pattern);
+}
+
+template<typename Mutex>
+void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter)
+{
+ std::lock_guard<Mutex> lock(mutex_);
+ set_formatter_(std::move(sink_formatter));
+}
+
+template<typename Mutex>
+void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_pattern_(const std::string &pattern)
+{
+ set_formatter_(details::make_unique<spdlog::pattern_formatter>(pattern));
+}
+
+template<typename Mutex>
+void SPDLOG_INLINE spdlog::sinks::base_sink<Mutex>::set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter)
+{
+ formatter_ = std::move(sink_formatter);
+}
diff --git a/include/spdlog/sinks/base_sink.h b/include/spdlog/sinks/base_sink.h
new file mode 100644
index 00000000..bf5072f8
--- /dev/null
+++ b/include/spdlog/sinks/base_sink.h
@@ -0,0 +1,52 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+//
+// base sink templated over a mutex (either dummy or real)
+// concrete implementation should override the sink_it_() and flush_() methods.
+// locking is taken care of in this class - no locking needed by the
+// implementers..
+//
+
+#include <spdlog/common.h>
+#include <spdlog/details/log_msg.h>
+#include <spdlog/sinks/sink.h>
+
+namespace spdlog {
+namespace sinks {
+template<typename Mutex>
+class base_sink : public sink
+{
+public:
+ base_sink();
+ explicit base_sink(std::unique_ptr<spdlog::formatter> formatter);
+ ~base_sink() override = default;
+
+ base_sink(const base_sink &) = delete;
+ base_sink(base_sink &&) = delete;
+
+ base_sink &operator=(const base_sink &) = delete;
+ base_sink &operator=(base_sink &&) = delete;
+
+ void log(const details::log_msg &msg) final;
+ void flush() final;
+ void set_pattern(const std::string &pattern) final;
+ void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) final;
+
+protected:
+ // sink formatter
+ std::unique_ptr<spdlog::formatter> formatter_;
+ Mutex mutex_;
+
+ virtual void sink_it_(const details::log_msg &msg) = 0;
+ virtual void flush_() = 0;
+ virtual void set_pattern_(const std::string &pattern);
+ virtual void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter);
+};
+} // namespace sinks
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "base_sink-inl.h"
+#endif
diff --git a/include/spdlog/sinks/basic_file_sink-inl.h b/include/spdlog/sinks/basic_file_sink-inl.h
new file mode 100644
index 00000000..1260d15c
--- /dev/null
+++ b/include/spdlog/sinks/basic_file_sink-inl.h
@@ -0,0 +1,43 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/basic_file_sink.h>
+#endif
+
+#include <spdlog/common.h>
+#include <spdlog/details/os.h>
+
+namespace spdlog {
+namespace sinks {
+
+template<typename Mutex>
+SPDLOG_INLINE basic_file_sink<Mutex>::basic_file_sink(const filename_t &filename, bool truncate)
+{
+ file_helper_.open(filename, truncate);
+}
+
+template<typename Mutex>
+SPDLOG_INLINE const filename_t &basic_file_sink<Mutex>::filename() const
+{
+ return file_helper_.filename();
+}
+
+template<typename Mutex>
+SPDLOG_INLINE void basic_file_sink<Mutex>::sink_it_(const details::log_msg &msg)
+{
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ file_helper_.write(formatted);
+}
+
+template<typename Mutex>
+SPDLOG_INLINE void basic_file_sink<Mutex>::flush_()
+{
+ file_helper_.flush();
+}
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/basic_file_sink.h b/include/spdlog/sinks/basic_file_sink.h
new file mode 100644
index 00000000..4a742624
--- /dev/null
+++ b/include/spdlog/sinks/basic_file_sink.h
@@ -0,0 +1,58 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/file_helper.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <mutex>
+#include <string>
+
+namespace spdlog {
+namespace sinks {
+/*
+ * Trivial file sink with single file as target
+ */
+template<typename Mutex>
+class basic_file_sink final : public base_sink<Mutex>
+{
+public:
+ explicit basic_file_sink(const filename_t &filename, bool truncate = false);
+ const filename_t &filename() const;
+
+protected:
+ void sink_it_(const details::log_msg &msg) override;
+ void flush_() override;
+
+private:
+ details::file_helper file_helper_;
+};
+
+using basic_file_sink_mt = basic_file_sink<std::mutex>;
+using basic_file_sink_st = basic_file_sink<details::null_mutex>;
+
+} // namespace sinks
+
+//
+// factory functions
+//
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> basic_logger_mt(const std::string &logger_name, const filename_t &filename, bool truncate = false)
+{
+ return Factory::template create<sinks::basic_file_sink_mt>(logger_name, filename, truncate);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> basic_logger_st(const std::string &logger_name, const filename_t &filename, bool truncate = false)
+{
+ return Factory::template create<sinks::basic_file_sink_st>(logger_name, filename, truncate);
+}
+
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "basic_file_sink-inl.h"
+#endif
diff --git a/include/spdlog/sinks/daily_file_sink.h b/include/spdlog/sinks/daily_file_sink.h
new file mode 100644
index 00000000..16be821a
--- /dev/null
+++ b/include/spdlog/sinks/daily_file_sink.h
@@ -0,0 +1,238 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <spdlog/details/file_helper.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/fmt/fmt.h>
+#include <spdlog/fmt/chrono.h>
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/os.h>
+#include <spdlog/details/circular_q.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <chrono>
+#include <cstdio>
+#include <ctime>
+#include <mutex>
+#include <string>
+
+namespace spdlog {
+namespace sinks {
+
+/*
+ * Generator of daily log file names in format basename.YYYY-MM-DD.ext
+ */
+struct daily_filename_calculator
+{
+ // Create filename for the form basename.YYYY-MM-DD
+ static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
+ {
+ filename_t basename, ext;
+ std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
+ return fmt::format(
+ SPDLOG_FILENAME_T("{}_{:04d}-{:02d}-{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, ext);
+ }
+};
+
+/*
+ * Generator of daily log file names with strftime format.
+ * Usages:
+ * auto sink = std::make_shared<spdlog::sinks::daily_file_format_sink_mt>("myapp-%Y-%m-%d:%H:%M:%S.log", hour, minute);"
+ * auto logger = spdlog::daily_logger_format_mt("loggername, "myapp-%Y-%m-%d:%X.log", hour, minute)"
+ *
+ */
+struct daily_filename_format_calculator
+{
+ static filename_t calc_filename (const filename_t &filename, const tm &now_tm)
+ {
+ // generate fmt datetime format string, e.g. {:%Y-%m-%d}.
+ filename_t fmt_filename = fmt::format(SPDLOG_FILENAME_T ("{{:{}}}"), filename);
+ return fmt::format(fmt_filename, now_tm);
+ }
+};
+
+/*
+ * Rotating file sink based on date.
+ * If truncate != false , the created file will be truncated.
+ * If max_files > 0, retain only the last max_files and delete previous.
+ */
+template<typename Mutex, typename FileNameCalc = daily_filename_calculator>
+class daily_file_sink final : public base_sink<Mutex>
+{
+public:
+ // create daily file sink which rotates on given time
+ daily_file_sink(filename_t base_filename, int rotation_hour, int rotation_minute, bool truncate = false, uint16_t max_files = 0)
+ : base_filename_(std::move(base_filename))
+ , rotation_h_(rotation_hour)
+ , rotation_m_(rotation_minute)
+ , truncate_(truncate)
+ , max_files_(max_files)
+ , filenames_q_()
+ {
+ if (rotation_hour < 0 || rotation_hour > 23 || rotation_minute < 0 || rotation_minute > 59)
+ {
+ throw_spdlog_ex("daily_file_sink: Invalid rotation time in ctor");
+ }
+
+ auto now = log_clock::now();
+ auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
+ file_helper_.open(filename, truncate_);
+ rotation_tp_ = next_rotation_tp_();
+
+ if (max_files_ > 0)
+ {
+ init_filenames_q_();
+ }
+ }
+
+ filename_t filename()
+ {
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ return file_helper_.filename();
+ }
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ auto time = msg.time;
+ bool should_rotate = time >= rotation_tp_;
+ if (should_rotate)
+ {
+ auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
+ file_helper_.open(filename, truncate_);
+ rotation_tp_ = next_rotation_tp_();
+ }
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ file_helper_.write(formatted);
+
+ // Do the cleaning only at the end because it might throw on failure.
+ if (should_rotate && max_files_ > 0)
+ {
+ delete_old_();
+ }
+ }
+
+ void flush_() override
+ {
+ file_helper_.flush();
+ }
+
+private:
+ void init_filenames_q_()
+ {
+ using details::os::path_exists;
+
+ filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
+ std::vector<filename_t> filenames;
+ auto now = log_clock::now();
+ while (filenames.size() < max_files_)
+ {
+ auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
+ if (!path_exists(filename))
+ {
+ break;
+ }
+ filenames.emplace_back(filename);
+ now -= std::chrono::hours(24);
+ }
+ for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter)
+ {
+ filenames_q_.push_back(std::move(*iter));
+ }
+ }
+
+ tm now_tm(log_clock::time_point tp)
+ {
+ time_t tnow = log_clock::to_time_t(tp);
+ return spdlog::details::os::localtime(tnow);
+ }
+
+ log_clock::time_point next_rotation_tp_()
+ {
+ auto now = log_clock::now();
+ tm date = now_tm(now);
+ date.tm_hour = rotation_h_;
+ date.tm_min = rotation_m_;
+ date.tm_sec = 0;
+ auto rotation_time = log_clock::from_time_t(std::mktime(&date));
+ if (rotation_time > now)
+ {
+ return rotation_time;
+ }
+ return {rotation_time + std::chrono::hours(24)};
+ }
+
+ // Delete the file N rotations ago.
+ // Throw spdlog_ex on failure to delete the old file.
+ void delete_old_()
+ {
+ using details::os::filename_to_str;
+ using details::os::remove_if_exists;
+
+ filename_t current_file = file_helper_.filename();
+ if (filenames_q_.full())
+ {
+ auto old_filename = std::move(filenames_q_.front());
+ filenames_q_.pop_front();
+ bool ok = remove_if_exists(old_filename) == 0;
+ if (!ok)
+ {
+ filenames_q_.push_back(std::move(current_file));
+ throw_spdlog_ex("Failed removing daily file " + filename_to_str(old_filename), errno);
+ }
+ }
+ filenames_q_.push_back(std::move(current_file));
+ }
+
+ filename_t base_filename_;
+ int rotation_h_;
+ int rotation_m_;
+ log_clock::time_point rotation_tp_;
+ details::file_helper file_helper_;
+ bool truncate_;
+ uint16_t max_files_;
+ details::circular_q<filename_t> filenames_q_;
+};
+
+using daily_file_sink_mt = daily_file_sink<std::mutex>;
+using daily_file_sink_st = daily_file_sink<details::null_mutex>;
+using daily_file_format_sink_mt = daily_file_sink<std::mutex, daily_filename_format_calculator>;
+using daily_file_format_sink_st = daily_file_sink<details::null_mutex, daily_filename_format_calculator>;
+
+} // namespace sinks
+
+//
+// factory functions
+//
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> daily_logger_mt(
+ const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
+{
+ return Factory::template create<sinks::daily_file_sink_mt>(logger_name, filename, hour, minute, truncate, max_files);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> daily_logger_format_mt(
+ const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
+{
+ return Factory::template create<sinks::daily_file_format_sink_mt>(logger_name, filename, hour, minute, truncate, max_files);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> daily_logger_st(
+ const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
+{
+ return Factory::template create<sinks::daily_file_sink_st>(logger_name, filename, hour, minute, truncate, max_files);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> daily_logger_format_st(
+ const std::string &logger_name, const filename_t &filename, int hour = 0, int minute = 0, bool truncate = false, uint16_t max_files = 0)
+{
+ return Factory::template create<sinks::daily_file_format_sink_st>(logger_name, filename, hour, minute, truncate, max_files);
+}
+} // namespace spdlog
diff --git a/include/spdlog/sinks/dist_sink.h b/include/spdlog/sinks/dist_sink.h
new file mode 100644
index 00000000..8fccb4ee
--- /dev/null
+++ b/include/spdlog/sinks/dist_sink.h
@@ -0,0 +1,97 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include "base_sink.h"
+#include <spdlog/details/log_msg.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/pattern_formatter.h>
+
+#include <algorithm>
+#include <memory>
+#include <mutex>
+#include <vector>
+
+// Distribution sink (mux). Stores a vector of sinks which get called when log
+// is called
+
+namespace spdlog {
+namespace sinks {
+
+template<typename Mutex>
+class dist_sink : public base_sink<Mutex>
+{
+public:
+ dist_sink() = default;
+ explicit dist_sink(std::vector<std::shared_ptr<sink>> sinks)
+ : sinks_(sinks)
+ {}
+
+ dist_sink(const dist_sink &) = delete;
+ dist_sink &operator=(const dist_sink &) = delete;
+
+ void add_sink(std::shared_ptr<sink> sink)
+ {
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ sinks_.push_back(sink);
+ }
+
+ void remove_sink(std::shared_ptr<sink> sink)
+ {
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ sinks_.erase(std::remove(sinks_.begin(), sinks_.end(), sink), sinks_.end());
+ }
+
+ void set_sinks(std::vector<std::shared_ptr<sink>> sinks)
+ {
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ sinks_ = std::move(sinks);
+ }
+
+ std::vector<std::shared_ptr<sink>> &sinks()
+ {
+ return sinks_;
+ }
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ for (auto &sink : sinks_)
+ {
+ if (sink->should_log(msg.level))
+ {
+ sink->log(msg);
+ }
+ }
+ }
+
+ void flush_() override
+ {
+ for (auto &sink : sinks_)
+ {
+ sink->flush();
+ }
+ }
+
+ void set_pattern_(const std::string &pattern) override
+ {
+ set_formatter_(details::make_unique<spdlog::pattern_formatter>(pattern));
+ }
+
+ void set_formatter_(std::unique_ptr<spdlog::formatter> sink_formatter) override
+ {
+ base_sink<Mutex>::formatter_ = std::move(sink_formatter);
+ for (auto &sink : sinks_)
+ {
+ sink->set_formatter(base_sink<Mutex>::formatter_->clone());
+ }
+ }
+ std::vector<std::shared_ptr<sink>> sinks_;
+};
+
+using dist_sink_mt = dist_sink<std::mutex>;
+using dist_sink_st = dist_sink<details::null_mutex>;
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/dup_filter_sink.h b/include/spdlog/sinks/dup_filter_sink.h
new file mode 100644
index 00000000..c9a08d68
--- /dev/null
+++ b/include/spdlog/sinks/dup_filter_sink.h
@@ -0,0 +1,90 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include "dist_sink.h"
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/details/log_msg.h>
+
+#include <mutex>
+#include <string>
+#include <chrono>
+
+// Duplicate message removal sink.
+// Skip the message if previous one is identical and less than "max_skip_duration" have passed
+//
+// Example:
+//
+// #include <spdlog/sinks/dup_filter_sink.h>
+//
+// int main() {
+// auto dup_filter = std::make_shared<dup_filter_sink_st>(std::chrono::seconds(5));
+// dup_filter->add_sink(std::make_shared<stdout_color_sink_mt>());
+// spdlog::logger l("logger", dup_filter);
+// l.info("Hello");
+// l.info("Hello");
+// l.info("Hello");
+// l.info("Different Hello");
+// }
+//
+// Will produce:
+// [2019-06-25 17:50:56.511] [logger] [info] Hello
+// [2019-06-25 17:50:56.512] [logger] [info] Skipped 3 duplicate messages..
+// [2019-06-25 17:50:56.512] [logger] [info] Different Hello
+
+namespace spdlog {
+namespace sinks {
+template<typename Mutex>
+class dup_filter_sink : public dist_sink<Mutex>
+{
+public:
+ template<class Rep, class Period>
+ explicit dup_filter_sink(std::chrono::duration<Rep, Period> max_skip_duration)
+ : max_skip_duration_{max_skip_duration}
+ {}
+
+protected:
+ std::chrono::microseconds max_skip_duration_;
+ log_clock::time_point last_msg_time_;
+ std::string last_msg_payload_;
+ size_t skip_counter_ = 0;
+
+ void sink_it_(const details::log_msg &msg) override
+ {
+ bool filtered = filter_(msg);
+ if (!filtered)
+ {
+ skip_counter_ += 1;
+ return;
+ }
+
+ // log the "skipped.." message
+ if (skip_counter_ > 0)
+ {
+ memory_buf_t buf;
+ fmt::format_to(buf, "Skipped {} duplicate messages..", skip_counter_);
+ details::log_msg skipped_msg{msg.logger_name, level::info, string_view_t{buf.data(), buf.size()}};
+ dist_sink<Mutex>::sink_it_(skipped_msg);
+ }
+
+ // log current message
+ dist_sink<Mutex>::sink_it_(msg);
+ last_msg_time_ = msg.time;
+ skip_counter_ = 0;
+ last_msg_payload_.assign(msg.payload.data(), msg.payload.data() + msg.payload.size());
+ }
+
+ // return whether the log msg should be displayed (true) or skipped (false)
+ bool filter_(const details::log_msg &msg)
+ {
+ auto filter_duration = msg.time - last_msg_time_;
+ return (filter_duration > max_skip_duration_) || (msg.payload != last_msg_payload_);
+ }
+};
+
+using dup_filter_sink_mt = dup_filter_sink<std::mutex>;
+using dup_filter_sink_st = dup_filter_sink<details::null_mutex>;
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/hourly_file_sink.h b/include/spdlog/sinks/hourly_file_sink.h
new file mode 100644
index 00000000..f5e34366
--- /dev/null
+++ b/include/spdlog/sinks/hourly_file_sink.h
@@ -0,0 +1,194 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <spdlog/details/file_helper.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/fmt/fmt.h>
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/os.h>
+#include <spdlog/details/circular_q.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <chrono>
+#include <cstdio>
+#include <ctime>
+#include <mutex>
+#include <string>
+
+namespace spdlog {
+namespace sinks {
+
+/*
+ * Generator of Hourly log file names in format basename.YYYY-MM-DD-HH.ext
+ */
+struct hourly_filename_calculator
+{
+ // Create filename for the form basename.YYYY-MM-DD-H
+ static filename_t calc_filename(const filename_t &filename, const tm &now_tm)
+ {
+ filename_t basename, ext;
+ std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
+ return fmt::format(
+ SPDLOG_FILENAME_T("{}_{:04d}{:02d}{:02d}_{:02d}{}"), basename, now_tm.tm_year + 1900, now_tm.tm_mon + 1, now_tm.tm_mday, now_tm.tm_hour, ext);
+ }
+};
+
+/*
+ * Rotating file sink based on time.
+ * If truncate != false , the created file will be truncated.
+ * If max_files > 0, retain only the last max_files and delete previous.
+ */
+template<typename Mutex, typename FileNameCalc = hourly_filename_calculator>
+class hourly_file_sink final : public base_sink<Mutex>
+{
+public:
+ // create hourly file sink which rotates on given time
+ hourly_file_sink(filename_t base_filename, bool truncate = false, uint16_t max_files = 0)
+ : base_filename_(std::move(base_filename))
+ , truncate_(truncate)
+ , max_files_(max_files)
+ , filenames_q_()
+ {
+ auto now = log_clock::now();
+ auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
+ file_helper_.open(filename, truncate_);
+ rotation_tp_ = next_rotation_tp_();
+
+ if (max_files_ > 0)
+ {
+ init_filenames_q_();
+ }
+ }
+
+ filename_t filename()
+ {
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ return file_helper_.filename();
+ }
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ auto time = msg.time;
+ bool should_rotate = time >= rotation_tp_;
+ if (should_rotate)
+ {
+ auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(time));
+ file_helper_.open(filename, truncate_);
+ rotation_tp_ = next_rotation_tp_();
+ }
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ file_helper_.write(formatted);
+
+ // Do the cleaning only at the end because it might throw on failure.
+ if (should_rotate && max_files_ > 0)
+ {
+ delete_old_();
+ }
+ }
+
+ void flush_() override
+ {
+ file_helper_.flush();
+ }
+
+private:
+ void init_filenames_q_()
+ {
+ using details::os::path_exists;
+
+ filenames_q_ = details::circular_q<filename_t>(static_cast<size_t>(max_files_));
+ std::vector<filename_t> filenames;
+ auto now = log_clock::now();
+ while (filenames.size() < max_files_)
+ {
+ auto filename = FileNameCalc::calc_filename(base_filename_, now_tm(now));
+ if (!path_exists(filename))
+ {
+ break;
+ }
+ filenames.emplace_back(filename);
+ now -= std::chrono::hours(1);
+ }
+ for (auto iter = filenames.rbegin(); iter != filenames.rend(); ++iter)
+ {
+ filenames_q_.push_back(std::move(*iter));
+ }
+ }
+
+ tm now_tm(log_clock::time_point tp)
+ {
+ time_t tnow = log_clock::to_time_t(tp);
+ return spdlog::details::os::localtime(tnow);
+ }
+
+ log_clock::time_point next_rotation_tp_()
+ {
+ auto now = log_clock::now();
+ tm date = now_tm(now);
+ date.tm_min = 0;
+ date.tm_sec = 0;
+ auto rotation_time = log_clock::from_time_t(std::mktime(&date));
+ if (rotation_time > now)
+ {
+ return rotation_time;
+ }
+ return {rotation_time + std::chrono::hours(1)};
+ }
+
+ // Delete the file N rotations ago.
+ // Throw spdlog_ex on failure to delete the old file.
+ void delete_old_()
+ {
+ using details::os::filename_to_str;
+ using details::os::remove_if_exists;
+
+ filename_t current_file = file_helper_.filename();
+ if (filenames_q_.full())
+ {
+ auto old_filename = std::move(filenames_q_.front());
+ filenames_q_.pop_front();
+ bool ok = remove_if_exists(old_filename) == 0;
+ if (!ok)
+ {
+ filenames_q_.push_back(std::move(current_file));
+ SPDLOG_THROW(spdlog_ex("Failed removing hourly file " + filename_to_str(old_filename), errno));
+ }
+ }
+ filenames_q_.push_back(std::move(current_file));
+ }
+
+ filename_t base_filename_;
+ log_clock::time_point rotation_tp_;
+ details::file_helper file_helper_;
+ bool truncate_;
+ uint16_t max_files_;
+ details::circular_q<filename_t> filenames_q_;
+};
+
+using hourly_file_sink_mt = hourly_file_sink<std::mutex>;
+using hourly_file_sink_st = hourly_file_sink<details::null_mutex>;
+
+} // namespace sinks
+
+//
+// factory functions
+//
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> hourly_logger_mt(
+ const std::string &logger_name, const filename_t &filename, bool truncate = false, uint16_t max_files = 0)
+{
+ return Factory::template create<sinks::hourly_file_sink_mt>(logger_name, filename, truncate, max_files);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> hourly_logger_st(
+ const std::string &logger_name, const filename_t &filename, bool truncate = false, uint16_t max_files = 0)
+{
+ return Factory::template create<sinks::hourly_file_sink_st>(logger_name, filename, truncate, max_files);
+}
+} // namespace spdlog
diff --git a/include/spdlog/sinks/msvc_sink.h b/include/spdlog/sinks/msvc_sink.h
new file mode 100644
index 00000000..8fec428d
--- /dev/null
+++ b/include/spdlog/sinks/msvc_sink.h
@@ -0,0 +1,49 @@
+// Copyright(c) 2016 Alexander Dalshov.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#if defined(_WIN32)
+
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/sinks/base_sink.h>
+
+#include <mutex>
+#include <string>
+
+
+// Avoid including windows.h (https://stackoverflow.com/a/30741042)
+extern "C" __declspec(dllimport) void __stdcall OutputDebugStringA(const char *lpOutputString);
+
+namespace spdlog {
+namespace sinks {
+/*
+ * MSVC sink (logging using OutputDebugStringA)
+ */
+template<typename Mutex>
+class msvc_sink : public base_sink<Mutex>
+{
+public:
+ msvc_sink() = default;
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ OutputDebugStringA(fmt::to_string(formatted).c_str());
+ }
+
+ void flush_() override {}
+};
+
+using msvc_sink_mt = msvc_sink<std::mutex>;
+using msvc_sink_st = msvc_sink<details::null_mutex>;
+
+using windebug_sink_mt = msvc_sink_mt;
+using windebug_sink_st = msvc_sink_st;
+
+} // namespace sinks
+} // namespace spdlog
+
+#endif
diff --git a/include/spdlog/sinks/null_sink.h b/include/spdlog/sinks/null_sink.h
new file mode 100644
index 00000000..eb832801
--- /dev/null
+++ b/include/spdlog/sinks/null_sink.h
@@ -0,0 +1,44 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <mutex>
+
+namespace spdlog {
+namespace sinks {
+
+template<typename Mutex>
+class null_sink : public base_sink<Mutex>
+{
+protected:
+ void sink_it_(const details::log_msg &) override {}
+ void flush_() override {}
+};
+
+using null_sink_mt = null_sink<details::null_mutex>;
+using null_sink_st = null_sink<details::null_mutex>;
+
+} // namespace sinks
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> null_logger_mt(const std::string &logger_name)
+{
+ auto null_logger = Factory::template create<sinks::null_sink_mt>(logger_name);
+ null_logger->set_level(level::off);
+ return null_logger;
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> null_logger_st(const std::string &logger_name)
+{
+ auto null_logger = Factory::template create<sinks::null_sink_st>(logger_name);
+ null_logger->set_level(level::off);
+ return null_logger;
+}
+
+} // namespace spdlog
diff --git a/include/spdlog/sinks/ostream_sink.h b/include/spdlog/sinks/ostream_sink.h
new file mode 100644
index 00000000..95c1e962
--- /dev/null
+++ b/include/spdlog/sinks/ostream_sink.h
@@ -0,0 +1,50 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/sinks/base_sink.h>
+
+#include <mutex>
+#include <ostream>
+
+namespace spdlog {
+namespace sinks {
+template<typename Mutex>
+class ostream_sink final : public base_sink<Mutex>
+{
+public:
+ explicit ostream_sink(std::ostream &os, bool force_flush = false)
+ : ostream_(os)
+ , force_flush_(force_flush)
+ {}
+ ostream_sink(const ostream_sink &) = delete;
+ ostream_sink &operator=(const ostream_sink &) = delete;
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ ostream_.write(formatted.data(), static_cast<std::streamsize>(formatted.size()));
+ if (force_flush_)
+ {
+ ostream_.flush();
+ }
+ }
+
+ void flush_() override
+ {
+ ostream_.flush();
+ }
+
+ std::ostream &ostream_;
+ bool force_flush_;
+};
+
+using ostream_sink_mt = ostream_sink<std::mutex>;
+using ostream_sink_st = ostream_sink<details::null_mutex>;
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/ringbuffer_sink.h b/include/spdlog/sinks/ringbuffer_sink.h
new file mode 100644
index 00000000..1ee3f691
--- /dev/null
+++ b/include/spdlog/sinks/ringbuffer_sink.h
@@ -0,0 +1,74 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include "spdlog/sinks/base_sink.h"
+#include "spdlog/details/circular_q.h"
+#include "spdlog/details/log_msg_buffer.h"
+#include "spdlog/details/null_mutex.h"
+
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace spdlog {
+namespace sinks {
+/*
+ * Ring buffer sink
+ */
+template<typename Mutex>
+class ringbuffer_sink final : public base_sink<Mutex>
+{
+public:
+ explicit ringbuffer_sink(size_t n_items)
+ : q_{n_items}
+ {}
+
+ std::vector<details::log_msg_buffer> last_raw(size_t lim = 0)
+ {
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ auto items_available = q_.size();
+ auto n_items = lim > 0 ? (std::min)(lim, items_available) : items_available;
+ std::vector<details::log_msg_buffer> ret;
+ ret.reserve(n_items);
+ for (size_t i = (items_available - n_items); i < items_available; i++)
+ {
+ ret.push_back(q_.at(i));
+ }
+ return ret;
+ }
+
+ std::vector<std::string> last_formatted(size_t lim = 0)
+ {
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ auto items_available = q_.size();
+ auto n_items = lim > 0 ? (std::min)(lim, items_available) : items_available;
+ std::vector<std::string> ret;
+ ret.reserve(n_items);
+ for (size_t i = (items_available - n_items); i < items_available; i++)
+ {
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(q_.at(i), formatted);
+ ret.push_back(fmt::to_string(formatted));
+ }
+ return ret;
+ }
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ q_.push_back(details::log_msg_buffer{msg});
+ }
+ void flush_() override {}
+
+private:
+ details::circular_q<details::log_msg_buffer> q_;
+};
+
+using ringbuffer_sink_mt = ringbuffer_sink<std::mutex>;
+using ringbuffer_sink_st = ringbuffer_sink<details::null_mutex>;
+
+} // namespace sinks
+
+} // namespace spdlog
diff --git a/include/spdlog/sinks/rotating_file_sink-inl.h b/include/spdlog/sinks/rotating_file_sink-inl.h
new file mode 100644
index 00000000..d715ebf3
--- /dev/null
+++ b/include/spdlog/sinks/rotating_file_sink-inl.h
@@ -0,0 +1,131 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/rotating_file_sink.h>
+#endif
+
+#include <spdlog/common.h>
+
+#include <spdlog/details/file_helper.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/fmt/fmt.h>
+
+#include <cerrno>
+#include <chrono>
+#include <ctime>
+#include <mutex>
+#include <string>
+#include <tuple>
+
+namespace spdlog {
+namespace sinks {
+
+template<typename Mutex>
+SPDLOG_INLINE rotating_file_sink<Mutex>::rotating_file_sink(
+ filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open)
+ : base_filename_(std::move(base_filename))
+ , max_size_(max_size)
+ , max_files_(max_files)
+{
+ file_helper_.open(calc_filename(base_filename_, 0));
+ current_size_ = file_helper_.size(); // expensive. called only once
+ if (rotate_on_open && current_size_ > 0)
+ {
+ rotate_();
+ }
+}
+
+// calc filename according to index and file extension if exists.
+// e.g. calc_filename("logs/mylog.txt, 3) => "logs/mylog.3.txt".
+template<typename Mutex>
+SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::calc_filename(const filename_t &filename, std::size_t index)
+{
+ if (index == 0u)
+ {
+ return filename;
+ }
+
+ filename_t basename, ext;
+ std::tie(basename, ext) = details::file_helper::split_by_extension(filename);
+ return fmt::format(SPDLOG_FILENAME_T("{}.{}{}"), basename, index, ext);
+}
+
+template<typename Mutex>
+SPDLOG_INLINE filename_t rotating_file_sink<Mutex>::filename()
+{
+ std::lock_guard<Mutex> lock(base_sink<Mutex>::mutex_);
+ return file_helper_.filename();
+}
+
+template<typename Mutex>
+SPDLOG_INLINE void rotating_file_sink<Mutex>::sink_it_(const details::log_msg &msg)
+{
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ current_size_ += formatted.size();
+ if (current_size_ > max_size_)
+ {
+ rotate_();
+ current_size_ = formatted.size();
+ }
+ file_helper_.write(formatted);
+}
+
+template<typename Mutex>
+SPDLOG_INLINE void rotating_file_sink<Mutex>::flush_()
+{
+ file_helper_.flush();
+}
+
+// Rotate files:
+// log.txt -> log.1.txt
+// log.1.txt -> log.2.txt
+// log.2.txt -> log.3.txt
+// log.3.txt -> delete
+template<typename Mutex>
+SPDLOG_INLINE void rotating_file_sink<Mutex>::rotate_()
+{
+ using details::os::filename_to_str;
+ using details::os::path_exists;
+ file_helper_.close();
+ for (auto i = max_files_; i > 0; --i)
+ {
+ filename_t src = calc_filename(base_filename_, i - 1);
+ if (!path_exists(src))
+ {
+ continue;
+ }
+ filename_t target = calc_filename(base_filename_, i);
+
+ if (!rename_file_(src, target))
+ {
+ // if failed try again after a small delay.
+ // this is a workaround to a windows issue, where very high rotation
+ // rates can cause the rename to fail with permission denied (because of antivirus?).
+ details::os::sleep_for_millis(100);
+ if (!rename_file_(src, target))
+ {
+ file_helper_.reopen(true); // truncate the log file anyway to prevent it to grow beyond its limit!
+ current_size_ = 0;
+ throw_spdlog_ex("rotating_file_sink: failed renaming " + filename_to_str(src) + " to " + filename_to_str(target), errno);
+ }
+ }
+ }
+ file_helper_.reopen(true);
+}
+
+// delete the target if exists, and rename the src file to target
+// return true on success, false otherwise.
+template<typename Mutex>
+SPDLOG_INLINE bool rotating_file_sink<Mutex>::rename_file_(const filename_t &src_filename, const filename_t &target_filename)
+{
+ // try to delete the target file in case it already exists.
+ (void)details::os::remove(target_filename);
+ return details::os::rename(src_filename, target_filename) == 0;
+}
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/rotating_file_sink.h b/include/spdlog/sinks/rotating_file_sink.h
new file mode 100644
index 00000000..e1e85a7d
--- /dev/null
+++ b/include/spdlog/sinks/rotating_file_sink.h
@@ -0,0 +1,78 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/file_helper.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <chrono>
+#include <mutex>
+#include <string>
+
+namespace spdlog {
+namespace sinks {
+
+//
+// Rotating file sink based on size
+//
+template<typename Mutex>
+class rotating_file_sink final : public base_sink<Mutex>
+{
+public:
+ rotating_file_sink(filename_t base_filename, std::size_t max_size, std::size_t max_files, bool rotate_on_open = false);
+ static filename_t calc_filename(const filename_t &filename, std::size_t index);
+ filename_t filename();
+
+protected:
+ void sink_it_(const details::log_msg &msg) override;
+ void flush_() override;
+
+private:
+ // Rotate files:
+ // log.txt -> log.1.txt
+ // log.1.txt -> log.2.txt
+ // log.2.txt -> log.3.txt
+ // log.3.txt -> delete
+ void rotate_();
+
+ // delete the target if exists, and rename the src file to target
+ // return true on success, false otherwise.
+ bool rename_file_(const filename_t &src_filename, const filename_t &target_filename);
+
+ filename_t base_filename_;
+ std::size_t max_size_;
+ std::size_t max_files_;
+ std::size_t current_size_;
+ details::file_helper file_helper_;
+};
+
+using rotating_file_sink_mt = rotating_file_sink<std::mutex>;
+using rotating_file_sink_st = rotating_file_sink<details::null_mutex>;
+
+} // namespace sinks
+
+//
+// factory functions
+//
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> rotating_logger_mt(
+ const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files, bool rotate_on_open = false)
+{
+ return Factory::template create<sinks::rotating_file_sink_mt>(logger_name, filename, max_file_size, max_files, rotate_on_open);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> rotating_logger_st(
+ const std::string &logger_name, const filename_t &filename, size_t max_file_size, size_t max_files, bool rotate_on_open = false)
+{
+ return Factory::template create<sinks::rotating_file_sink_st>(logger_name, filename, max_file_size, max_files, rotate_on_open);
+}
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "rotating_file_sink-inl.h"
+#endif
diff --git a/include/spdlog/sinks/sink-inl.h b/include/spdlog/sinks/sink-inl.h
new file mode 100644
index 00000000..a8dd6a6c
--- /dev/null
+++ b/include/spdlog/sinks/sink-inl.h
@@ -0,0 +1,25 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/sink.h>
+#endif
+
+#include <spdlog/common.h>
+
+SPDLOG_INLINE bool spdlog::sinks::sink::should_log(spdlog::level::level_enum msg_level) const
+{
+ return msg_level >= level_.load(std::memory_order_relaxed);
+}
+
+SPDLOG_INLINE void spdlog::sinks::sink::set_level(level::level_enum log_level)
+{
+ level_.store(log_level, std::memory_order_relaxed);
+}
+
+SPDLOG_INLINE spdlog::level::level_enum spdlog::sinks::sink::level() const
+{
+ return static_cast<spdlog::level::level_enum>(level_.load(std::memory_order_relaxed));
+}
diff --git a/include/spdlog/sinks/sink.h b/include/spdlog/sinks/sink.h
new file mode 100644
index 00000000..be99744d
--- /dev/null
+++ b/include/spdlog/sinks/sink.h
@@ -0,0 +1,35 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/log_msg.h>
+#include <spdlog/formatter.h>
+
+namespace spdlog {
+
+namespace sinks {
+class SPDLOG_API sink
+{
+public:
+ virtual ~sink() = default;
+ virtual void log(const details::log_msg &msg) = 0;
+ virtual void flush() = 0;
+ virtual void set_pattern(const std::string &pattern) = 0;
+ virtual void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) = 0;
+
+ void set_level(level::level_enum log_level);
+ level::level_enum level() const;
+ bool should_log(level::level_enum msg_level) const;
+
+protected:
+ // sink log level - default is all
+ level_t level_{level::trace};
+};
+
+} // namespace sinks
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "sink-inl.h"
+#endif
diff --git a/include/spdlog/sinks/stdout_color_sinks-inl.h b/include/spdlog/sinks/stdout_color_sinks-inl.h
new file mode 100644
index 00000000..935f1ccc
--- /dev/null
+++ b/include/spdlog/sinks/stdout_color_sinks-inl.h
@@ -0,0 +1,38 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/stdout_color_sinks.h>
+#endif
+
+#include <spdlog/logger.h>
+#include <spdlog/common.h>
+
+namespace spdlog {
+
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name, color_mode mode)
+{
+ return Factory::template create<sinks::stdout_color_sink_mt>(logger_name, mode);
+}
+
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stdout_color_st(const std::string &logger_name, color_mode mode)
+{
+ return Factory::template create<sinks::stdout_color_sink_st>(logger_name, mode);
+}
+
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name, color_mode mode)
+{
+ return Factory::template create<sinks::stderr_color_sink_mt>(logger_name, mode);
+}
+
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mode mode)
+{
+ return Factory::template create<sinks::stderr_color_sink_st>(logger_name, mode);
+}
+} // namespace spdlog
diff --git a/include/spdlog/sinks/stdout_color_sinks.h b/include/spdlog/sinks/stdout_color_sinks.h
new file mode 100644
index 00000000..e67aa91b
--- /dev/null
+++ b/include/spdlog/sinks/stdout_color_sinks.h
@@ -0,0 +1,45 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifdef _WIN32
+#include <spdlog/sinks/wincolor_sink.h>
+#else
+#include <spdlog/sinks/ansicolor_sink.h>
+#endif
+
+#include <spdlog/details/synchronous_factory.h>
+
+namespace spdlog {
+namespace sinks {
+#ifdef _WIN32
+using stdout_color_sink_mt = wincolor_stdout_sink_mt;
+using stdout_color_sink_st = wincolor_stdout_sink_st;
+using stderr_color_sink_mt = wincolor_stderr_sink_mt;
+using stderr_color_sink_st = wincolor_stderr_sink_st;
+#else
+using stdout_color_sink_mt = ansicolor_stdout_sink_mt;
+using stdout_color_sink_st = ansicolor_stdout_sink_st;
+using stderr_color_sink_mt = ansicolor_stderr_sink_mt;
+using stderr_color_sink_st = ansicolor_stderr_sink_st;
+#endif
+} // namespace sinks
+
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stdout_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic);
+
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stdout_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic);
+
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stderr_color_mt(const std::string &logger_name, color_mode mode = color_mode::automatic);
+
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stderr_color_st(const std::string &logger_name, color_mode mode = color_mode::automatic);
+
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "stdout_color_sinks-inl.h"
+#endif
diff --git a/include/spdlog/sinks/stdout_sinks-inl.h b/include/spdlog/sinks/stdout_sinks-inl.h
new file mode 100644
index 00000000..25192607
--- /dev/null
+++ b/include/spdlog/sinks/stdout_sinks-inl.h
@@ -0,0 +1,135 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/stdout_sinks.h>
+#endif
+
+#include <spdlog/details/console_globals.h>
+#include <spdlog/pattern_formatter.h>
+#include <memory>
+
+#ifdef _WIN32
+// under windows using fwrite to non-binary stream results in \r\r\n (see issue #1675)
+// so instead we use ::FileWrite
+#include <spdlog/details/windows_include.h>
+#include <fileapi.h> // WriteFile (..)
+#include <io.h> // _get_osfhandle(..)
+#include <stdio.h> // _fileno(..)
+#endif // WIN32
+
+namespace spdlog {
+
+namespace sinks {
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE stdout_sink_base<ConsoleMutex>::stdout_sink_base(FILE *file)
+ : mutex_(ConsoleMutex::mutex())
+ , file_(file)
+ , formatter_(details::make_unique<spdlog::pattern_formatter>())
+{
+#ifdef _WIN32
+ // get windows handle from the FILE* object
+
+ handle_ = (HANDLE)::_get_osfhandle(::_fileno(file_));
+
+ // don't throw to support cases where no console is attached,
+ // and let the log method to do nothing if (handle_ == INVALID_HANDLE_VALUE).
+ // throw only if non stdout/stderr target is requested (probably regular file and not console).
+ if (handle_ == INVALID_HANDLE_VALUE && file != stdout && file != stderr)
+ {
+ throw_spdlog_ex("spdlog::stdout_sink_base: _get_osfhandle() failed", errno);
+ }
+#endif // WIN32
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::log(const details::log_msg &msg)
+{
+#ifdef _WIN32
+ if (handle_ == INVALID_HANDLE_VALUE)
+ {
+ return;
+ }
+ std::lock_guard<mutex_t> lock(mutex_);
+ memory_buf_t formatted;
+ formatter_->format(msg, formatted);
+ ::fflush(file_); // flush in case there is somthing in this file_ already
+ auto size = static_cast<DWORD>(formatted.size());
+ DWORD bytes_written = 0;
+ bool ok = ::WriteFile(handle_, formatted.data(), size, &bytes_written, nullptr) != 0;
+ if (!ok)
+ {
+ throw_spdlog_ex("stdout_sink_base: WriteFile() failed. GetLastError(): " + std::to_string(::GetLastError()));
+ }
+#else
+ std::lock_guard<mutex_t> lock(mutex_);
+ memory_buf_t formatted;
+ formatter_->format(msg, formatted);
+ ::fwrite(formatted.data(), sizeof(char), formatted.size(), file_);
+ ::fflush(file_); // flush every line to terminal
+#endif // WIN32
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::flush()
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ fflush(file_);
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::set_pattern(const std::string &pattern)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE void stdout_sink_base<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ formatter_ = std::move(sink_formatter);
+}
+
+// stdout sink
+template<typename ConsoleMutex>
+SPDLOG_INLINE stdout_sink<ConsoleMutex>::stdout_sink()
+ : stdout_sink_base<ConsoleMutex>(stdout)
+{}
+
+// stderr sink
+template<typename ConsoleMutex>
+SPDLOG_INLINE stderr_sink<ConsoleMutex>::stderr_sink()
+ : stdout_sink_base<ConsoleMutex>(stderr)
+{}
+
+} // namespace sinks
+
+// factory methods
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stdout_logger_mt(const std::string &logger_name)
+{
+ return Factory::template create<sinks::stdout_sink_mt>(logger_name);
+}
+
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stdout_logger_st(const std::string &logger_name)
+{
+ return Factory::template create<sinks::stdout_sink_st>(logger_name);
+}
+
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stderr_logger_mt(const std::string &logger_name)
+{
+ return Factory::template create<sinks::stderr_sink_mt>(logger_name);
+}
+
+template<typename Factory>
+SPDLOG_INLINE std::shared_ptr<logger> stderr_logger_st(const std::string &logger_name)
+{
+ return Factory::template create<sinks::stderr_sink_st>(logger_name);
+}
+} // namespace spdlog
diff --git a/include/spdlog/sinks/stdout_sinks.h b/include/spdlog/sinks/stdout_sinks.h
new file mode 100644
index 00000000..40688a46
--- /dev/null
+++ b/include/spdlog/sinks/stdout_sinks.h
@@ -0,0 +1,87 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/details/console_globals.h>
+#include <spdlog/details/synchronous_factory.h>
+#include <spdlog/sinks/sink.h>
+#include <cstdio>
+
+#ifdef _WIN32
+#include <spdlog/details/windows_include.h>
+#endif
+
+namespace spdlog {
+
+namespace sinks {
+
+template<typename ConsoleMutex>
+class stdout_sink_base : public sink
+{
+public:
+ using mutex_t = typename ConsoleMutex::mutex_t;
+ explicit stdout_sink_base(FILE *file);
+ ~stdout_sink_base() override = default;
+
+ stdout_sink_base(const stdout_sink_base &other) = delete;
+ stdout_sink_base(stdout_sink_base &&other) = delete;
+
+ stdout_sink_base &operator=(const stdout_sink_base &other) = delete;
+ stdout_sink_base &operator=(stdout_sink_base &&other) = delete;
+
+ void log(const details::log_msg &msg) override;
+ void flush() override;
+ void set_pattern(const std::string &pattern) override;
+
+ void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override;
+
+protected:
+ mutex_t &mutex_;
+ FILE *file_;
+ std::unique_ptr<spdlog::formatter> formatter_;
+#ifdef _WIN32
+ HANDLE handle_;
+#endif // WIN32
+};
+
+template<typename ConsoleMutex>
+class stdout_sink : public stdout_sink_base<ConsoleMutex>
+{
+public:
+ stdout_sink();
+};
+
+template<typename ConsoleMutex>
+class stderr_sink : public stdout_sink_base<ConsoleMutex>
+{
+public:
+ stderr_sink();
+};
+
+using stdout_sink_mt = stdout_sink<details::console_mutex>;
+using stdout_sink_st = stdout_sink<details::console_nullmutex>;
+
+using stderr_sink_mt = stderr_sink<details::console_mutex>;
+using stderr_sink_st = stderr_sink<details::console_nullmutex>;
+
+} // namespace sinks
+
+// factory methods
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stdout_logger_mt(const std::string &logger_name);
+
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stdout_logger_st(const std::string &logger_name);
+
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stderr_logger_mt(const std::string &logger_name);
+
+template<typename Factory = spdlog::synchronous_factory>
+std::shared_ptr<logger> stderr_logger_st(const std::string &logger_name);
+
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "stdout_sinks-inl.h"
+#endif
diff --git a/include/spdlog/sinks/syslog_sink.h b/include/spdlog/sinks/syslog_sink.h
new file mode 100644
index 00000000..7c38fcb5
--- /dev/null
+++ b/include/spdlog/sinks/syslog_sink.h
@@ -0,0 +1,109 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <array>
+#include <string>
+#include <syslog.h>
+
+namespace spdlog {
+namespace sinks {
+/**
+ * Sink that write to syslog using the `syscall()` library call.
+ */
+template<typename Mutex>
+class syslog_sink : public base_sink<Mutex>
+{
+
+public:
+ syslog_sink(std::string ident, int syslog_option, int syslog_facility, bool enable_formatting)
+ : enable_formatting_{enable_formatting}
+ , syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG,
+ /* spdlog::level::debug */ LOG_DEBUG,
+ /* spdlog::level::info */ LOG_INFO,
+ /* spdlog::level::warn */ LOG_WARNING,
+ /* spdlog::level::err */ LOG_ERR,
+ /* spdlog::level::critical */ LOG_CRIT,
+ /* spdlog::level::off */ LOG_INFO}}
+ , ident_{std::move(ident)}
+ {
+ // set ident to be program name if empty
+ ::openlog(ident_.empty() ? nullptr : ident_.c_str(), syslog_option, syslog_facility);
+ }
+
+ ~syslog_sink() override
+ {
+ ::closelog();
+ }
+
+ syslog_sink(const syslog_sink &) = delete;
+ syslog_sink &operator=(const syslog_sink &) = delete;
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ string_view_t payload;
+ memory_buf_t formatted;
+ if (enable_formatting_)
+ {
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ payload = string_view_t(formatted.data(), formatted.size());
+ }
+ else
+ {
+ payload = msg.payload;
+ }
+
+ size_t length = payload.size();
+ // limit to max int
+ if (length > static_cast<size_t>(std::numeric_limits<int>::max()))
+ {
+ length = static_cast<size_t>(std::numeric_limits<int>::max());
+ }
+
+ ::syslog(syslog_prio_from_level(msg), "%.*s", static_cast<int>(length), payload.data());
+ }
+
+ void flush_() override {}
+ bool enable_formatting_ = false;
+
+private:
+ using levels_array = std::array<int, 7>;
+ levels_array syslog_levels_;
+ // must store the ident because the man says openlog might use the pointer as
+ // is and not a string copy
+ const std::string ident_;
+
+ //
+ // Simply maps spdlog's log level to syslog priority level.
+ //
+ int syslog_prio_from_level(const details::log_msg &msg) const
+ {
+ return syslog_levels_.at(static_cast<levels_array::size_type>(msg.level));
+ }
+};
+
+using syslog_sink_mt = syslog_sink<std::mutex>;
+using syslog_sink_st = syslog_sink<details::null_mutex>;
+} // namespace sinks
+
+// Create and register a syslog logger
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> syslog_logger_mt(const std::string &logger_name, const std::string &syslog_ident = "", int syslog_option = 0,
+ int syslog_facility = LOG_USER, bool enable_formatting = false)
+{
+ return Factory::template create<sinks::syslog_sink_mt>(logger_name, syslog_ident, syslog_option, syslog_facility, enable_formatting);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> syslog_logger_st(const std::string &logger_name, const std::string &syslog_ident = "", int syslog_option = 0,
+ int syslog_facility = LOG_USER, bool enable_formatting = false)
+{
+ return Factory::template create<sinks::syslog_sink_st>(logger_name, syslog_ident, syslog_option, syslog_facility, enable_formatting);
+}
+} // namespace spdlog
diff --git a/include/spdlog/sinks/systemd_sink.h b/include/spdlog/sinks/systemd_sink.h
new file mode 100644
index 00000000..d23824b8
--- /dev/null
+++ b/include/spdlog/sinks/systemd_sink.h
@@ -0,0 +1,103 @@
+// Copyright(c) 2019 ZVYAGIN.Alexander@gmail.com
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <array>
+#ifndef SD_JOURNAL_SUPPRESS_LOCATION
+#define SD_JOURNAL_SUPPRESS_LOCATION
+#endif
+#include <systemd/sd-journal.h>
+
+namespace spdlog {
+namespace sinks {
+
+/**
+ * Sink that write to systemd journal using the `sd_journal_send()` library call.
+ *
+ * Locking is not needed, as `sd_journal_send()` itself is thread-safe.
+ */
+template<typename Mutex>
+class systemd_sink : public base_sink<Mutex>
+{
+public:
+ //
+ systemd_sink()
+ : syslog_levels_{{/* spdlog::level::trace */ LOG_DEBUG,
+ /* spdlog::level::debug */ LOG_DEBUG,
+ /* spdlog::level::info */ LOG_INFO,
+ /* spdlog::level::warn */ LOG_WARNING,
+ /* spdlog::level::err */ LOG_ERR,
+ /* spdlog::level::critical */ LOG_CRIT,
+ /* spdlog::level::off */ LOG_INFO}}
+ {}
+
+ ~systemd_sink() override {}
+
+ systemd_sink(const systemd_sink &) = delete;
+ systemd_sink &operator=(const systemd_sink &) = delete;
+
+protected:
+ using levels_array = std::array<int, 7>;
+ levels_array syslog_levels_;
+
+ void sink_it_(const details::log_msg &msg) override
+ {
+ int err;
+
+ size_t length = msg.payload.size();
+ // limit to max int
+ if (length > static_cast<size_t>(std::numeric_limits<int>::max()))
+ {
+ length = static_cast<size_t>(std::numeric_limits<int>::max());
+ }
+
+ // Do not send source location if not available
+ if (msg.source.empty())
+ {
+ // Note: function call inside '()' to avoid macro expansion
+ err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), msg.payload.data(), "PRIORITY=%d", syslog_level(msg.level),
+ "SYSLOG_IDENTIFIER=%.*s", static_cast<int>(msg.logger_name.size()), msg.logger_name.data(), nullptr);
+ }
+ else
+ {
+ err = (sd_journal_send)("MESSAGE=%.*s", static_cast<int>(length), msg.payload.data(), "PRIORITY=%d", syslog_level(msg.level),
+ "SYSLOG_IDENTIFIER=%.*s", static_cast<int>(msg.logger_name.size()), msg.logger_name.data(), "CODE_FILE=%s",
+ msg.source.filename, "CODE_LINE=%d", msg.source.line, "CODE_FUNC=%s", msg.source.funcname, nullptr);
+ }
+
+ if (err)
+ {
+ throw_spdlog_ex("Failed writing to systemd", errno);
+ }
+ }
+
+ int syslog_level(level::level_enum l)
+ {
+ return syslog_levels_.at(static_cast<levels_array::size_type>(l));
+ }
+
+ void flush_() override {}
+};
+
+using systemd_sink_mt = systemd_sink<std::mutex>;
+using systemd_sink_st = systemd_sink<details::null_mutex>;
+} // namespace sinks
+
+// Create and register a syslog logger
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> systemd_logger_mt(const std::string &logger_name)
+{
+ return Factory::template create<sinks::systemd_sink_mt>(logger_name);
+}
+
+template<typename Factory = spdlog::synchronous_factory>
+inline std::shared_ptr<logger> systemd_logger_st(const std::string &logger_name)
+{
+ return Factory::template create<sinks::systemd_sink_st>(logger_name);
+}
+} // namespace spdlog
diff --git a/include/spdlog/sinks/tcp_sink.h b/include/spdlog/sinks/tcp_sink.h
new file mode 100644
index 00000000..9dd9e51d
--- /dev/null
+++ b/include/spdlog/sinks/tcp_sink.h
@@ -0,0 +1,81 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <spdlog/sinks/base_sink.h>
+#include <spdlog/details/null_mutex.h>
+#ifdef _WIN32
+#include <spdlog/details/tcp_client-windows.h>
+#else
+#include <spdlog/details/tcp_client.h>
+#endif
+
+#include <mutex>
+#include <string>
+#include <chrono>
+#include <functional>
+
+#pragma once
+
+// Simple tcp client sink
+// Connects to remote address and send the formatted log.
+// Will attempt to reconnect if connection drops.
+// If more complicated behaviour is needed (i.e get responses), you can inherit it and override the sink_it_ method.
+
+namespace spdlog {
+namespace sinks {
+
+struct tcp_sink_config
+{
+ std::string server_host;
+ int server_port;
+ bool lazy_connect = false; // if true connect on first log call instead of on construction
+
+ tcp_sink_config(std::string host, int port)
+ : server_host{std::move(host)}
+ , server_port{port}
+ {}
+};
+
+template<typename Mutex>
+class tcp_sink : public spdlog::sinks::base_sink<Mutex>
+{
+public:
+ // connect to tcp host/port or throw if failed
+ // host can be hostname or ip address
+
+ explicit tcp_sink(tcp_sink_config sink_config)
+ : config_{std::move(sink_config)}
+ {
+ if (!config_.lazy_connect)
+ {
+ this->client_.connect(config_.server_host, config_.server_port);
+ }
+ }
+
+ ~tcp_sink() override = default;
+
+protected:
+ void sink_it_(const spdlog::details::log_msg &msg) override
+ {
+ spdlog::memory_buf_t formatted;
+ spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
+ if (!client_.is_connected())
+ {
+ client_.connect(config_.server_host, config_.server_port);
+ }
+ client_.send(formatted.data(), formatted.size());
+ }
+
+ void flush_() override {}
+ tcp_sink_config config_;
+ details::tcp_client client_;
+};
+
+using tcp_sink_mt = tcp_sink<std::mutex>;
+using tcp_sink_st = tcp_sink<spdlog::details::null_mutex>;
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/win_eventlog_sink.h b/include/spdlog/sinks/win_eventlog_sink.h
new file mode 100644
index 00000000..68170dd9
--- /dev/null
+++ b/include/spdlog/sinks/win_eventlog_sink.h
@@ -0,0 +1,276 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+// Writing to Windows Event Log requires the registry entries below to be present, with the following modifications:
+// 1. <log_name> should be replaced with your log name (e.g. your application name)
+// 2. <source_name> should be replaced with the specific source name and the key should be duplicated for
+// each source used in the application
+//
+// Since typically modifications of this kind require elevation, it's better to do it as a part of setup procedure.
+// The snippet below uses mscoree.dll as the message file as it exists on most of the Windows systems anyway and
+// happens to contain the needed resource.
+//
+// You can also specify a custom message file if needed.
+// Please refer to Event Log functions descriptions in MSDN for more details on custom message files.
+
+/*---------------------------------------------------------------------------------------
+
+Windows Registry Editor Version 5.00
+
+[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\<log_name>]
+
+[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\EventLog\<log_name>\<source_name>]
+"TypesSupported"=dword:00000007
+"EventMessageFile"=hex(2):25,00,73,00,79,00,73,00,74,00,65,00,6d,00,72,00,6f,\
+ 00,6f,00,74,00,25,00,5c,00,53,00,79,00,73,00,74,00,65,00,6d,00,33,00,32,00,\
+ 5c,00,6d,00,73,00,63,00,6f,00,72,00,65,00,65,00,2e,00,64,00,6c,00,6c,00,00,\
+ 00
+
+-----------------------------------------------------------------------------------------*/
+
+#pragma once
+
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/sinks/base_sink.h>
+
+#include <spdlog/details/windows_include.h>
+#include <winbase.h>
+
+#include <mutex>
+#include <string>
+#include <vector>
+
+namespace spdlog {
+namespace sinks {
+
+namespace win_eventlog {
+
+namespace internal {
+
+/** Windows error */
+struct win32_error : public spdlog_ex
+{
+ /** Formats an error report line: "user-message: error-code (system message)" */
+ static std::string format(std::string const &user_message, DWORD error_code = GetLastError())
+ {
+ std::string system_message;
+
+ LPSTR format_message_result{};
+ auto format_message_succeeded =
+ ::FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
+ error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&format_message_result, 0, nullptr);
+
+ if (format_message_succeeded && format_message_result)
+ {
+ system_message = fmt::format(" ({})", format_message_result);
+ }
+
+ if (format_message_result)
+ {
+ LocalFree((HLOCAL)format_message_result);
+ }
+
+ return fmt::format("{}: {}{}", user_message, error_code, system_message);
+ }
+
+ explicit win32_error(std::string const &func_name, DWORD error = GetLastError())
+ : spdlog_ex(format(func_name, error))
+ {}
+};
+
+/** Wrapper for security identifiers (SID) on Windows */
+struct sid_t
+{
+ std::vector<char> buffer_;
+
+public:
+ sid_t() {}
+
+ /** creates a wrapped SID copy */
+ static sid_t duplicate_sid(PSID psid)
+ {
+ if (!::IsValidSid(psid))
+ {
+ throw_spdlog_ex("sid_t::sid_t(): invalid SID received");
+ }
+
+ auto const sid_length{::GetLengthSid(psid)};
+
+ sid_t result;
+ result.buffer_.resize(sid_length);
+ if (!::CopySid(sid_length, (PSID)result.as_sid(), psid))
+ {
+ SPDLOG_THROW(win32_error("CopySid"));
+ }
+
+ return result;
+ }
+
+ /** Retrieves pointer to the internal buffer contents as SID* */
+ SID *as_sid() const
+ {
+ return buffer_.empty() ? nullptr : (SID *)buffer_.data();
+ }
+
+ /** Get SID for the current user */
+ static sid_t get_current_user_sid()
+ {
+ /* create and init RAII holder for process token */
+ struct process_token_t
+ {
+ HANDLE token_handle_ = INVALID_HANDLE_VALUE;
+ explicit process_token_t(HANDLE process)
+ {
+ if (!::OpenProcessToken(process, TOKEN_QUERY, &token_handle_))
+ {
+ SPDLOG_THROW(win32_error("OpenProcessToken"));
+ }
+ }
+
+ ~process_token_t()
+ {
+ ::CloseHandle(token_handle_);
+ }
+
+ } current_process_token(::GetCurrentProcess()); // GetCurrentProcess returns pseudohandle, no leak here!
+
+ // Get the required size, this is expected to fail with ERROR_INSUFFICIENT_BUFFER and return the token size
+ DWORD tusize = 0;
+ if (::GetTokenInformation(current_process_token.token_handle_, TokenUser, NULL, 0, &tusize))
+ {
+ SPDLOG_THROW(win32_error("GetTokenInformation should fail"));
+ }
+
+ // get user token
+ std::vector<unsigned char> buffer(static_cast<size_t>(tusize));
+ if (!::GetTokenInformation(current_process_token.token_handle_, TokenUser, (LPVOID)buffer.data(), tusize, &tusize))
+ {
+ SPDLOG_THROW(win32_error("GetTokenInformation"));
+ }
+
+ // create a wrapper of the SID data as stored in the user token
+ return sid_t::duplicate_sid(((TOKEN_USER *)buffer.data())->User.Sid);
+ }
+};
+
+struct eventlog
+{
+ static WORD get_event_type(details::log_msg const &msg)
+ {
+ switch (msg.level)
+ {
+ case level::trace:
+ case level::debug:
+ return EVENTLOG_SUCCESS;
+
+ case level::info:
+ return EVENTLOG_INFORMATION_TYPE;
+
+ case level::warn:
+ return EVENTLOG_WARNING_TYPE;
+
+ case level::err:
+ case level::critical:
+ case level::off:
+ return EVENTLOG_ERROR_TYPE;
+
+ default:
+ return EVENTLOG_INFORMATION_TYPE;
+ }
+ }
+
+ static WORD get_event_category(details::log_msg const &msg)
+ {
+ return (WORD)msg.level;
+ }
+};
+
+} // namespace internal
+
+/*
+ * Windows Event Log sink
+ */
+template<typename Mutex>
+class win_eventlog_sink : public base_sink<Mutex>
+{
+private:
+ HANDLE hEventLog_{NULL};
+ internal::sid_t current_user_sid_;
+ std::string source_;
+ WORD event_id_;
+
+ HANDLE event_log_handle()
+ {
+ if (!hEventLog_)
+ {
+ hEventLog_ = ::RegisterEventSourceA(nullptr, source_.c_str());
+ if (!hEventLog_ || hEventLog_ == (HANDLE)ERROR_ACCESS_DENIED)
+ {
+ SPDLOG_THROW(internal::win32_error("RegisterEventSource"));
+ }
+ }
+
+ return hEventLog_;
+ }
+
+protected:
+ void sink_it_(const details::log_msg &msg) override
+ {
+ using namespace internal;
+
+ bool succeeded;
+ memory_buf_t formatted;
+ base_sink<Mutex>::formatter_->format(msg, formatted);
+ formatted.push_back('\0');
+
+#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
+ wmemory_buf_t buf;
+ details::os::utf8_to_wstrbuf(string_view_t(formatted.data(), formatted.size()), buf);
+
+ LPCWSTR lp_wstr = buf.data();
+ succeeded = ::ReportEventW(event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg), event_id_,
+ current_user_sid_.as_sid(), 1, 0, &lp_wstr, nullptr);
+#else
+ LPCSTR lp_str = formatted.data();
+ succeeded = ::ReportEventA(event_log_handle(), eventlog::get_event_type(msg), eventlog::get_event_category(msg), event_id_,
+ current_user_sid_.as_sid(), 1, 0, &lp_str, nullptr);
+#endif
+
+ if (!succeeded)
+ {
+ SPDLOG_THROW(win32_error("ReportEvent"));
+ }
+ }
+
+ void flush_() override {}
+
+public:
+ win_eventlog_sink(std::string const &source, WORD event_id = 1000 /* according to mscoree.dll */)
+ : source_(source)
+ , event_id_(event_id)
+ {
+ try
+ {
+ current_user_sid_ = internal::sid_t::get_current_user_sid();
+ }
+ catch (...)
+ {
+ // get_current_user_sid() is unlikely to fail and if it does, we can still proceed without
+ // current_user_sid but in the event log the record will have no user name
+ }
+ }
+
+ ~win_eventlog_sink()
+ {
+ if (hEventLog_)
+ DeregisterEventSource(hEventLog_);
+ }
+};
+
+} // namespace win_eventlog
+
+using win_eventlog_sink_mt = win_eventlog::win_eventlog_sink<std::mutex>;
+using win_eventlog_sink_st = win_eventlog::win_eventlog_sink<details::null_mutex>;
+
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/wincolor_sink-inl.h b/include/spdlog/sinks/wincolor_sink-inl.h
new file mode 100644
index 00000000..e2676d3c
--- /dev/null
+++ b/include/spdlog/sinks/wincolor_sink-inl.h
@@ -0,0 +1,175 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/sinks/wincolor_sink.h>
+#endif
+
+#include <spdlog/details/windows_include.h>
+#include <wincon.h>
+
+#include <spdlog/common.h>
+#include <spdlog/pattern_formatter.h>
+
+namespace spdlog {
+namespace sinks {
+template<typename ConsoleMutex>
+SPDLOG_INLINE wincolor_sink<ConsoleMutex>::wincolor_sink(void *out_handle, color_mode mode)
+ : out_handle_(out_handle)
+ , mutex_(ConsoleMutex::mutex())
+ , formatter_(details::make_unique<spdlog::pattern_formatter>())
+{
+
+ set_color_mode_impl(mode);
+ // set level colors
+ colors_[level::trace] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE; // white
+ colors_[level::debug] = FOREGROUND_GREEN | FOREGROUND_BLUE; // cyan
+ colors_[level::info] = FOREGROUND_GREEN; // green
+ colors_[level::warn] = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; // intense yellow
+ colors_[level::err] = FOREGROUND_RED | FOREGROUND_INTENSITY; // intense red
+ colors_[level::critical] =
+ BACKGROUND_RED | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; // intense white on red background
+ colors_[level::off] = 0;
+}
+
+template<typename ConsoleMutex>
+SPDLOG_INLINE wincolor_sink<ConsoleMutex>::~wincolor_sink()
+{
+ this->flush();
+}
+
+// change the color for the given level
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color(level::level_enum level, std::uint16_t color)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ colors_[level] = color;
+}
+
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::log(const details::log_msg &msg)
+{
+ if (out_handle_ == nullptr || out_handle_ == INVALID_HANDLE_VALUE)
+ {
+ return;
+ }
+
+ std::lock_guard<mutex_t> lock(mutex_);
+ msg.color_range_start = 0;
+ msg.color_range_end = 0;
+ memory_buf_t formatted;
+ formatter_->format(msg, formatted);
+ if (should_do_colors_ && msg.color_range_end > msg.color_range_start)
+ {
+ // before color range
+ print_range_(formatted, 0, msg.color_range_start);
+ // in color range
+ auto orig_attribs = static_cast<WORD>(set_foreground_color_(colors_[msg.level]));
+ print_range_(formatted, msg.color_range_start, msg.color_range_end);
+ // reset to orig colors
+ ::SetConsoleTextAttribute(static_cast<HANDLE>(out_handle_), orig_attribs);
+ print_range_(formatted, msg.color_range_end, formatted.size());
+ }
+ else // print without colors if color range is invalid (or color is disabled)
+ {
+ write_to_file_(formatted);
+ }
+}
+
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::flush()
+{
+ // windows console always flushed?
+}
+
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_pattern(const std::string &pattern)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ formatter_ = std::unique_ptr<spdlog::formatter>(new pattern_formatter(pattern));
+}
+
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ formatter_ = std::move(sink_formatter);
+}
+
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color_mode(color_mode mode)
+{
+ std::lock_guard<mutex_t> lock(mutex_);
+ set_color_mode_impl(mode);
+}
+
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_color_mode_impl(color_mode mode)
+{
+ if (mode == color_mode::automatic)
+ {
+ // should do colors only if out_handle_ points to actual console.
+ DWORD console_mode;
+ bool in_console = ::GetConsoleMode(static_cast<HANDLE>(out_handle_), &console_mode) != 0;
+ should_do_colors_ = in_console;
+ }
+ else
+ {
+ should_do_colors_ = mode == color_mode::always ? true : false;
+ }
+}
+
+// set foreground color and return the orig console attributes (for resetting later)
+template<typename ConsoleMutex>
+std::uint16_t SPDLOG_INLINE wincolor_sink<ConsoleMutex>::set_foreground_color_(std::uint16_t attribs)
+{
+ CONSOLE_SCREEN_BUFFER_INFO orig_buffer_info;
+ if (!::GetConsoleScreenBufferInfo(static_cast<HANDLE>(out_handle_), &orig_buffer_info))
+ {
+ // just return white if failed getting console info
+ return FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE;
+ }
+
+ // change only the foreground bits (lowest 4 bits)
+ auto new_attribs = static_cast<WORD>(attribs) | (orig_buffer_info.wAttributes & 0xfff0);
+ auto ignored = ::SetConsoleTextAttribute(static_cast<HANDLE>(out_handle_), static_cast<WORD>(new_attribs));
+ (void)(ignored);
+ return static_cast<std::uint16_t>(orig_buffer_info.wAttributes); // return orig attribs
+}
+
+// print a range of formatted message to console
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::print_range_(const memory_buf_t &formatted, size_t start, size_t end)
+{
+ if (end > start)
+ {
+ auto size = static_cast<DWORD>(end - start);
+ auto ignored = ::WriteConsoleA(static_cast<HANDLE>(out_handle_), formatted.data() + start, size, nullptr, nullptr);
+ (void)(ignored);
+ }
+}
+
+template<typename ConsoleMutex>
+void SPDLOG_INLINE wincolor_sink<ConsoleMutex>::write_to_file_(const memory_buf_t &formatted)
+{
+ auto size = static_cast<DWORD>(formatted.size());
+ DWORD bytes_written = 0;
+ auto ignored = ::WriteFile(static_cast<HANDLE>(out_handle_), formatted.data(), size, &bytes_written, nullptr);
+ (void)(ignored);
+}
+
+// wincolor_stdout_sink
+template<typename ConsoleMutex>
+SPDLOG_INLINE wincolor_stdout_sink<ConsoleMutex>::wincolor_stdout_sink(color_mode mode)
+ : wincolor_sink<ConsoleMutex>(::GetStdHandle(STD_OUTPUT_HANDLE), mode)
+{}
+
+// wincolor_stderr_sink
+template<typename ConsoleMutex>
+SPDLOG_INLINE wincolor_stderr_sink<ConsoleMutex>::wincolor_stderr_sink(color_mode mode)
+ : wincolor_sink<ConsoleMutex>(::GetStdHandle(STD_ERROR_HANDLE), mode)
+{}
+} // namespace sinks
+} // namespace spdlog
diff --git a/include/spdlog/sinks/wincolor_sink.h b/include/spdlog/sinks/wincolor_sink.h
new file mode 100644
index 00000000..a82f1b24
--- /dev/null
+++ b/include/spdlog/sinks/wincolor_sink.h
@@ -0,0 +1,85 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <spdlog/details/console_globals.h>
+#include <spdlog/details/null_mutex.h>
+#include <spdlog/sinks/sink.h>
+
+#include <memory>
+#include <mutex>
+#include <string>
+#include <array>
+#include <cstdint>
+
+namespace spdlog {
+namespace sinks {
+/*
+ * Windows color console sink. Uses WriteConsoleA to write to the console with
+ * colors
+ */
+template<typename ConsoleMutex>
+class wincolor_sink : public sink
+{
+public:
+ wincolor_sink(void *out_handle, color_mode mode);
+ ~wincolor_sink() override;
+
+ wincolor_sink(const wincolor_sink &other) = delete;
+ wincolor_sink &operator=(const wincolor_sink &other) = delete;
+
+ // change the color for the given level
+ void set_color(level::level_enum level, std::uint16_t color);
+ void log(const details::log_msg &msg) final override;
+ void flush() final override;
+ void set_pattern(const std::string &pattern) override final;
+ void set_formatter(std::unique_ptr<spdlog::formatter> sink_formatter) override final;
+ void set_color_mode(color_mode mode);
+
+protected:
+ using mutex_t = typename ConsoleMutex::mutex_t;
+ void *out_handle_;
+ mutex_t &mutex_;
+ bool should_do_colors_;
+ std::unique_ptr<spdlog::formatter> formatter_;
+ std::array<std::uint16_t, level::n_levels> colors_;
+
+ // set foreground color and return the orig console attributes (for resetting later)
+ std::uint16_t set_foreground_color_(std::uint16_t attribs);
+
+ // print a range of formatted message to console
+ void print_range_(const memory_buf_t &formatted, size_t start, size_t end);
+
+ // in case we are redirected to file (not in console mode)
+ void write_to_file_(const memory_buf_t &formatted);
+
+ void set_color_mode_impl(color_mode mode);
+};
+
+template<typename ConsoleMutex>
+class wincolor_stdout_sink : public wincolor_sink<ConsoleMutex>
+{
+public:
+ explicit wincolor_stdout_sink(color_mode mode = color_mode::automatic);
+};
+
+template<typename ConsoleMutex>
+class wincolor_stderr_sink : public wincolor_sink<ConsoleMutex>
+{
+public:
+ explicit wincolor_stderr_sink(color_mode mode = color_mode::automatic);
+};
+
+using wincolor_stdout_sink_mt = wincolor_stdout_sink<details::console_mutex>;
+using wincolor_stdout_sink_st = wincolor_stdout_sink<details::console_nullmutex>;
+
+using wincolor_stderr_sink_mt = wincolor_stderr_sink<details::console_mutex>;
+using wincolor_stderr_sink_st = wincolor_stderr_sink<details::console_nullmutex>;
+} // namespace sinks
+} // namespace spdlog
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "wincolor_sink-inl.h"
+#endif
diff --git a/include/spdlog/spdlog-inl.h b/include/spdlog/spdlog-inl.h
new file mode 100644
index 00000000..96e09f59
--- /dev/null
+++ b/include/spdlog/spdlog-inl.h
@@ -0,0 +1,125 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#ifndef SPDLOG_HEADER_ONLY
+#include <spdlog/spdlog.h>
+#endif
+
+#include <spdlog/common.h>
+#include <spdlog/pattern_formatter.h>
+
+namespace spdlog {
+
+SPDLOG_INLINE void initialize_logger(std::shared_ptr<logger> logger)
+{
+ details::registry::instance().initialize_logger(std::move(logger));
+}
+
+SPDLOG_INLINE std::shared_ptr<logger> get(const std::string &name)
+{
+ return details::registry::instance().get(name);
+}
+
+SPDLOG_INLINE void set_formatter(std::unique_ptr<spdlog::formatter> formatter)
+{
+ details::registry::instance().set_formatter(std::move(formatter));
+}
+
+SPDLOG_INLINE void set_pattern(std::string pattern, pattern_time_type time_type)
+{
+ set_formatter(std::unique_ptr<spdlog::formatter>(new pattern_formatter(std::move(pattern), time_type)));
+}
+
+SPDLOG_INLINE void enable_backtrace(size_t n_messages)
+{
+ details::registry::instance().enable_backtrace(n_messages);
+}
+
+SPDLOG_INLINE void disable_backtrace()
+{
+ details::registry::instance().disable_backtrace();
+}
+
+SPDLOG_INLINE void dump_backtrace()
+{
+ default_logger_raw()->dump_backtrace();
+}
+
+SPDLOG_INLINE level::level_enum get_level()
+{
+ return default_logger_raw()->level();
+}
+
+SPDLOG_INLINE bool should_log(level::level_enum log_level)
+{
+ return default_logger_raw()->should_log(log_level);
+}
+
+SPDLOG_INLINE void set_level(level::level_enum log_level)
+{
+ details::registry::instance().set_level(log_level);
+}
+
+SPDLOG_INLINE void flush_on(level::level_enum log_level)
+{
+ details::registry::instance().flush_on(log_level);
+}
+
+SPDLOG_INLINE void flush_every(std::chrono::seconds interval)
+{
+ details::registry::instance().flush_every(interval);
+}
+
+SPDLOG_INLINE void set_error_handler(void (*handler)(const std::string &msg))
+{
+ details::registry::instance().set_error_handler(handler);
+}
+
+SPDLOG_INLINE void register_logger(std::shared_ptr<logger> logger)
+{
+ details::registry::instance().register_logger(std::move(logger));
+}
+
+SPDLOG_INLINE void apply_all(const std::function<void(std::shared_ptr<logger>)> &fun)
+{
+ details::registry::instance().apply_all(fun);
+}
+
+SPDLOG_INLINE void drop(const std::string &name)
+{
+ details::registry::instance().drop(name);
+}
+
+SPDLOG_INLINE void drop_all()
+{
+ details::registry::instance().drop_all();
+}
+
+SPDLOG_INLINE void shutdown()
+{
+ details::registry::instance().shutdown();
+}
+
+SPDLOG_INLINE void set_automatic_registration(bool automatic_registration)
+{
+ details::registry::instance().set_automatic_registration(automatic_registration);
+}
+
+SPDLOG_INLINE std::shared_ptr<spdlog::logger> default_logger()
+{
+ return details::registry::instance().default_logger();
+}
+
+SPDLOG_INLINE spdlog::logger *default_logger_raw()
+{
+ return details::registry::instance().get_default_raw();
+}
+
+SPDLOG_INLINE void set_default_logger(std::shared_ptr<spdlog::logger> default_logger)
+{
+ details::registry::instance().set_default_logger(std::move(default_logger));
+}
+
+} // namespace spdlog
diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h
new file mode 100644
index 00000000..bb130d94
--- /dev/null
+++ b/include/spdlog/spdlog.h
@@ -0,0 +1,295 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+// spdlog main header file.
+// see example.cpp for usage example
+
+#ifndef SPDLOG_H
+#define SPDLOG_H
+
+#pragma once
+
+#include <spdlog/common.h>
+#include <spdlog/details/registry.h>
+#include <spdlog/logger.h>
+#include <spdlog/version.h>
+#include <spdlog/details/synchronous_factory.h>
+
+#include <chrono>
+#include <functional>
+#include <memory>
+#include <string>
+
+namespace spdlog {
+
+using default_factory = synchronous_factory;
+
+// Create and register a logger with a templated sink type
+// The logger's level, formatter and flush level will be set according the
+// global settings.
+//
+// Example:
+// spdlog::create<daily_file_sink_st>("logger_name", "dailylog_filename", 11, 59);
+template<typename Sink, typename... SinkArgs>
+inline std::shared_ptr<spdlog::logger> create(std::string logger_name, SinkArgs &&...sink_args)
+{
+ return default_factory::create<Sink>(std::move(logger_name), std::forward<SinkArgs>(sink_args)...);
+}
+
+// Initialize and register a logger,
+// formatter and flush level will be set according the global settings.
+//
+// Useful for initializing manually created loggers with the global settings.
+//
+// Example:
+// auto mylogger = std::make_shared<spdlog::logger>("mylogger", ...);
+// spdlog::initialize_logger(mylogger);
+SPDLOG_API void initialize_logger(std::shared_ptr<logger> logger);
+
+// Return an existing logger or nullptr if a logger with such name doesn't
+// exist.
+// example: spdlog::get("my_logger")->info("hello {}", "world");
+SPDLOG_API std::shared_ptr<logger> get(const std::string &name);
+
+// Set global formatter. Each sink in each logger will get a clone of this object
+SPDLOG_API void set_formatter(std::unique_ptr<spdlog::formatter> formatter);
+
+// Set global format string.
+// example: spdlog::set_pattern("%Y-%m-%d %H:%M:%S.%e %l : %v");
+SPDLOG_API void set_pattern(std::string pattern, pattern_time_type time_type = pattern_time_type::local);
+
+// enable global backtrace support
+SPDLOG_API void enable_backtrace(size_t n_messages);
+
+// disable global backtrace support
+SPDLOG_API void disable_backtrace();
+
+// call dump backtrace on default logger
+SPDLOG_API void dump_backtrace();
+
+// Get global logging level
+SPDLOG_API level::level_enum get_level();
+
+// Set global logging level
+SPDLOG_API void set_level(level::level_enum log_level);
+
+// Determine whether the default logger should log messages with a certain level
+SPDLOG_API bool should_log(level::level_enum lvl);
+
+// Set global flush level
+SPDLOG_API void flush_on(level::level_enum log_level);
+
+// Start/Restart a periodic flusher thread
+// Warning: Use only if all your loggers are thread safe!
+SPDLOG_API void flush_every(std::chrono::seconds interval);
+
+// Set global error handler
+SPDLOG_API void set_error_handler(void (*handler)(const std::string &msg));
+
+// Register the given logger with the given name
+SPDLOG_API void register_logger(std::shared_ptr<logger> logger);
+
+// Apply a user defined function on all registered loggers
+// Example:
+// spdlog::apply_all([&](std::shared_ptr<spdlog::logger> l) {l->flush();});
+SPDLOG_API void apply_all(const std::function<void(std::shared_ptr<logger>)> &fun);
+
+// Drop the reference to the given logger
+SPDLOG_API void drop(const std::string &name);
+
+// Drop all references from the registry
+SPDLOG_API void drop_all();
+
+// stop any running threads started by spdlog and clean registry loggers
+SPDLOG_API void shutdown();
+
+// Automatic registration of loggers when using spdlog::create() or spdlog::create_async
+SPDLOG_API void set_automatic_registration(bool automatic_registration);
+
+// API for using default logger (stdout_color_mt),
+// e.g: spdlog::info("Message {}", 1);
+//
+// The default logger object can be accessed using the spdlog::default_logger():
+// For example, to add another sink to it:
+// spdlog::default_logger()->sinks().push_back(some_sink);
+//
+// The default logger can replaced using spdlog::set_default_logger(new_logger).
+// For example, to replace it with a file logger.
+//
+// IMPORTANT:
+// The default API is thread safe (for _mt loggers), but:
+// set_default_logger() *should not* be used concurrently with the default API.
+// e.g do not call set_default_logger() from one thread while calling spdlog::info() from another.
+
+SPDLOG_API std::shared_ptr<spdlog::logger> default_logger();
+
+SPDLOG_API spdlog::logger *default_logger_raw();
+
+SPDLOG_API void set_default_logger(std::shared_ptr<spdlog::logger> default_logger);
+
+template<typename FormatString, typename... Args>
+inline void log(source_loc source, level::level_enum lvl, const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->log(source, lvl, fmt, std::forward<Args>(args)...);
+}
+
+template<typename FormatString, typename... Args>
+inline void log(level::level_enum lvl, const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->log(source_loc{}, lvl, fmt, std::forward<Args>(args)...);
+}
+
+template<typename FormatString, typename... Args>
+inline void trace(const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->trace(fmt, std::forward<Args>(args)...);
+}
+
+template<typename FormatString, typename... Args>
+inline void debug(const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->debug(fmt, std::forward<Args>(args)...);
+}
+
+template<typename FormatString, typename... Args>
+inline void info(const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->info(fmt, std::forward<Args>(args)...);
+}
+
+template<typename FormatString, typename... Args>
+inline void warn(const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->warn(fmt, std::forward<Args>(args)...);
+}
+
+template<typename FormatString, typename... Args>
+inline void error(const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->error(fmt, std::forward<Args>(args)...);
+}
+
+template<typename FormatString, typename... Args>
+inline void critical(const FormatString &fmt, Args&&...args)
+{
+ default_logger_raw()->critical(fmt, std::forward<Args>(args)...);
+}
+
+template<typename T>
+inline void log(source_loc source, level::level_enum lvl, const T &msg)
+{
+ default_logger_raw()->log(source, lvl, msg);
+}
+
+template<typename T>
+inline void log(level::level_enum lvl, const T &msg)
+{
+ default_logger_raw()->log(lvl, msg);
+}
+
+template<typename T>
+inline void trace(const T &msg)
+{
+ default_logger_raw()->trace(msg);
+}
+
+template<typename T>
+inline void debug(const T &msg)
+{
+ default_logger_raw()->debug(msg);
+}
+
+template<typename T>
+inline void info(const T &msg)
+{
+ default_logger_raw()->info(msg);
+}
+
+template<typename T>
+inline void warn(const T &msg)
+{
+ default_logger_raw()->warn(msg);
+}
+
+template<typename T>
+inline void error(const T &msg)
+{
+ default_logger_raw()->error(msg);
+}
+
+template<typename T>
+inline void critical(const T &msg)
+{
+ default_logger_raw()->critical(msg);
+}
+
+} // namespace spdlog
+
+//
+// enable/disable log calls at compile time according to global level.
+//
+// define SPDLOG_ACTIVE_LEVEL to one of those (before including spdlog.h):
+// SPDLOG_LEVEL_TRACE,
+// SPDLOG_LEVEL_DEBUG,
+// SPDLOG_LEVEL_INFO,
+// SPDLOG_LEVEL_WARN,
+// SPDLOG_LEVEL_ERROR,
+// SPDLOG_LEVEL_CRITICAL,
+// SPDLOG_LEVEL_OFF
+//
+
+#define SPDLOG_LOGGER_CALL(logger, level, ...) (logger)->log(spdlog::source_loc{__FILE__, __LINE__, SPDLOG_FUNCTION}, level, __VA_ARGS__)
+
+#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_TRACE
+#define SPDLOG_LOGGER_TRACE(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::trace, __VA_ARGS__)
+#define SPDLOG_TRACE(...) SPDLOG_LOGGER_TRACE(spdlog::default_logger_raw(), __VA_ARGS__)
+#else
+#define SPDLOG_LOGGER_TRACE(logger, ...) (void)0
+#define SPDLOG_TRACE(...) (void)0
+#endif
+
+#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_DEBUG
+#define SPDLOG_LOGGER_DEBUG(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::debug, __VA_ARGS__)
+#define SPDLOG_DEBUG(...) SPDLOG_LOGGER_DEBUG(spdlog::default_logger_raw(), __VA_ARGS__)
+#else
+#define SPDLOG_LOGGER_DEBUG(logger, ...) (void)0
+#define SPDLOG_DEBUG(...) (void)0
+#endif
+
+#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_INFO
+#define SPDLOG_LOGGER_INFO(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::info, __VA_ARGS__)
+#define SPDLOG_INFO(...) SPDLOG_LOGGER_INFO(spdlog::default_logger_raw(), __VA_ARGS__)
+#else
+#define SPDLOG_LOGGER_INFO(logger, ...) (void)0
+#define SPDLOG_INFO(...) (void)0
+#endif
+
+#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_WARN
+#define SPDLOG_LOGGER_WARN(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::warn, __VA_ARGS__)
+#define SPDLOG_WARN(...) SPDLOG_LOGGER_WARN(spdlog::default_logger_raw(), __VA_ARGS__)
+#else
+#define SPDLOG_LOGGER_WARN(logger, ...) (void)0
+#define SPDLOG_WARN(...) (void)0
+#endif
+
+#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_ERROR
+#define SPDLOG_LOGGER_ERROR(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::err, __VA_ARGS__)
+#define SPDLOG_ERROR(...) SPDLOG_LOGGER_ERROR(spdlog::default_logger_raw(), __VA_ARGS__)
+#else
+#define SPDLOG_LOGGER_ERROR(logger, ...) (void)0
+#define SPDLOG_ERROR(...) (void)0
+#endif
+
+#if SPDLOG_ACTIVE_LEVEL <= SPDLOG_LEVEL_CRITICAL
+#define SPDLOG_LOGGER_CRITICAL(logger, ...) SPDLOG_LOGGER_CALL(logger, spdlog::level::critical, __VA_ARGS__)
+#define SPDLOG_CRITICAL(...) SPDLOG_LOGGER_CRITICAL(spdlog::default_logger_raw(), __VA_ARGS__)
+#else
+#define SPDLOG_LOGGER_CRITICAL(logger, ...) (void)0
+#define SPDLOG_CRITICAL(...) (void)0
+#endif
+
+#ifdef SPDLOG_HEADER_ONLY
+#include "spdlog-inl.h"
+#endif
+
+#endif // SPDLOG_H
diff --git a/include/spdlog/stopwatch.h b/include/spdlog/stopwatch.h
new file mode 100644
index 00000000..bb976b19
--- /dev/null
+++ b/include/spdlog/stopwatch.h
@@ -0,0 +1,61 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#include <spdlog/fmt/fmt.h>
+
+// Stopwatch support for spdlog (using std::chrono::steady_clock).
+// Displays elapsed seconds since construction as double.
+//
+// Usage:
+//
+// spdlog::stopwatch sw;
+// ...
+// spdlog::debug("Elapsed: {} seconds", sw); => "Elapsed 0.005116733 seconds"
+// spdlog::info("Elapsed: {:.6} seconds", sw); => "Elapsed 0.005163 seconds"
+//
+//
+// If other units are needed (e.g. millis instead of double), include "fmt/chrono.h" and use "duration_cast<..>(sw.elapsed())":
+//
+// #include <spdlog/fmt/chrono.h>
+//..
+// using std::chrono::duration_cast;
+// using std::chrono::milliseconds;
+// spdlog::info("Elapsed {}", duration_cast<milliseconds>(sw.elapsed())); => "Elapsed 5ms"
+
+namespace spdlog {
+class stopwatch
+{
+ using clock = std::chrono::steady_clock;
+ std::chrono::time_point<clock> start_tp_;
+
+public:
+ stopwatch()
+ : start_tp_{clock::now()}
+ {}
+
+ std::chrono::duration<double> elapsed() const
+ {
+ return std::chrono::duration<double>(clock::now() - start_tp_);
+ }
+
+ void reset()
+ {
+ start_tp_ = clock ::now();
+ }
+};
+} // namespace spdlog
+
+// Support for fmt formatting (e.g. "{:012.9}" or just "{}")
+namespace fmt {
+template<>
+struct formatter<spdlog::stopwatch> : formatter<double>
+{
+ template<typename FormatContext>
+ auto format(const spdlog::stopwatch &sw, FormatContext &ctx) -> decltype(ctx.out())
+ {
+ return formatter<double>::format(sw.elapsed().count(), ctx);
+ }
+};
+} // namespace fmt
diff --git a/include/spdlog/tweakme.h b/include/spdlog/tweakme.h
new file mode 100644
index 00000000..31e417ab
--- /dev/null
+++ b/include/spdlog/tweakme.h
@@ -0,0 +1,124 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+///////////////////////////////////////////////////////////////////////////////
+//
+// Edit this file to squeeze more performance, and to customize supported
+// features
+//
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Under Linux, the much faster CLOCK_REALTIME_COARSE clock can be used.
+// This clock is less accurate - can be off by dozens of millis - depending on
+// the kernel HZ.
+// Uncomment to use it instead of the regular clock.
+//
+// #define SPDLOG_CLOCK_COARSE
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment if thread id logging is not needed (i.e. no %t in the log pattern).
+// This will prevent spdlog from querying the thread id on each log call.
+//
+// WARNING: If the log pattern contains thread id (i.e, %t) while this flag is
+// on, zero will be logged as thread id.
+//
+// #define SPDLOG_NO_THREAD_ID
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to prevent spdlog from using thread local storage.
+//
+// WARNING: if your program forks, UNCOMMENT this flag to prevent undefined
+// thread ids in the children logs.
+//
+// #define SPDLOG_NO_TLS
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to avoid spdlog's usage of atomic log levels
+// Use only if your code never modifies a logger's log levels concurrently by
+// different threads.
+//
+// #define SPDLOG_NO_ATOMIC_LEVELS
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to enable usage of wchar_t for file names on Windows.
+//
+// #define SPDLOG_WCHAR_FILENAMES
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to override default eol ("\n" or "\r\n" under Linux/Windows)
+//
+// #define SPDLOG_EOL ";-)\n"
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to override default folder separators ("/" or "\\/" under
+// Linux/Windows). Each character in the string is treated as a different
+// separator.
+//
+// #define SPDLOG_FOLDER_SEPS "\\"
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to use your own copy of the fmt library instead of spdlog's copy.
+// In this case spdlog will try to include <fmt/format.h> so set your -I flag
+// accordingly.
+//
+// #define SPDLOG_FMT_EXTERNAL
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to enable wchar_t support (convert to utf8)
+//
+// #define SPDLOG_WCHAR_TO_UTF8_SUPPORT
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to prevent child processes from inheriting log file descriptors
+//
+// #define SPDLOG_PREVENT_CHILD_FD
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to customize level names (e.g. "MT TRACE")
+//
+// #define SPDLOG_LEVEL_NAMES { "MY TRACE", "MY DEBUG", "MY INFO", "MY WARNING",
+// "MY ERROR", "MY CRITICAL", "OFF" }
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to customize short level names (e.g. "MT")
+// These can be longer than one character.
+//
+// #define SPDLOG_SHORT_LEVEL_NAMES { "T", "D", "I", "W", "E", "C", "O" }
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment to disable default logger creation.
+// This might save some (very) small initialization time if no default logger is needed.
+//
+// #define SPDLOG_DISABLE_DEFAULT_LOGGER
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment and set to compile time level with zero cost (default is INFO).
+// Macros like SPDLOG_DEBUG(..), SPDLOG_INFO(..) will expand to empty statements if not enabled
+//
+// #define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
+///////////////////////////////////////////////////////////////////////////////
+
+///////////////////////////////////////////////////////////////////////////////
+// Uncomment (and change if desired) macro to use for function names.
+// This is compiler dependent.
+// __PRETTY_FUNCTION__ might be nicer in clang/gcc, and __FUNCTION__ in msvc.
+// Defaults to __FUNCTION__ (should work on all compilers) if not defined.
+//
+// #define SPDLOG_FUNCTION __PRETTY_FUNCTION__
+///////////////////////////////////////////////////////////////////////////////
diff --git a/include/spdlog/version.h b/include/spdlog/version.h
new file mode 100644
index 00000000..828f78cb
--- /dev/null
+++ b/include/spdlog/version.h
@@ -0,0 +1,10 @@
+// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
+// Distributed under the MIT License (http://opensource.org/licenses/MIT)
+
+#pragma once
+
+#define SPDLOG_VER_MAJOR 1
+#define SPDLOG_VER_MINOR 8
+#define SPDLOG_VER_PATCH 5
+
+#define SPDLOG_VERSION (SPDLOG_VER_MAJOR * 10000 + SPDLOG_VER_MINOR * 100 + SPDLOG_VER_PATCH)